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/LangOptions.h"
27 #include "clang/Basic/TypeTraits.h"
28 #include "llvm/ADT/APFloat.h"
29 #include "llvm/ADT/APSInt.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/StringRef.h"
32 #include "llvm/Support/Compiler.h"
38 class CXXBaseSpecifier;
39 class CXXMemberCallExpr;
40 class CXXOperatorCallExpr;
44 class MaterializeTemporaryExpr;
46 class ObjCPropertyRefExpr;
47 class OpaqueValueExpr;
53 /// \brief A simple array of base specifiers.
54 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
56 /// \brief An adjustment to be made to the temporary created when emitting a
57 /// reference binding, which accesses a particular subobject of that temporary.
58 struct SubobjectAdjustment {
60 DerivedToBaseAdjustment,
62 MemberPointerAdjustment
66 const CastExpr *BasePath;
67 const CXXRecordDecl *DerivedClass;
71 const MemberPointerType *MPT;
76 struct DTB DerivedToBase;
81 SubobjectAdjustment(const CastExpr *BasePath,
82 const CXXRecordDecl *DerivedClass)
83 : Kind(DerivedToBaseAdjustment) {
84 DerivedToBase.BasePath = BasePath;
85 DerivedToBase.DerivedClass = DerivedClass;
88 SubobjectAdjustment(FieldDecl *Field)
89 : Kind(FieldAdjustment) {
93 SubobjectAdjustment(const MemberPointerType *MPT, Expr *RHS)
94 : Kind(MemberPointerAdjustment) {
100 /// Expr - This represents one expression. Note that Expr's are subclasses of
101 /// Stmt. This allows an expression to be transparently used any place a Stmt
104 class Expr : public Stmt {
108 Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK,
109 bool TD, bool VD, bool ID, bool ContainsUnexpandedParameterPack)
112 ExprBits.TypeDependent = TD;
113 ExprBits.ValueDependent = VD;
114 ExprBits.InstantiationDependent = ID;
115 ExprBits.ValueKind = VK;
116 ExprBits.ObjectKind = OK;
117 ExprBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
121 /// \brief Construct an empty expression.
122 explicit Expr(StmtClass SC, EmptyShell) : Stmt(SC) { }
125 QualType getType() const { return TR; }
126 void setType(QualType t) {
127 // In C++, the type of an expression is always adjusted so that it
128 // will not have 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;
153 /// isTypeDependent - Determines whether this expression is
154 /// type-dependent (C++ [temp.dep.expr]), which means that its type
155 /// could change from one template instantiation to the next. For
156 /// example, the expressions "x" and "x + y" are type-dependent in
157 /// the following code, but "y" is not type-dependent:
159 /// template<typename T>
160 /// void add(T x, int y) {
164 bool isTypeDependent() const { return ExprBits.TypeDependent; }
166 /// \brief Set whether this expression is type-dependent or not.
167 void setTypeDependent(bool TD) {
168 ExprBits.TypeDependent = TD;
171 /// \brief Whether this expression is instantiation-dependent, meaning that
172 /// it depends in some way on a template parameter, even if neither its type
173 /// nor (constant) value can change due to the template instantiation.
175 /// In the following example, the expression \c sizeof(sizeof(T() + T())) is
176 /// instantiation-dependent (since it involves a template parameter \c T), but
177 /// is neither type- nor value-dependent, since the type of the inner
178 /// \c sizeof is known (\c std::size_t) and therefore the size of the outer
179 /// \c sizeof is known.
182 /// template<typename T>
183 /// void f(T x, T y) {
184 /// sizeof(sizeof(T() + T());
188 bool isInstantiationDependent() const {
189 return ExprBits.InstantiationDependent;
192 /// \brief Set whether this expression is instantiation-dependent or not.
193 void setInstantiationDependent(bool ID) {
194 ExprBits.InstantiationDependent = ID;
197 /// \brief Whether this expression contains an unexpanded parameter
198 /// pack (for C++11 variadic templates).
200 /// Given the following function template:
203 /// template<typename F, typename ...Types>
204 /// void forward(const F &f, Types &&...args) {
205 /// f(static_cast<Types&&>(args)...);
209 /// The expressions \c args and \c static_cast<Types&&>(args) both
210 /// contain parameter packs.
211 bool containsUnexpandedParameterPack() const {
212 return ExprBits.ContainsUnexpandedParameterPack;
215 /// \brief Set the bit that describes whether this expression
216 /// contains an unexpanded parameter pack.
217 void setContainsUnexpandedParameterPack(bool PP = true) {
218 ExprBits.ContainsUnexpandedParameterPack = PP;
221 /// getExprLoc - Return the preferred location for the arrow when diagnosing
222 /// a problem with a generic expression.
223 SourceLocation getExprLoc() const LLVM_READONLY;
225 /// isUnusedResultAWarning - Return true if this immediate expression should
226 /// be warned about if the result is unused. If so, fill in expr, location,
227 /// and ranges with expr to warn on and source locations/ranges appropriate
229 bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc,
230 SourceRange &R1, SourceRange &R2,
231 ASTContext &Ctx) const;
233 /// isLValue - True if this expression is an "l-value" according to
234 /// the rules of the current language. C and C++ give somewhat
235 /// different rules for this concept, but in general, the result of
236 /// an l-value expression identifies a specific object whereas the
237 /// result of an r-value expression is a value detached from any
238 /// specific storage.
240 /// C++11 divides the concept of "r-value" into pure r-values
241 /// ("pr-values") and so-called expiring values ("x-values"), which
242 /// identify specific objects that can be safely cannibalized for
243 /// their resources. This is an unfortunate abuse of terminology on
244 /// the part of the C++ committee. In Clang, when we say "r-value",
245 /// we generally mean a pr-value.
246 bool isLValue() const { return getValueKind() == VK_LValue; }
247 bool isRValue() const { return getValueKind() == VK_RValue; }
248 bool isXValue() const { return getValueKind() == VK_XValue; }
249 bool isGLValue() const { return getValueKind() != VK_RValue; }
251 enum LValueClassification {
254 LV_IncompleteVoidType,
255 LV_DuplicateVectorComponents,
256 LV_InvalidExpression,
257 LV_InvalidMessageExpression,
259 LV_SubObjCPropertySetting,
263 /// Reasons why an expression might not be an l-value.
264 LValueClassification ClassifyLValue(ASTContext &Ctx) const;
266 enum isModifiableLvalueResult {
269 MLV_IncompleteVoidType,
270 MLV_DuplicateVectorComponents,
271 MLV_InvalidExpression,
272 MLV_LValueCast, // Specialized form of MLV_InvalidExpression.
277 MLV_NoSetterProperty,
279 MLV_SubObjCPropertySetting,
280 MLV_InvalidMessageExpression,
284 /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
285 /// does not have an incomplete type, does not have a const-qualified type,
286 /// and if it is a structure or union, does not have any member (including,
287 /// recursively, any member or element of all contained aggregates or unions)
288 /// with a const-qualified type.
290 /// \param Loc [in,out] - A source location which *may* be filled
291 /// in with the location of the expression making this a
292 /// non-modifiable lvalue, if specified.
293 isModifiableLvalueResult
294 isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc = nullptr) const;
296 /// \brief The return type of classify(). Represents the C++11 expression
298 class Classification {
300 /// \brief The various classification results. Most of these mean prvalue.
304 CL_Function, // Functions cannot be lvalues in C.
305 CL_Void, // Void cannot be an lvalue in C.
306 CL_AddressableVoid, // Void expression whose address can be taken in C.
307 CL_DuplicateVectorComponents, // A vector shuffle with dupes.
308 CL_MemberFunction, // An expression referring to a member function
309 CL_SubObjCPropertySetting,
310 CL_ClassTemporary, // A temporary of class type, or subobject thereof.
311 CL_ArrayTemporary, // A temporary of array type.
312 CL_ObjCMessageRValue, // ObjC message is an rvalue
313 CL_PRValue // A prvalue for any other reason, of any other type
315 /// \brief The results of modification testing.
316 enum ModifiableType {
317 CM_Untested, // testModifiable was false.
319 CM_RValue, // Not modifiable because it's an rvalue
320 CM_Function, // Not modifiable because it's a function; C++ only
321 CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext
322 CM_NoSetterProperty,// Implicit assignment to ObjC property without setter
333 unsigned short Modifiable;
335 explicit Classification(Kinds k, ModifiableType m)
336 : Kind(k), Modifiable(m)
342 Kinds getKind() const { return static_cast<Kinds>(Kind); }
343 ModifiableType getModifiable() const {
344 assert(Modifiable != CM_Untested && "Did not test for modifiability.");
345 return static_cast<ModifiableType>(Modifiable);
347 bool isLValue() const { return Kind == CL_LValue; }
348 bool isXValue() const { return Kind == CL_XValue; }
349 bool isGLValue() const { return Kind <= CL_XValue; }
350 bool isPRValue() const { return Kind >= CL_Function; }
351 bool isRValue() const { return Kind >= CL_XValue; }
352 bool isModifiable() const { return getModifiable() == CM_Modifiable; }
354 /// \brief Create a simple, modifiably lvalue
355 static Classification makeSimpleLValue() {
356 return Classification(CL_LValue, CM_Modifiable);
360 /// \brief Classify - Classify this expression according to the C++11
361 /// expression taxonomy.
363 /// C++11 defines ([basic.lval]) a new taxonomy of expressions to replace the
364 /// old lvalue vs rvalue. This function determines the type of expression this
365 /// is. There are three expression types:
366 /// - lvalues are classical lvalues as in C++03.
367 /// - prvalues are equivalent to rvalues in C++03.
368 /// - xvalues are expressions yielding unnamed rvalue references, e.g. a
369 /// function returning an rvalue reference.
370 /// lvalues and xvalues are collectively referred to as glvalues, while
371 /// prvalues and xvalues together form rvalues.
372 Classification Classify(ASTContext &Ctx) const {
373 return ClassifyImpl(Ctx, nullptr);
376 /// \brief ClassifyModifiable - Classify this expression according to the
377 /// C++11 expression taxonomy, and see if it is valid on the left side
378 /// of an assignment.
380 /// This function extends classify in that it also tests whether the
381 /// expression is modifiable (C99 6.3.2.1p1).
382 /// \param Loc A source location that might be filled with a relevant location
383 /// if the expression is not modifiable.
384 Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{
385 return ClassifyImpl(Ctx, &Loc);
388 /// getValueKindForType - Given a formal return or parameter type,
389 /// give its value kind.
390 static ExprValueKind getValueKindForType(QualType T) {
391 if (const ReferenceType *RT = T->getAs<ReferenceType>())
392 return (isa<LValueReferenceType>(RT)
394 : (RT->getPointeeType()->isFunctionType()
395 ? VK_LValue : VK_XValue));
399 /// getValueKind - The value kind that this expression produces.
400 ExprValueKind getValueKind() const {
401 return static_cast<ExprValueKind>(ExprBits.ValueKind);
404 /// getObjectKind - The object kind that this expression produces.
405 /// Object kinds are meaningful only for expressions that yield an
406 /// l-value or x-value.
407 ExprObjectKind getObjectKind() const {
408 return static_cast<ExprObjectKind>(ExprBits.ObjectKind);
411 bool isOrdinaryOrBitFieldObject() const {
412 ExprObjectKind OK = getObjectKind();
413 return (OK == OK_Ordinary || OK == OK_BitField);
416 /// setValueKind - Set the value kind produced by this expression.
417 void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; }
419 /// setObjectKind - Set the object kind produced by this expression.
420 void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; }
423 Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const;
427 /// \brief Returns true if this expression is a gl-value that
428 /// potentially refers to a bit-field.
430 /// In C++, whether a gl-value refers to a bitfield is essentially
431 /// an aspect of the value-kind type system.
432 bool refersToBitField() const { return getObjectKind() == OK_BitField; }
434 /// \brief If this expression refers to a bit-field, retrieve the
435 /// declaration of that bit-field.
437 /// Note that this returns a non-null pointer in subtly different
438 /// places than refersToBitField returns true. In particular, this can
439 /// return a non-null pointer even for r-values loaded from
440 /// bit-fields, but it will return null for a conditional bit-field.
441 FieldDecl *getSourceBitField();
443 const FieldDecl *getSourceBitField() const {
444 return const_cast<Expr*>(this)->getSourceBitField();
447 /// \brief If this expression is an l-value for an Objective C
448 /// property, find the underlying property reference expression.
449 const ObjCPropertyRefExpr *getObjCProperty() const;
451 /// \brief Check if this expression is the ObjC 'self' implicit parameter.
452 bool isObjCSelfExpr() const;
454 /// \brief Returns whether this expression refers to a vector element.
455 bool refersToVectorElement() const;
457 /// \brief Returns whether this expression refers to a global register
459 bool refersToGlobalRegisterVar() const;
461 /// \brief Returns whether this expression has a placeholder type.
462 bool hasPlaceholderType() const {
463 return getType()->isPlaceholderType();
466 /// \brief Returns whether this expression has a specific placeholder type.
467 bool hasPlaceholderType(BuiltinType::Kind K) const {
468 assert(BuiltinType::isPlaceholderTypeKind(K));
469 if (const BuiltinType *BT = dyn_cast<BuiltinType>(getType()))
470 return BT->getKind() == K;
474 /// isKnownToHaveBooleanValue - Return true if this is an integer expression
475 /// that is known to return 0 or 1. This happens for _Bool/bool expressions
476 /// but also int expressions which are produced by things like comparisons in
478 bool isKnownToHaveBooleanValue() const;
480 /// isIntegerConstantExpr - Return true if this expression is a valid integer
481 /// constant expression, and, if so, return its value in Result. If not a
482 /// valid i-c-e, return false and fill in Loc (if specified) with the location
483 /// of the invalid expression.
485 /// Note: This does not perform the implicit conversions required by C++11
487 bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx,
488 SourceLocation *Loc = nullptr,
489 bool isEvaluated = true) const;
490 bool isIntegerConstantExpr(const ASTContext &Ctx,
491 SourceLocation *Loc = nullptr) const;
493 /// isCXX98IntegralConstantExpr - Return true if this expression is an
494 /// integral constant expression in C++98. Can only be used in C++.
495 bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const;
497 /// isCXX11ConstantExpr - Return true if this expression is a constant
498 /// expression in C++11. Can only be used in C++.
500 /// Note: This does not perform the implicit conversions required by C++11
502 bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result = nullptr,
503 SourceLocation *Loc = nullptr) const;
505 /// isPotentialConstantExpr - Return true if this function's definition
506 /// might be usable in a constant expression in C++11, if it were marked
507 /// constexpr. Return false if the function can never produce a constant
508 /// expression, along with diagnostics describing why not.
509 static bool isPotentialConstantExpr(const FunctionDecl *FD,
511 PartialDiagnosticAt> &Diags);
513 /// isPotentialConstantExprUnevaluted - Return true if this expression might
514 /// be usable in a constant expression in C++11 in an unevaluated context, if
515 /// it were in function FD marked constexpr. Return false if the function can
516 /// never produce a constant expression, along with diagnostics describing
518 static bool isPotentialConstantExprUnevaluated(Expr *E,
519 const FunctionDecl *FD,
521 PartialDiagnosticAt> &Diags);
523 /// isConstantInitializer - Returns true if this expression can be emitted to
524 /// IR as a constant, and thus can be used as a constant initializer in C.
525 /// If this expression is not constant and Culprit is non-null,
526 /// it is used to store the address of first non constant expr.
527 bool isConstantInitializer(ASTContext &Ctx, bool ForRef,
528 const Expr **Culprit = nullptr) const;
530 /// EvalStatus is a struct with detailed info about an evaluation in progress.
532 /// \brief Whether the evaluated expression has side effects.
533 /// For example, (f() && 0) can be folded, but it still has side effects.
536 /// \brief Whether the evaluation hit undefined behavior.
537 /// For example, 1.0 / 0.0 can be folded to Inf, but has undefined behavior.
538 /// Likewise, INT_MAX + 1 can be folded to INT_MIN, but has UB.
539 bool HasUndefinedBehavior;
541 /// Diag - If this is non-null, it will be filled in with a stack of notes
542 /// indicating why evaluation failed (or why it failed to produce a constant
544 /// If the expression is unfoldable, the notes will indicate why it's not
545 /// foldable. If the expression is foldable, but not a constant expression,
546 /// the notes will describes why it isn't a constant expression. If the
547 /// expression *is* a constant expression, no notes will be produced.
548 SmallVectorImpl<PartialDiagnosticAt> *Diag;
551 : HasSideEffects(false), HasUndefinedBehavior(false), Diag(nullptr) {}
553 // hasSideEffects - Return true if the evaluated expression has
555 bool hasSideEffects() const {
556 return HasSideEffects;
560 /// EvalResult is a struct with detailed info about an evaluated expression.
561 struct EvalResult : EvalStatus {
562 /// Val - This is the value the expression can be folded to.
565 // isGlobalLValue - Return true if the evaluated lvalue expression
567 bool isGlobalLValue() const;
570 /// EvaluateAsRValue - Return true if this is a constant which we can fold to
571 /// an rvalue using any crazy technique (that has nothing to do with language
572 /// standards) that we want to, even if the expression has side-effects. If
573 /// this function returns true, it returns the folded constant in Result. If
574 /// the expression is a glvalue, an lvalue-to-rvalue conversion will be
576 bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const;
578 /// EvaluateAsBooleanCondition - Return true if this is a constant
579 /// which we we can fold and convert to a boolean condition using
580 /// any crazy technique that we want to, even if the expression has
582 bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx) const;
584 enum SideEffectsKind {
585 SE_NoSideEffects, ///< Strictly evaluate the expression.
586 SE_AllowUndefinedBehavior, ///< Allow UB that we can give a value, but not
587 ///< arbitrary unmodeled side effects.
588 SE_AllowSideEffects ///< Allow any unmodeled side effect.
591 /// EvaluateAsInt - Return true if this is a constant which we can fold and
592 /// convert to an integer, using any crazy technique that we want to.
593 bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx,
594 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
596 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
597 /// constant folded without side-effects, but discard the result.
598 bool isEvaluatable(const ASTContext &Ctx,
599 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
601 /// HasSideEffects - This routine returns true for all those expressions
602 /// which have any effect other than producing a value. Example is a function
603 /// call, volatile variable read, or throwing an exception. If
604 /// IncludePossibleEffects is false, this call treats certain expressions with
605 /// potential side effects (such as function call-like expressions,
606 /// instantiation-dependent expressions, or invocations from a macro) as not
607 /// having side effects.
608 bool HasSideEffects(const ASTContext &Ctx,
609 bool IncludePossibleEffects = true) const;
611 /// \brief Determine whether this expression involves a call to any function
612 /// that is not trivial.
613 bool hasNonTrivialCall(const ASTContext &Ctx) const;
615 /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded
616 /// integer. This must be called on an expression that constant folds to an
618 llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx,
619 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
621 void EvaluateForOverflow(const ASTContext &Ctx) const;
623 /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an
624 /// lvalue with link time known address, with no side-effects.
625 bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const;
627 /// EvaluateAsInitializer - Evaluate an expression as if it were the
628 /// initializer of the given declaration. Returns true if the initializer
629 /// can be folded to a constant, and produces any relevant notes. In C++11,
630 /// notes will be produced if the expression is not a constant expression.
631 bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx,
633 SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
635 /// EvaluateWithSubstitution - Evaluate an expression as if from the context
636 /// of a call to the given function with the given arguments, inside an
637 /// unevaluated context. Returns true if the expression could be folded to a
639 bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
640 const FunctionDecl *Callee,
641 ArrayRef<const Expr*> Args) const;
643 /// \brief If the current Expr is a pointer, this will try to statically
644 /// determine the number of bytes available where the pointer is pointing.
645 /// Returns true if all of the above holds and we were able to figure out the
646 /// size, false otherwise.
648 /// \param Type - How to evaluate the size of the Expr, as defined by the
649 /// "type" parameter of __builtin_object_size
650 bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
651 unsigned Type) const;
653 /// \brief Enumeration used to describe the kind of Null pointer constant
654 /// returned from \c isNullPointerConstant().
655 enum NullPointerConstantKind {
656 /// \brief Expression is not a Null pointer constant.
659 /// \brief Expression is a Null pointer constant built from a zero integer
660 /// expression that is not a simple, possibly parenthesized, zero literal.
661 /// C++ Core Issue 903 will classify these expressions as "not pointers"
662 /// once it is adopted.
663 /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
666 /// \brief Expression is a Null pointer constant built from a literal zero.
669 /// \brief Expression is a C++11 nullptr.
672 /// \brief Expression is a GNU-style __null constant.
676 /// \brief Enumeration used to describe how \c isNullPointerConstant()
677 /// should cope with value-dependent expressions.
678 enum NullPointerConstantValueDependence {
679 /// \brief Specifies that the expression should never be value-dependent.
680 NPC_NeverValueDependent = 0,
682 /// \brief Specifies that a value-dependent expression of integral or
683 /// dependent type should be considered a null pointer constant.
684 NPC_ValueDependentIsNull,
686 /// \brief Specifies that a value-dependent expression should be considered
687 /// to never be a null pointer constant.
688 NPC_ValueDependentIsNotNull
691 /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to
692 /// a Null pointer constant. The return value can further distinguish the
693 /// kind of NULL pointer constant that was detected.
694 NullPointerConstantKind isNullPointerConstant(
696 NullPointerConstantValueDependence NPC) const;
698 /// isOBJCGCCandidate - Return true if this expression may be used in a read/
700 bool isOBJCGCCandidate(ASTContext &Ctx) const;
702 /// \brief Returns true if this expression is a bound member function.
703 bool isBoundMemberFunction(ASTContext &Ctx) const;
705 /// \brief Given an expression of bound-member type, find the type
706 /// of the member. Returns null if this is an *overloaded* bound
707 /// member expression.
708 static QualType findBoundMemberType(const Expr *expr);
710 /// IgnoreImpCasts - Skip past any implicit casts which might
711 /// surround this expression. Only skips ImplicitCastExprs.
712 Expr *IgnoreImpCasts() LLVM_READONLY;
714 /// IgnoreImplicit - Skip past any implicit AST nodes which might
715 /// surround this expression.
716 Expr *IgnoreImplicit() LLVM_READONLY {
717 return cast<Expr>(Stmt::IgnoreImplicit());
720 const Expr *IgnoreImplicit() const LLVM_READONLY {
721 return const_cast<Expr*>(this)->IgnoreImplicit();
724 /// IgnoreParens - Ignore parentheses. If this Expr is a ParenExpr, return
725 /// its subexpression. If that subexpression is also a ParenExpr,
726 /// then this method recursively returns its subexpression, and so forth.
727 /// Otherwise, the method returns the current Expr.
728 Expr *IgnoreParens() LLVM_READONLY;
730 /// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr
731 /// or CastExprs, returning their operand.
732 Expr *IgnoreParenCasts() LLVM_READONLY;
734 /// Ignore casts. Strip off any CastExprs, returning their operand.
735 Expr *IgnoreCasts() LLVM_READONLY;
737 /// IgnoreParenImpCasts - Ignore parentheses and implicit casts. Strip off
738 /// any ParenExpr or ImplicitCastExprs, returning their operand.
739 Expr *IgnoreParenImpCasts() LLVM_READONLY;
741 /// IgnoreConversionOperator - Ignore conversion operator. If this Expr is a
742 /// call to a conversion operator, return the argument.
743 Expr *IgnoreConversionOperator() LLVM_READONLY;
745 const Expr *IgnoreConversionOperator() const LLVM_READONLY {
746 return const_cast<Expr*>(this)->IgnoreConversionOperator();
749 const Expr *IgnoreParenImpCasts() const LLVM_READONLY {
750 return const_cast<Expr*>(this)->IgnoreParenImpCasts();
753 /// Ignore parentheses and lvalue casts. Strip off any ParenExpr and
754 /// CastExprs that represent lvalue casts, returning their operand.
755 Expr *IgnoreParenLValueCasts() LLVM_READONLY;
757 const Expr *IgnoreParenLValueCasts() const LLVM_READONLY {
758 return const_cast<Expr*>(this)->IgnoreParenLValueCasts();
761 /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
762 /// value (including ptr->int casts of the same size). Strip off any
763 /// ParenExpr or CastExprs, returning their operand.
764 Expr *IgnoreParenNoopCasts(ASTContext &Ctx) LLVM_READONLY;
766 /// Ignore parentheses and derived-to-base casts.
767 Expr *ignoreParenBaseCasts() LLVM_READONLY;
769 const Expr *ignoreParenBaseCasts() const LLVM_READONLY {
770 return const_cast<Expr*>(this)->ignoreParenBaseCasts();
773 /// \brief Determine whether this expression is a default function argument.
775 /// Default arguments are implicitly generated in the abstract syntax tree
776 /// by semantic analysis for function calls, object constructions, etc. in
777 /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
778 /// this routine also looks through any implicit casts to determine whether
779 /// the expression is a default argument.
780 bool isDefaultArgument() const;
782 /// \brief Determine whether the result of this expression is a
783 /// temporary object of the given class type.
784 bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const;
786 /// \brief Whether this expression is an implicit reference to 'this' in C++.
787 bool isImplicitCXXThis() const;
789 const Expr *IgnoreImpCasts() const LLVM_READONLY {
790 return const_cast<Expr*>(this)->IgnoreImpCasts();
792 const Expr *IgnoreParens() const LLVM_READONLY {
793 return const_cast<Expr*>(this)->IgnoreParens();
795 const Expr *IgnoreParenCasts() const LLVM_READONLY {
796 return const_cast<Expr*>(this)->IgnoreParenCasts();
798 /// Strip off casts, but keep parentheses.
799 const Expr *IgnoreCasts() const LLVM_READONLY {
800 return const_cast<Expr*>(this)->IgnoreCasts();
803 const Expr *IgnoreParenNoopCasts(ASTContext &Ctx) const LLVM_READONLY {
804 return const_cast<Expr*>(this)->IgnoreParenNoopCasts(Ctx);
807 static bool hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs);
809 /// \brief For an expression of class type or pointer to class type,
810 /// return the most derived class decl the expression is known to refer to.
812 /// If this expression is a cast, this method looks through it to find the
813 /// most derived decl that can be inferred from the expression.
814 /// This is valid because derived-to-base conversions have undefined
815 /// behavior if the object isn't dynamically of the derived type.
816 const CXXRecordDecl *getBestDynamicClassType() const;
818 /// Walk outwards from an expression we want to bind a reference to and
819 /// find the expression whose lifetime needs to be extended. Record
820 /// the LHSs of comma expressions and adjustments needed along the path.
821 const Expr *skipRValueSubobjectAdjustments(
822 SmallVectorImpl<const Expr *> &CommaLHS,
823 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const;
825 static bool classof(const Stmt *T) {
826 return T->getStmtClass() >= firstExprConstant &&
827 T->getStmtClass() <= lastExprConstant;
831 //===----------------------------------------------------------------------===//
832 // Primary Expressions.
833 //===----------------------------------------------------------------------===//
835 /// OpaqueValueExpr - An expression referring to an opaque object of a
836 /// fixed type and value class. These don't correspond to concrete
837 /// syntax; instead they're used to express operations (usually copy
838 /// operations) on values whose source is generally obvious from
840 class OpaqueValueExpr : public Expr {
841 friend class ASTStmtReader;
846 OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK,
847 ExprObjectKind OK = OK_Ordinary,
848 Expr *SourceExpr = nullptr)
849 : Expr(OpaqueValueExprClass, T, VK, OK,
850 T->isDependentType(),
851 T->isDependentType() ||
852 (SourceExpr && SourceExpr->isValueDependent()),
853 T->isInstantiationDependentType(),
855 SourceExpr(SourceExpr), Loc(Loc) {
858 /// Given an expression which invokes a copy constructor --- i.e. a
859 /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups ---
860 /// find the OpaqueValueExpr that's the source of the construction.
861 static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr);
863 explicit OpaqueValueExpr(EmptyShell Empty)
864 : Expr(OpaqueValueExprClass, Empty) { }
866 /// \brief Retrieve the location of this expression.
867 SourceLocation getLocation() const { return Loc; }
869 SourceLocation getLocStart() const LLVM_READONLY {
870 return SourceExpr ? SourceExpr->getLocStart() : Loc;
872 SourceLocation getLocEnd() const LLVM_READONLY {
873 return SourceExpr ? SourceExpr->getLocEnd() : Loc;
875 SourceLocation getExprLoc() const LLVM_READONLY {
876 if (SourceExpr) return SourceExpr->getExprLoc();
880 child_range children() {
881 return child_range(child_iterator(), child_iterator());
884 /// The source expression of an opaque value expression is the
885 /// expression which originally generated the value. This is
886 /// provided as a convenience for analyses that don't wish to
887 /// precisely model the execution behavior of the program.
889 /// The source expression is typically set when building the
890 /// expression which binds the opaque value expression in the first
892 Expr *getSourceExpr() const { return SourceExpr; }
894 static bool classof(const Stmt *T) {
895 return T->getStmtClass() == OpaqueValueExprClass;
899 /// \brief A reference to a declared variable, function, enum, etc.
902 /// This encodes all the information about how a declaration is referenced
903 /// within an expression.
905 /// There are several optional constructs attached to DeclRefExprs only when
906 /// they apply in order to conserve memory. These are laid out past the end of
907 /// the object, and flags in the DeclRefExprBitfield track whether they exist:
909 /// DeclRefExprBits.HasQualifier:
910 /// Specifies when this declaration reference expression has a C++
911 /// nested-name-specifier.
912 /// DeclRefExprBits.HasFoundDecl:
913 /// Specifies when this declaration reference expression has a record of
914 /// a NamedDecl (different from the referenced ValueDecl) which was found
915 /// during name lookup and/or overload resolution.
916 /// DeclRefExprBits.HasTemplateKWAndArgsInfo:
917 /// Specifies when this declaration reference expression has an explicit
918 /// C++ template keyword and/or template argument list.
919 /// DeclRefExprBits.RefersToEnclosingVariableOrCapture
920 /// Specifies when this declaration reference expression (validly)
921 /// refers to an enclosed local or a captured variable.
922 class DeclRefExpr final
924 private llvm::TrailingObjects<DeclRefExpr, NestedNameSpecifierLoc,
925 NamedDecl *, ASTTemplateKWAndArgsInfo,
926 TemplateArgumentLoc> {
927 /// \brief The declaration that we are referencing.
930 /// \brief The location of the declaration name itself.
933 /// \brief Provides source/type location info for the declaration name
935 DeclarationNameLoc DNLoc;
937 size_t numTrailingObjects(OverloadToken<NestedNameSpecifierLoc>) const {
938 return hasQualifier() ? 1 : 0;
941 size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
942 return hasFoundDecl() ? 1 : 0;
945 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
946 return hasTemplateKWAndArgsInfo() ? 1 : 0;
949 /// \brief Test whether there is a distinct FoundDecl attached to the end of
951 bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; }
953 DeclRefExpr(const ASTContext &Ctx,
954 NestedNameSpecifierLoc QualifierLoc,
955 SourceLocation TemplateKWLoc,
956 ValueDecl *D, bool RefersToEnlosingVariableOrCapture,
957 const DeclarationNameInfo &NameInfo,
959 const TemplateArgumentListInfo *TemplateArgs,
960 QualType T, ExprValueKind VK);
962 /// \brief Construct an empty declaration reference expression.
963 explicit DeclRefExpr(EmptyShell Empty)
964 : Expr(DeclRefExprClass, Empty) { }
966 /// \brief Computes the type- and value-dependence flags for this
967 /// declaration reference expression.
968 void computeDependence(const ASTContext &C);
971 DeclRefExpr(ValueDecl *D, bool RefersToEnclosingVariableOrCapture, QualType T,
972 ExprValueKind VK, SourceLocation L,
973 const DeclarationNameLoc &LocInfo = DeclarationNameLoc())
974 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
975 D(D), Loc(L), DNLoc(LocInfo) {
976 DeclRefExprBits.HasQualifier = 0;
977 DeclRefExprBits.HasTemplateKWAndArgsInfo = 0;
978 DeclRefExprBits.HasFoundDecl = 0;
979 DeclRefExprBits.HadMultipleCandidates = 0;
980 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
981 RefersToEnclosingVariableOrCapture;
982 computeDependence(D->getASTContext());
986 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
987 SourceLocation TemplateKWLoc, ValueDecl *D,
988 bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc,
989 QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr,
990 const TemplateArgumentListInfo *TemplateArgs = nullptr);
993 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
994 SourceLocation TemplateKWLoc, ValueDecl *D,
995 bool RefersToEnclosingVariableOrCapture,
996 const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK,
997 NamedDecl *FoundD = nullptr,
998 const TemplateArgumentListInfo *TemplateArgs = nullptr);
1000 /// \brief Construct an empty declaration reference expression.
1001 static DeclRefExpr *CreateEmpty(const ASTContext &Context,
1004 bool HasTemplateKWAndArgsInfo,
1005 unsigned NumTemplateArgs);
1007 ValueDecl *getDecl() { return D; }
1008 const ValueDecl *getDecl() const { return D; }
1009 void setDecl(ValueDecl *NewD) { D = NewD; }
1011 DeclarationNameInfo getNameInfo() const {
1012 return DeclarationNameInfo(getDecl()->getDeclName(), Loc, DNLoc);
1015 SourceLocation getLocation() const { return Loc; }
1016 void setLocation(SourceLocation L) { Loc = L; }
1017 SourceLocation getLocStart() const LLVM_READONLY;
1018 SourceLocation getLocEnd() const LLVM_READONLY;
1020 /// \brief Determine whether this declaration reference was preceded by a
1021 /// C++ nested-name-specifier, e.g., \c N::foo.
1022 bool hasQualifier() const { return DeclRefExprBits.HasQualifier; }
1024 /// \brief If the name was qualified, retrieves the nested-name-specifier
1025 /// that precedes the name, with source-location information.
1026 NestedNameSpecifierLoc getQualifierLoc() const {
1027 if (!hasQualifier())
1028 return NestedNameSpecifierLoc();
1029 return *getTrailingObjects<NestedNameSpecifierLoc>();
1032 /// \brief If the name was qualified, retrieves the nested-name-specifier
1033 /// that precedes the name. Otherwise, returns NULL.
1034 NestedNameSpecifier *getQualifier() const {
1035 return getQualifierLoc().getNestedNameSpecifier();
1038 /// \brief Get the NamedDecl through which this reference occurred.
1040 /// This Decl may be different from the ValueDecl actually referred to in the
1041 /// presence of using declarations, etc. It always returns non-NULL, and may
1042 /// simple return the ValueDecl when appropriate.
1044 NamedDecl *getFoundDecl() {
1045 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1048 /// \brief Get the NamedDecl through which this reference occurred.
1049 /// See non-const variant.
1050 const NamedDecl *getFoundDecl() const {
1051 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1054 bool hasTemplateKWAndArgsInfo() const {
1055 return DeclRefExprBits.HasTemplateKWAndArgsInfo;
1058 /// \brief Retrieve the location of the template keyword preceding
1059 /// this name, if any.
1060 SourceLocation getTemplateKeywordLoc() const {
1061 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1062 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
1065 /// \brief Retrieve the location of the left angle bracket starting the
1066 /// explicit template argument list following the name, if any.
1067 SourceLocation getLAngleLoc() const {
1068 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1069 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
1072 /// \brief Retrieve the location of the right angle bracket ending the
1073 /// explicit template argument list following the name, if any.
1074 SourceLocation getRAngleLoc() const {
1075 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1076 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
1079 /// \brief Determines whether the name in this declaration reference
1080 /// was preceded by the template keyword.
1081 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
1083 /// \brief Determines whether this declaration reference was followed by an
1084 /// explicit template argument list.
1085 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
1087 /// \brief Copies the template arguments (if present) into the given
1089 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
1090 if (hasExplicitTemplateArgs())
1091 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
1092 getTrailingObjects<TemplateArgumentLoc>(), List);
1095 /// \brief Retrieve the template arguments provided as part of this
1097 const TemplateArgumentLoc *getTemplateArgs() const {
1098 if (!hasExplicitTemplateArgs())
1101 return getTrailingObjects<TemplateArgumentLoc>();
1104 /// \brief Retrieve the number of template arguments provided as part of this
1106 unsigned getNumTemplateArgs() const {
1107 if (!hasExplicitTemplateArgs())
1110 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
1113 /// \brief Returns true if this expression refers to a function that
1114 /// was resolved from an overloaded set having size greater than 1.
1115 bool hadMultipleCandidates() const {
1116 return DeclRefExprBits.HadMultipleCandidates;
1118 /// \brief Sets the flag telling whether this expression refers to
1119 /// a function that was resolved from an overloaded set having size
1121 void setHadMultipleCandidates(bool V = true) {
1122 DeclRefExprBits.HadMultipleCandidates = V;
1125 /// \brief Does this DeclRefExpr refer to an enclosing local or a captured
1127 bool refersToEnclosingVariableOrCapture() const {
1128 return DeclRefExprBits.RefersToEnclosingVariableOrCapture;
1131 static bool classof(const Stmt *T) {
1132 return T->getStmtClass() == DeclRefExprClass;
1136 child_range children() {
1137 return child_range(child_iterator(), child_iterator());
1140 friend TrailingObjects;
1141 friend class ASTStmtReader;
1142 friend class ASTStmtWriter;
1145 /// \brief [C99 6.4.2.2] - A predefined identifier such as __func__.
1146 class PredefinedExpr : public Expr {
1151 LFunction, // Same as Function, but as wide string.
1155 /// \brief The same as PrettyFunction, except that the
1156 /// 'virtual' keyword is omitted for virtual member functions.
1157 PrettyFunctionNoVirtual
1166 PredefinedExpr(SourceLocation L, QualType FNTy, IdentType IT,
1169 /// \brief Construct an empty predefined expression.
1170 explicit PredefinedExpr(EmptyShell Empty)
1171 : Expr(PredefinedExprClass, Empty), Loc(), Type(Func), FnName(nullptr) {}
1173 IdentType getIdentType() const { return Type; }
1175 SourceLocation getLocation() const { return Loc; }
1176 void setLocation(SourceLocation L) { Loc = L; }
1178 StringLiteral *getFunctionName();
1179 const StringLiteral *getFunctionName() const {
1180 return const_cast<PredefinedExpr *>(this)->getFunctionName();
1183 static StringRef getIdentTypeName(IdentType IT);
1184 static std::string ComputeName(IdentType IT, const Decl *CurrentDecl);
1186 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1187 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1189 static bool classof(const Stmt *T) {
1190 return T->getStmtClass() == PredefinedExprClass;
1194 child_range children() { return child_range(&FnName, &FnName + 1); }
1196 friend class ASTStmtReader;
1199 /// \brief Used by IntegerLiteral/FloatingLiteral to store the numeric without
1202 /// For large floats/integers, APFloat/APInt will allocate memory from the heap
1203 /// to represent these numbers. Unfortunately, when we use a BumpPtrAllocator
1204 /// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with
1205 /// the APFloat/APInt values will never get freed. APNumericStorage uses
1206 /// ASTContext's allocator for memory allocation.
1207 class APNumericStorage {
1209 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
1210 uint64_t *pVal; ///< Used to store the >64 bits integer value.
1214 bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; }
1216 APNumericStorage(const APNumericStorage &) = delete;
1217 void operator=(const APNumericStorage &) = delete;
1220 APNumericStorage() : VAL(0), BitWidth(0) { }
1222 llvm::APInt getIntValue() const {
1223 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1225 return llvm::APInt(BitWidth, NumWords, pVal);
1227 return llvm::APInt(BitWidth, VAL);
1229 void setIntValue(const ASTContext &C, const llvm::APInt &Val);
1232 class APIntStorage : private APNumericStorage {
1234 llvm::APInt getValue() const { return getIntValue(); }
1235 void setValue(const ASTContext &C, const llvm::APInt &Val) {
1236 setIntValue(C, Val);
1240 class APFloatStorage : private APNumericStorage {
1242 llvm::APFloat getValue(const llvm::fltSemantics &Semantics) const {
1243 return llvm::APFloat(Semantics, getIntValue());
1245 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1246 setIntValue(C, Val.bitcastToAPInt());
1250 class IntegerLiteral : public Expr, public APIntStorage {
1253 /// \brief Construct an empty integer literal.
1254 explicit IntegerLiteral(EmptyShell Empty)
1255 : Expr(IntegerLiteralClass, Empty) { }
1258 // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
1259 // or UnsignedLongLongTy
1260 IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1263 /// \brief Returns a new integer literal with value 'V' and type 'type'.
1264 /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy,
1265 /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V
1266 /// \param V - the value that the returned integer literal contains.
1267 static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V,
1268 QualType type, SourceLocation l);
1269 /// \brief Returns a new empty integer literal.
1270 static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty);
1272 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1273 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1275 /// \brief Retrieve the location of the literal.
1276 SourceLocation getLocation() const { return Loc; }
1278 void setLocation(SourceLocation Location) { Loc = Location; }
1280 static bool classof(const Stmt *T) {
1281 return T->getStmtClass() == IntegerLiteralClass;
1285 child_range children() {
1286 return child_range(child_iterator(), child_iterator());
1290 class CharacterLiteral : public Expr {
1292 enum CharacterKind {
1304 // type should be IntTy
1305 CharacterLiteral(unsigned value, CharacterKind kind, QualType type,
1307 : Expr(CharacterLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
1309 Value(value), Loc(l) {
1310 CharacterLiteralBits.Kind = kind;
1313 /// \brief Construct an empty character literal.
1314 CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
1316 SourceLocation getLocation() const { return Loc; }
1317 CharacterKind getKind() const {
1318 return static_cast<CharacterKind>(CharacterLiteralBits.Kind);
1321 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1322 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1324 unsigned getValue() const { return Value; }
1326 void setLocation(SourceLocation Location) { Loc = Location; }
1327 void setKind(CharacterKind kind) { CharacterLiteralBits.Kind = kind; }
1328 void setValue(unsigned Val) { Value = Val; }
1330 static bool classof(const Stmt *T) {
1331 return T->getStmtClass() == CharacterLiteralClass;
1335 child_range children() {
1336 return child_range(child_iterator(), child_iterator());
1340 class FloatingLiteral : public Expr, private APFloatStorage {
1343 FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact,
1344 QualType Type, SourceLocation L);
1346 /// \brief Construct an empty floating-point literal.
1347 explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty);
1350 static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V,
1351 bool isexact, QualType Type, SourceLocation L);
1352 static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty);
1354 llvm::APFloat getValue() const {
1355 return APFloatStorage::getValue(getSemantics());
1357 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1358 assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics");
1359 APFloatStorage::setValue(C, Val);
1362 /// Get a raw enumeration value representing the floating-point semantics of
1363 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1364 APFloatSemantics getRawSemantics() const {
1365 return static_cast<APFloatSemantics>(FloatingLiteralBits.Semantics);
1368 /// Set the raw enumeration value representing the floating-point semantics of
1369 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1370 void setRawSemantics(APFloatSemantics Sem) {
1371 FloatingLiteralBits.Semantics = Sem;
1374 /// Return the APFloat semantics this literal uses.
1375 const llvm::fltSemantics &getSemantics() const;
1377 /// Set the APFloat semantics this literal uses.
1378 void setSemantics(const llvm::fltSemantics &Sem);
1380 bool isExact() const { return FloatingLiteralBits.IsExact; }
1381 void setExact(bool E) { FloatingLiteralBits.IsExact = E; }
1383 /// getValueAsApproximateDouble - This returns the value as an inaccurate
1384 /// double. Note that this may cause loss of precision, but is useful for
1385 /// debugging dumps, etc.
1386 double getValueAsApproximateDouble() const;
1388 SourceLocation getLocation() const { return Loc; }
1389 void setLocation(SourceLocation L) { Loc = L; }
1391 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1392 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1394 static bool classof(const Stmt *T) {
1395 return T->getStmtClass() == FloatingLiteralClass;
1399 child_range children() {
1400 return child_range(child_iterator(), child_iterator());
1404 /// ImaginaryLiteral - We support imaginary integer and floating point literals,
1405 /// like "1.0i". We represent these as a wrapper around FloatingLiteral and
1406 /// IntegerLiteral classes. Instances of this class always have a Complex type
1407 /// whose element type matches the subexpression.
1409 class ImaginaryLiteral : public Expr {
1412 ImaginaryLiteral(Expr *val, QualType Ty)
1413 : Expr(ImaginaryLiteralClass, Ty, VK_RValue, OK_Ordinary, false, false,
1417 /// \brief Build an empty imaginary literal.
1418 explicit ImaginaryLiteral(EmptyShell Empty)
1419 : Expr(ImaginaryLiteralClass, Empty) { }
1421 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1422 Expr *getSubExpr() { return cast<Expr>(Val); }
1423 void setSubExpr(Expr *E) { Val = E; }
1425 SourceLocation getLocStart() const LLVM_READONLY { return Val->getLocStart(); }
1426 SourceLocation getLocEnd() const LLVM_READONLY { return Val->getLocEnd(); }
1428 static bool classof(const Stmt *T) {
1429 return T->getStmtClass() == ImaginaryLiteralClass;
1433 child_range children() { return child_range(&Val, &Val+1); }
1436 /// StringLiteral - This represents a string literal expression, e.g. "foo"
1437 /// or L"bar" (wide strings). The actual string is returned by getBytes()
1438 /// is NOT null-terminated, and the length of the string is determined by
1439 /// calling getByteLength(). The C type for a string is always a
1440 /// ConstantArrayType. In C++, the char type is const qualified, in C it is
1443 /// Note that strings in C can be formed by concatenation of multiple string
1444 /// literal pptokens in translation phase #6. This keeps track of the locations
1445 /// of each of these pieces.
1447 /// Strings in C can also be truncated and extended by assigning into arrays,
1448 /// e.g. with constructs like:
1449 /// char X[2] = "foobar";
1450 /// In this case, getByteLength() will return 6, but the string literal will
1451 /// have type "char[2]".
1452 class StringLiteral : public Expr {
1463 friend class ASTStmtReader;
1467 const uint16_t *asUInt16;
1468 const uint32_t *asUInt32;
1471 unsigned CharByteWidth : 4;
1473 unsigned IsPascal : 1;
1474 unsigned NumConcatenated;
1475 SourceLocation TokLocs[1];
1477 StringLiteral(QualType Ty) :
1478 Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false,
1481 static int mapCharByteWidth(TargetInfo const &target,StringKind k);
1484 /// This is the "fully general" constructor that allows representation of
1485 /// strings formed from multiple concatenated tokens.
1486 static StringLiteral *Create(const ASTContext &C, StringRef Str,
1487 StringKind Kind, bool Pascal, QualType Ty,
1488 const SourceLocation *Loc, unsigned NumStrs);
1490 /// Simple constructor for string literals made from one token.
1491 static StringLiteral *Create(const ASTContext &C, StringRef Str,
1492 StringKind Kind, bool Pascal, QualType Ty,
1493 SourceLocation Loc) {
1494 return Create(C, Str, Kind, Pascal, Ty, &Loc, 1);
1497 /// \brief Construct an empty string literal.
1498 static StringLiteral *CreateEmpty(const ASTContext &C, unsigned NumStrs);
1500 StringRef getString() const {
1501 assert(CharByteWidth==1
1502 && "This function is used in places that assume strings use char");
1503 return StringRef(StrData.asChar, getByteLength());
1506 /// Allow access to clients that need the byte representation, such as
1507 /// ASTWriterStmt::VisitStringLiteral().
1508 StringRef getBytes() const {
1509 // FIXME: StringRef may not be the right type to use as a result for this.
1510 if (CharByteWidth == 1)
1511 return StringRef(StrData.asChar, getByteLength());
1512 if (CharByteWidth == 4)
1513 return StringRef(reinterpret_cast<const char*>(StrData.asUInt32),
1515 assert(CharByteWidth == 2 && "unsupported CharByteWidth");
1516 return StringRef(reinterpret_cast<const char*>(StrData.asUInt16),
1520 void outputString(raw_ostream &OS) const;
1522 uint32_t getCodeUnit(size_t i) const {
1523 assert(i < Length && "out of bounds access");
1524 if (CharByteWidth == 1)
1525 return static_cast<unsigned char>(StrData.asChar[i]);
1526 if (CharByteWidth == 4)
1527 return StrData.asUInt32[i];
1528 assert(CharByteWidth == 2 && "unsupported CharByteWidth");
1529 return StrData.asUInt16[i];
1532 unsigned getByteLength() const { return CharByteWidth*Length; }
1533 unsigned getLength() const { return Length; }
1534 unsigned getCharByteWidth() const { return CharByteWidth; }
1536 /// \brief Sets the string data to the given string data.
1537 void setString(const ASTContext &C, StringRef Str,
1538 StringKind Kind, bool IsPascal);
1540 StringKind getKind() const { return static_cast<StringKind>(Kind); }
1543 bool isAscii() const { return Kind == Ascii; }
1544 bool isWide() const { return Kind == Wide; }
1545 bool isUTF8() const { return Kind == UTF8; }
1546 bool isUTF16() const { return Kind == UTF16; }
1547 bool isUTF32() const { return Kind == UTF32; }
1548 bool isPascal() const { return IsPascal; }
1550 bool containsNonAsciiOrNull() const {
1551 StringRef Str = getString();
1552 for (unsigned i = 0, e = Str.size(); i != e; ++i)
1553 if (!isASCII(Str[i]) || !Str[i])
1558 /// getNumConcatenated - Get the number of string literal tokens that were
1559 /// concatenated in translation phase #6 to form this string literal.
1560 unsigned getNumConcatenated() const { return NumConcatenated; }
1562 SourceLocation getStrTokenLoc(unsigned TokNum) const {
1563 assert(TokNum < NumConcatenated && "Invalid tok number");
1564 return TokLocs[TokNum];
1566 void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1567 assert(TokNum < NumConcatenated && "Invalid tok number");
1568 TokLocs[TokNum] = L;
1571 /// getLocationOfByte - Return a source location that points to the specified
1572 /// byte of this string literal.
1574 /// Strings are amazingly complex. They can be formed from multiple tokens
1575 /// and can have escape sequences in them in addition to the usual trigraph
1576 /// and escaped newline business. This routine handles this complexity.
1579 getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1580 const LangOptions &Features, const TargetInfo &Target,
1581 unsigned *StartToken = nullptr,
1582 unsigned *StartTokenByteOffset = nullptr) const;
1584 typedef const SourceLocation *tokloc_iterator;
1585 tokloc_iterator tokloc_begin() const { return TokLocs; }
1586 tokloc_iterator tokloc_end() const { return TokLocs + NumConcatenated; }
1588 SourceLocation getLocStart() const LLVM_READONLY { return TokLocs[0]; }
1589 SourceLocation getLocEnd() const LLVM_READONLY {
1590 return TokLocs[NumConcatenated - 1];
1593 static bool classof(const Stmt *T) {
1594 return T->getStmtClass() == StringLiteralClass;
1598 child_range children() {
1599 return child_range(child_iterator(), child_iterator());
1603 /// ParenExpr - This represents a parethesized expression, e.g. "(1)". This
1604 /// AST node is only formed if full location information is requested.
1605 class ParenExpr : public Expr {
1606 SourceLocation L, R;
1609 ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
1610 : Expr(ParenExprClass, val->getType(),
1611 val->getValueKind(), val->getObjectKind(),
1612 val->isTypeDependent(), val->isValueDependent(),
1613 val->isInstantiationDependent(),
1614 val->containsUnexpandedParameterPack()),
1615 L(l), R(r), Val(val) {}
1617 /// \brief Construct an empty parenthesized expression.
1618 explicit ParenExpr(EmptyShell Empty)
1619 : Expr(ParenExprClass, Empty) { }
1621 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1622 Expr *getSubExpr() { return cast<Expr>(Val); }
1623 void setSubExpr(Expr *E) { Val = E; }
1625 SourceLocation getLocStart() const LLVM_READONLY { return L; }
1626 SourceLocation getLocEnd() const LLVM_READONLY { return R; }
1628 /// \brief Get the location of the left parentheses '('.
1629 SourceLocation getLParen() const { return L; }
1630 void setLParen(SourceLocation Loc) { L = Loc; }
1632 /// \brief Get the location of the right parentheses ')'.
1633 SourceLocation getRParen() const { return R; }
1634 void setRParen(SourceLocation Loc) { R = Loc; }
1636 static bool classof(const Stmt *T) {
1637 return T->getStmtClass() == ParenExprClass;
1641 child_range children() { return child_range(&Val, &Val+1); }
1644 /// UnaryOperator - This represents the unary-expression's (except sizeof and
1645 /// alignof), the postinc/postdec operators from postfix-expression, and various
1648 /// Notes on various nodes:
1650 /// Real/Imag - These return the real/imag part of a complex operand. If
1651 /// applied to a non-complex value, the former returns its operand and the
1652 /// later returns zero in the type of the operand.
1654 class UnaryOperator : public Expr {
1656 typedef UnaryOperatorKind Opcode;
1664 UnaryOperator(Expr *input, Opcode opc, QualType type,
1665 ExprValueKind VK, ExprObjectKind OK, SourceLocation l)
1666 : Expr(UnaryOperatorClass, type, VK, OK,
1667 input->isTypeDependent() || type->isDependentType(),
1668 input->isValueDependent(),
1669 (input->isInstantiationDependent() ||
1670 type->isInstantiationDependentType()),
1671 input->containsUnexpandedParameterPack()),
1672 Opc(opc), Loc(l), Val(input) {}
1674 /// \brief Build an empty unary operator.
1675 explicit UnaryOperator(EmptyShell Empty)
1676 : Expr(UnaryOperatorClass, Empty), Opc(UO_AddrOf) { }
1678 Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
1679 void setOpcode(Opcode O) { Opc = O; }
1681 Expr *getSubExpr() const { return cast<Expr>(Val); }
1682 void setSubExpr(Expr *E) { Val = E; }
1684 /// getOperatorLoc - Return the location of the operator.
1685 SourceLocation getOperatorLoc() const { return Loc; }
1686 void setOperatorLoc(SourceLocation L) { Loc = L; }
1688 /// isPostfix - Return true if this is a postfix operation, like x++.
1689 static bool isPostfix(Opcode Op) {
1690 return Op == UO_PostInc || Op == UO_PostDec;
1693 /// isPrefix - Return true if this is a prefix operation, like --x.
1694 static bool isPrefix(Opcode Op) {
1695 return Op == UO_PreInc || Op == UO_PreDec;
1698 bool isPrefix() const { return isPrefix(getOpcode()); }
1699 bool isPostfix() const { return isPostfix(getOpcode()); }
1701 static bool isIncrementOp(Opcode Op) {
1702 return Op == UO_PreInc || Op == UO_PostInc;
1704 bool isIncrementOp() const {
1705 return isIncrementOp(getOpcode());
1708 static bool isDecrementOp(Opcode Op) {
1709 return Op == UO_PreDec || Op == UO_PostDec;
1711 bool isDecrementOp() const {
1712 return isDecrementOp(getOpcode());
1715 static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; }
1716 bool isIncrementDecrementOp() const {
1717 return isIncrementDecrementOp(getOpcode());
1720 static bool isArithmeticOp(Opcode Op) {
1721 return Op >= UO_Plus && Op <= UO_LNot;
1723 bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
1725 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1726 /// corresponds to, e.g. "sizeof" or "[pre]++"
1727 static StringRef getOpcodeStr(Opcode Op);
1729 /// \brief Retrieve the unary opcode that corresponds to the given
1730 /// overloaded operator.
1731 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
1733 /// \brief Retrieve the overloaded operator kind that corresponds to
1734 /// the given unary opcode.
1735 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
1737 SourceLocation getLocStart() const LLVM_READONLY {
1738 return isPostfix() ? Val->getLocStart() : Loc;
1740 SourceLocation getLocEnd() const LLVM_READONLY {
1741 return isPostfix() ? Loc : Val->getLocEnd();
1743 SourceLocation getExprLoc() const LLVM_READONLY { return Loc; }
1745 static bool classof(const Stmt *T) {
1746 return T->getStmtClass() == UnaryOperatorClass;
1750 child_range children() { return child_range(&Val, &Val+1); }
1753 /// Helper class for OffsetOfExpr.
1755 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
1756 class OffsetOfNode {
1758 /// \brief The kind of offsetof node we have.
1760 /// \brief An index into an array.
1764 /// \brief A field in a dependent type, known only by its name.
1766 /// \brief An implicit indirection through a C++ base class, when the
1767 /// field found is in a base class.
1772 enum { MaskBits = 2, Mask = 0x03 };
1774 /// \brief The source range that covers this part of the designator.
1777 /// \brief The data describing the designator, which comes in three
1778 /// different forms, depending on the lower two bits.
1779 /// - An unsigned index into the array of Expr*'s stored after this node
1780 /// in memory, for [constant-expression] designators.
1781 /// - A FieldDecl*, for references to a known field.
1782 /// - An IdentifierInfo*, for references to a field with a given name
1783 /// when the class type is dependent.
1784 /// - A CXXBaseSpecifier*, for references that look at a field in a
1789 /// \brief Create an offsetof node that refers to an array element.
1790 OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
1791 SourceLocation RBracketLoc)
1792 : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) {}
1794 /// \brief Create an offsetof node that refers to a field.
1795 OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field, SourceLocation NameLoc)
1796 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
1797 Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) {}
1799 /// \brief Create an offsetof node that refers to an identifier.
1800 OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
1801 SourceLocation NameLoc)
1802 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
1803 Data(reinterpret_cast<uintptr_t>(Name) | Identifier) {}
1805 /// \brief Create an offsetof node that refers into a C++ base class.
1806 explicit OffsetOfNode(const CXXBaseSpecifier *Base)
1807 : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
1809 /// \brief Determine what kind of offsetof node this is.
1810 Kind getKind() const { return static_cast<Kind>(Data & Mask); }
1812 /// \brief For an array element node, returns the index into the array
1814 unsigned getArrayExprIndex() const {
1815 assert(getKind() == Array);
1819 /// \brief For a field offsetof node, returns the field.
1820 FieldDecl *getField() const {
1821 assert(getKind() == Field);
1822 return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
1825 /// \brief For a field or identifier offsetof node, returns the name of
1827 IdentifierInfo *getFieldName() const;
1829 /// \brief For a base class node, returns the base specifier.
1830 CXXBaseSpecifier *getBase() const {
1831 assert(getKind() == Base);
1832 return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
1835 /// \brief Retrieve the source range that covers this offsetof node.
1837 /// For an array element node, the source range contains the locations of
1838 /// the square brackets. For a field or identifier node, the source range
1839 /// contains the location of the period (if there is one) and the
1841 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
1842 SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
1843 SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
1846 /// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
1847 /// offsetof(record-type, member-designator). For example, given:
1858 /// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
1860 class OffsetOfExpr final
1862 private llvm::TrailingObjects<OffsetOfExpr, OffsetOfNode, Expr *> {
1863 SourceLocation OperatorLoc, RParenLoc;
1865 TypeSourceInfo *TSInfo;
1866 // Number of sub-components (i.e. instances of OffsetOfNode).
1868 // Number of sub-expressions (i.e. array subscript expressions).
1871 size_t numTrailingObjects(OverloadToken<OffsetOfNode>) const {
1875 OffsetOfExpr(const ASTContext &C, QualType type,
1876 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1877 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
1878 SourceLocation RParenLoc);
1880 explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
1881 : Expr(OffsetOfExprClass, EmptyShell()),
1882 TSInfo(nullptr), NumComps(numComps), NumExprs(numExprs) {}
1886 static OffsetOfExpr *Create(const ASTContext &C, QualType type,
1887 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1888 ArrayRef<OffsetOfNode> comps,
1889 ArrayRef<Expr*> exprs, SourceLocation RParenLoc);
1891 static OffsetOfExpr *CreateEmpty(const ASTContext &C,
1892 unsigned NumComps, unsigned NumExprs);
1894 /// getOperatorLoc - Return the location of the operator.
1895 SourceLocation getOperatorLoc() const { return OperatorLoc; }
1896 void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
1898 /// \brief Return the location of the right parentheses.
1899 SourceLocation getRParenLoc() const { return RParenLoc; }
1900 void setRParenLoc(SourceLocation R) { RParenLoc = R; }
1902 TypeSourceInfo *getTypeSourceInfo() const {
1905 void setTypeSourceInfo(TypeSourceInfo *tsi) {
1909 const OffsetOfNode &getComponent(unsigned Idx) const {
1910 assert(Idx < NumComps && "Subscript out of range");
1911 return getTrailingObjects<OffsetOfNode>()[Idx];
1914 void setComponent(unsigned Idx, OffsetOfNode ON) {
1915 assert(Idx < NumComps && "Subscript out of range");
1916 getTrailingObjects<OffsetOfNode>()[Idx] = ON;
1919 unsigned getNumComponents() const {
1923 Expr* getIndexExpr(unsigned Idx) {
1924 assert(Idx < NumExprs && "Subscript out of range");
1925 return getTrailingObjects<Expr *>()[Idx];
1928 const Expr *getIndexExpr(unsigned Idx) const {
1929 assert(Idx < NumExprs && "Subscript out of range");
1930 return getTrailingObjects<Expr *>()[Idx];
1933 void setIndexExpr(unsigned Idx, Expr* E) {
1934 assert(Idx < NumComps && "Subscript out of range");
1935 getTrailingObjects<Expr *>()[Idx] = E;
1938 unsigned getNumExpressions() const {
1942 SourceLocation getLocStart() const LLVM_READONLY { return OperatorLoc; }
1943 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
1945 static bool classof(const Stmt *T) {
1946 return T->getStmtClass() == OffsetOfExprClass;
1950 child_range children() {
1951 Stmt **begin = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>());
1952 return child_range(begin, begin + NumExprs);
1954 friend TrailingObjects;
1957 /// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
1958 /// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and
1959 /// vec_step (OpenCL 1.1 6.11.12).
1960 class UnaryExprOrTypeTraitExpr : public Expr {
1965 SourceLocation OpLoc, RParenLoc;
1968 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo,
1969 QualType resultType, SourceLocation op,
1970 SourceLocation rp) :
1971 Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1972 false, // Never type-dependent (C++ [temp.dep.expr]p3).
1973 // Value-dependent if the argument is type-dependent.
1974 TInfo->getType()->isDependentType(),
1975 TInfo->getType()->isInstantiationDependentType(),
1976 TInfo->getType()->containsUnexpandedParameterPack()),
1977 OpLoc(op), RParenLoc(rp) {
1978 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1979 UnaryExprOrTypeTraitExprBits.IsType = true;
1980 Argument.Ty = TInfo;
1983 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E,
1984 QualType resultType, SourceLocation op,
1987 /// \brief Construct an empty sizeof/alignof expression.
1988 explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty)
1989 : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
1991 UnaryExprOrTypeTrait getKind() const {
1992 return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind);
1994 void setKind(UnaryExprOrTypeTrait K) { UnaryExprOrTypeTraitExprBits.Kind = K;}
1996 bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; }
1997 QualType getArgumentType() const {
1998 return getArgumentTypeInfo()->getType();
2000 TypeSourceInfo *getArgumentTypeInfo() const {
2001 assert(isArgumentType() && "calling getArgumentType() when arg is expr");
2004 Expr *getArgumentExpr() {
2005 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
2006 return static_cast<Expr*>(Argument.Ex);
2008 const Expr *getArgumentExpr() const {
2009 return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
2012 void setArgument(Expr *E) {
2014 UnaryExprOrTypeTraitExprBits.IsType = false;
2016 void setArgument(TypeSourceInfo *TInfo) {
2017 Argument.Ty = TInfo;
2018 UnaryExprOrTypeTraitExprBits.IsType = true;
2021 /// Gets the argument type, or the type of the argument expression, whichever
2023 QualType getTypeOfArgument() const {
2024 return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
2027 SourceLocation getOperatorLoc() const { return OpLoc; }
2028 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2030 SourceLocation getRParenLoc() const { return RParenLoc; }
2031 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2033 SourceLocation getLocStart() const LLVM_READONLY { return OpLoc; }
2034 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
2036 static bool classof(const Stmt *T) {
2037 return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
2041 child_range children();
2044 //===----------------------------------------------------------------------===//
2045 // Postfix Operators.
2046 //===----------------------------------------------------------------------===//
2048 /// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
2049 class ArraySubscriptExpr : public Expr {
2050 enum { LHS, RHS, END_EXPR=2 };
2051 Stmt* SubExprs[END_EXPR];
2052 SourceLocation RBracketLoc;
2054 ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
2055 ExprValueKind VK, ExprObjectKind OK,
2056 SourceLocation rbracketloc)
2057 : Expr(ArraySubscriptExprClass, t, VK, OK,
2058 lhs->isTypeDependent() || rhs->isTypeDependent(),
2059 lhs->isValueDependent() || rhs->isValueDependent(),
2060 (lhs->isInstantiationDependent() ||
2061 rhs->isInstantiationDependent()),
2062 (lhs->containsUnexpandedParameterPack() ||
2063 rhs->containsUnexpandedParameterPack())),
2064 RBracketLoc(rbracketloc) {
2065 SubExprs[LHS] = lhs;
2066 SubExprs[RHS] = rhs;
2069 /// \brief Create an empty array subscript expression.
2070 explicit ArraySubscriptExpr(EmptyShell Shell)
2071 : Expr(ArraySubscriptExprClass, Shell) { }
2073 /// An array access can be written A[4] or 4[A] (both are equivalent).
2074 /// - getBase() and getIdx() always present the normalized view: A[4].
2075 /// In this case getBase() returns "A" and getIdx() returns "4".
2076 /// - getLHS() and getRHS() present the syntactic view. e.g. for
2077 /// 4[A] getLHS() returns "4".
2078 /// Note: Because vector element access is also written A[4] we must
2079 /// predicate the format conversion in getBase and getIdx only on the
2080 /// the type of the RHS, as it is possible for the LHS to be a vector of
2082 Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
2083 const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2084 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2086 Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
2087 const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2088 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2091 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
2094 const Expr *getBase() const {
2095 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
2099 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
2102 const Expr *getIdx() const {
2103 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
2106 SourceLocation getLocStart() const LLVM_READONLY {
2107 return getLHS()->getLocStart();
2109 SourceLocation getLocEnd() const LLVM_READONLY { return RBracketLoc; }
2111 SourceLocation getRBracketLoc() const { return RBracketLoc; }
2112 void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
2114 SourceLocation getExprLoc() const LLVM_READONLY {
2115 return getBase()->getExprLoc();
2118 static bool classof(const Stmt *T) {
2119 return T->getStmtClass() == ArraySubscriptExprClass;
2123 child_range children() {
2124 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2128 /// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
2129 /// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
2130 /// while its subclasses may represent alternative syntax that (semantically)
2131 /// results in a function call. For example, CXXOperatorCallExpr is
2132 /// a subclass for overloaded operator calls that use operator syntax, e.g.,
2133 /// "str1 + str2" to resolve to a function call.
2134 class CallExpr : public Expr {
2135 enum { FN=0, PREARGS_START=1 };
2138 SourceLocation RParenLoc;
2141 // These versions of the constructor are for derived classes.
2142 CallExpr(const ASTContext& C, StmtClass SC, Expr *fn, unsigned NumPreArgs,
2143 ArrayRef<Expr*> args, QualType t, ExprValueKind VK,
2144 SourceLocation rparenloc);
2145 CallExpr(const ASTContext &C, StmtClass SC, unsigned NumPreArgs,
2148 Stmt *getPreArg(unsigned i) {
2149 assert(i < getNumPreArgs() && "Prearg access out of range!");
2150 return SubExprs[PREARGS_START+i];
2152 const Stmt *getPreArg(unsigned i) const {
2153 assert(i < getNumPreArgs() && "Prearg access out of range!");
2154 return SubExprs[PREARGS_START+i];
2156 void setPreArg(unsigned i, Stmt *PreArg) {
2157 assert(i < getNumPreArgs() && "Prearg access out of range!");
2158 SubExprs[PREARGS_START+i] = PreArg;
2161 unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
2164 CallExpr(const ASTContext& C, Expr *fn, ArrayRef<Expr*> args, QualType t,
2165 ExprValueKind VK, SourceLocation rparenloc);
2167 /// \brief Build an empty call expression.
2168 CallExpr(const ASTContext &C, StmtClass SC, EmptyShell Empty);
2170 const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); }
2171 Expr *getCallee() { return cast<Expr>(SubExprs[FN]); }
2172 void setCallee(Expr *F) { SubExprs[FN] = F; }
2174 Decl *getCalleeDecl();
2175 const Decl *getCalleeDecl() const {
2176 return const_cast<CallExpr*>(this)->getCalleeDecl();
2179 /// \brief If the callee is a FunctionDecl, return it. Otherwise return 0.
2180 FunctionDecl *getDirectCallee();
2181 const FunctionDecl *getDirectCallee() const {
2182 return const_cast<CallExpr*>(this)->getDirectCallee();
2185 /// getNumArgs - Return the number of actual arguments to this call.
2187 unsigned getNumArgs() const { return NumArgs; }
2189 /// \brief Retrieve the call arguments.
2191 return reinterpret_cast<Expr **>(SubExprs+getNumPreArgs()+PREARGS_START);
2193 const Expr *const *getArgs() const {
2194 return reinterpret_cast<Expr **>(SubExprs + getNumPreArgs() +
2198 /// getArg - Return the specified argument.
2199 Expr *getArg(unsigned Arg) {
2200 assert(Arg < NumArgs && "Arg access out of range!");
2201 return cast_or_null<Expr>(SubExprs[Arg + getNumPreArgs() + PREARGS_START]);
2203 const Expr *getArg(unsigned Arg) const {
2204 assert(Arg < NumArgs && "Arg access out of range!");
2205 return cast_or_null<Expr>(SubExprs[Arg + getNumPreArgs() + PREARGS_START]);
2208 /// setArg - Set the specified argument.
2209 void setArg(unsigned Arg, Expr *ArgExpr) {
2210 assert(Arg < NumArgs && "Arg access out of range!");
2211 SubExprs[Arg+getNumPreArgs()+PREARGS_START] = ArgExpr;
2214 /// setNumArgs - This changes the number of arguments present in this call.
2215 /// Any orphaned expressions are deleted by this, and any new operands are set
2217 void setNumArgs(const ASTContext& C, unsigned NumArgs);
2219 typedef ExprIterator arg_iterator;
2220 typedef ConstExprIterator const_arg_iterator;
2221 typedef llvm::iterator_range<arg_iterator> arg_range;
2222 typedef llvm::iterator_range<const_arg_iterator> arg_const_range;
2224 arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
2225 arg_const_range arguments() const {
2226 return arg_const_range(arg_begin(), arg_end());
2229 arg_iterator arg_begin() { return SubExprs+PREARGS_START+getNumPreArgs(); }
2230 arg_iterator arg_end() {
2231 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2233 const_arg_iterator arg_begin() const {
2234 return SubExprs+PREARGS_START+getNumPreArgs();
2236 const_arg_iterator arg_end() const {
2237 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2240 /// This method provides fast access to all the subexpressions of
2241 /// a CallExpr without going through the slower virtual child_iterator
2242 /// interface. This provides efficient reverse iteration of the
2243 /// subexpressions. This is currently used for CFG construction.
2244 ArrayRef<Stmt*> getRawSubExprs() {
2245 return llvm::makeArrayRef(SubExprs,
2246 getNumPreArgs() + PREARGS_START + getNumArgs());
2249 /// getNumCommas - Return the number of commas that must have been present in
2250 /// this function call.
2251 unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; }
2253 /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID
2254 /// of the callee. If not, return 0.
2255 unsigned getBuiltinCallee() const;
2257 /// \brief Returns \c true if this is a call to a builtin which does not
2258 /// evaluate side-effects within its arguments.
2259 bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const;
2261 /// getCallReturnType - Get the return type of the call expr. This is not
2262 /// always the type of the expr itself, if the return type is a reference
2264 QualType getCallReturnType(const ASTContext &Ctx) const;
2266 SourceLocation getRParenLoc() const { return RParenLoc; }
2267 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2269 SourceLocation getLocStart() const LLVM_READONLY;
2270 SourceLocation getLocEnd() const LLVM_READONLY;
2272 static bool classof(const Stmt *T) {
2273 return T->getStmtClass() >= firstCallExprConstant &&
2274 T->getStmtClass() <= lastCallExprConstant;
2278 child_range children() {
2279 return child_range(&SubExprs[0],
2280 &SubExprs[0]+NumArgs+getNumPreArgs()+PREARGS_START);
2284 /// Extra data stored in some MemberExpr objects.
2285 struct MemberExprNameQualifier {
2286 /// \brief The nested-name-specifier that qualifies the name, including
2287 /// source-location information.
2288 NestedNameSpecifierLoc QualifierLoc;
2290 /// \brief The DeclAccessPair through which the MemberDecl was found due to
2291 /// name qualifiers.
2292 DeclAccessPair FoundDecl;
2295 /// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F.
2297 class MemberExpr final
2299 private llvm::TrailingObjects<MemberExpr, MemberExprNameQualifier,
2300 ASTTemplateKWAndArgsInfo,
2301 TemplateArgumentLoc> {
2302 /// Base - the expression for the base pointer or structure references. In
2303 /// X.F, this is "X".
2306 /// MemberDecl - This is the decl being referenced by the field/member name.
2307 /// In X.F, this is the decl referenced by F.
2308 ValueDecl *MemberDecl;
2310 /// MemberDNLoc - Provides source/type location info for the
2311 /// declaration name embedded in MemberDecl.
2312 DeclarationNameLoc MemberDNLoc;
2314 /// MemberLoc - This is the location of the member name.
2315 SourceLocation MemberLoc;
2317 /// This is the location of the -> or . in the expression.
2318 SourceLocation OperatorLoc;
2320 /// IsArrow - True if this is "X->F", false if this is "X.F".
2323 /// \brief True if this member expression used a nested-name-specifier to
2324 /// refer to the member, e.g., "x->Base::f", or found its member via a using
2325 /// declaration. When true, a MemberExprNameQualifier
2326 /// structure is allocated immediately after the MemberExpr.
2327 bool HasQualifierOrFoundDecl : 1;
2329 /// \brief True if this member expression specified a template keyword
2330 /// and/or a template argument list explicitly, e.g., x->f<int>,
2331 /// x->template f, x->template f<int>.
2332 /// When true, an ASTTemplateKWAndArgsInfo structure and its
2333 /// TemplateArguments (if any) are present.
2334 bool HasTemplateKWAndArgsInfo : 1;
2336 /// \brief True if this member expression refers to a method that
2337 /// was resolved from an overloaded set having size greater than 1.
2338 bool HadMultipleCandidates : 1;
2340 size_t numTrailingObjects(OverloadToken<MemberExprNameQualifier>) const {
2341 return HasQualifierOrFoundDecl ? 1 : 0;
2344 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
2345 return HasTemplateKWAndArgsInfo ? 1 : 0;
2349 MemberExpr(Expr *base, bool isarrow, SourceLocation operatorloc,
2350 ValueDecl *memberdecl, const DeclarationNameInfo &NameInfo,
2351 QualType ty, ExprValueKind VK, ExprObjectKind OK)
2352 : Expr(MemberExprClass, ty, VK, OK, base->isTypeDependent(),
2353 base->isValueDependent(), base->isInstantiationDependent(),
2354 base->containsUnexpandedParameterPack()),
2355 Base(base), MemberDecl(memberdecl), MemberDNLoc(NameInfo.getInfo()),
2356 MemberLoc(NameInfo.getLoc()), OperatorLoc(operatorloc),
2357 IsArrow(isarrow), HasQualifierOrFoundDecl(false),
2358 HasTemplateKWAndArgsInfo(false), HadMultipleCandidates(false) {
2359 assert(memberdecl->getDeclName() == NameInfo.getName());
2362 // NOTE: this constructor should be used only when it is known that
2363 // the member name can not provide additional syntactic info
2364 // (i.e., source locations for C++ operator names or type source info
2365 // for constructors, destructors and conversion operators).
2366 MemberExpr(Expr *base, bool isarrow, SourceLocation operatorloc,
2367 ValueDecl *memberdecl, SourceLocation l, QualType ty,
2368 ExprValueKind VK, ExprObjectKind OK)
2369 : Expr(MemberExprClass, ty, VK, OK, base->isTypeDependent(),
2370 base->isValueDependent(), base->isInstantiationDependent(),
2371 base->containsUnexpandedParameterPack()),
2372 Base(base), MemberDecl(memberdecl), MemberDNLoc(), MemberLoc(l),
2373 OperatorLoc(operatorloc), IsArrow(isarrow),
2374 HasQualifierOrFoundDecl(false), HasTemplateKWAndArgsInfo(false),
2375 HadMultipleCandidates(false) {}
2377 static MemberExpr *Create(const ASTContext &C, Expr *base, bool isarrow,
2378 SourceLocation OperatorLoc,
2379 NestedNameSpecifierLoc QualifierLoc,
2380 SourceLocation TemplateKWLoc, ValueDecl *memberdecl,
2381 DeclAccessPair founddecl,
2382 DeclarationNameInfo MemberNameInfo,
2383 const TemplateArgumentListInfo *targs, QualType ty,
2384 ExprValueKind VK, ExprObjectKind OK);
2386 void setBase(Expr *E) { Base = E; }
2387 Expr *getBase() const { return cast<Expr>(Base); }
2389 /// \brief Retrieve the member declaration to which this expression refers.
2391 /// The returned declaration will either be a FieldDecl or (in C++)
2392 /// a CXXMethodDecl.
2393 ValueDecl *getMemberDecl() const { return MemberDecl; }
2394 void setMemberDecl(ValueDecl *D) { MemberDecl = D; }
2396 /// \brief Retrieves the declaration found by lookup.
2397 DeclAccessPair getFoundDecl() const {
2398 if (!HasQualifierOrFoundDecl)
2399 return DeclAccessPair::make(getMemberDecl(),
2400 getMemberDecl()->getAccess());
2401 return getTrailingObjects<MemberExprNameQualifier>()->FoundDecl;
2404 /// \brief Determines whether this member expression actually had
2405 /// a C++ nested-name-specifier prior to the name of the member, e.g.,
2407 bool hasQualifier() const { return getQualifier() != nullptr; }
2409 /// \brief If the member name was qualified, retrieves the
2410 /// nested-name-specifier that precedes the member name, with source-location
2412 NestedNameSpecifierLoc getQualifierLoc() const {
2413 if (!HasQualifierOrFoundDecl)
2414 return NestedNameSpecifierLoc();
2416 return getTrailingObjects<MemberExprNameQualifier>()->QualifierLoc;
2419 /// \brief If the member name was qualified, retrieves the
2420 /// nested-name-specifier that precedes the member name. Otherwise, returns
2422 NestedNameSpecifier *getQualifier() const {
2423 return getQualifierLoc().getNestedNameSpecifier();
2426 /// \brief Retrieve the location of the template keyword preceding
2427 /// the member name, if any.
2428 SourceLocation getTemplateKeywordLoc() const {
2429 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2430 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
2433 /// \brief Retrieve the location of the left angle bracket starting the
2434 /// explicit template argument list following the member name, if any.
2435 SourceLocation getLAngleLoc() const {
2436 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2437 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
2440 /// \brief Retrieve the location of the right angle bracket ending the
2441 /// explicit template argument list following the member name, if any.
2442 SourceLocation getRAngleLoc() const {
2443 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2444 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
2447 /// Determines whether the member name was preceded by the template keyword.
2448 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
2450 /// \brief Determines whether the member name was followed by an
2451 /// explicit template argument list.
2452 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
2454 /// \brief Copies the template arguments (if present) into the given
2456 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
2457 if (hasExplicitTemplateArgs())
2458 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
2459 getTrailingObjects<TemplateArgumentLoc>(), List);
2462 /// \brief Retrieve the template arguments provided as part of this
2464 const TemplateArgumentLoc *getTemplateArgs() const {
2465 if (!hasExplicitTemplateArgs())
2468 return getTrailingObjects<TemplateArgumentLoc>();
2471 /// \brief Retrieve the number of template arguments provided as part of this
2473 unsigned getNumTemplateArgs() const {
2474 if (!hasExplicitTemplateArgs())
2477 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
2480 /// \brief Retrieve the member declaration name info.
2481 DeclarationNameInfo getMemberNameInfo() const {
2482 return DeclarationNameInfo(MemberDecl->getDeclName(),
2483 MemberLoc, MemberDNLoc);
2486 SourceLocation getOperatorLoc() const LLVM_READONLY { return OperatorLoc; }
2488 bool isArrow() const { return IsArrow; }
2489 void setArrow(bool A) { IsArrow = A; }
2491 /// getMemberLoc - Return the location of the "member", in X->F, it is the
2492 /// location of 'F'.
2493 SourceLocation getMemberLoc() const { return MemberLoc; }
2494 void setMemberLoc(SourceLocation L) { MemberLoc = L; }
2496 SourceLocation getLocStart() const LLVM_READONLY;
2497 SourceLocation getLocEnd() const LLVM_READONLY;
2499 SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; }
2501 /// \brief Determine whether the base of this explicit is implicit.
2502 bool isImplicitAccess() const {
2503 return getBase() && getBase()->isImplicitCXXThis();
2506 /// \brief Returns true if this member expression refers to a method that
2507 /// was resolved from an overloaded set having size greater than 1.
2508 bool hadMultipleCandidates() const {
2509 return HadMultipleCandidates;
2511 /// \brief Sets the flag telling whether this expression refers to
2512 /// a method that was resolved from an overloaded set having size
2514 void setHadMultipleCandidates(bool V = true) {
2515 HadMultipleCandidates = V;
2518 /// \brief Returns true if virtual dispatch is performed.
2519 /// If the member access is fully qualified, (i.e. X::f()), virtual
2520 /// dispatching is not performed. In -fapple-kext mode qualified
2521 /// calls to virtual method will still go through the vtable.
2522 bool performsVirtualDispatch(const LangOptions &LO) const {
2523 return LO.AppleKext || !hasQualifier();
2526 static bool classof(const Stmt *T) {
2527 return T->getStmtClass() == MemberExprClass;
2531 child_range children() { return child_range(&Base, &Base+1); }
2533 friend TrailingObjects;
2534 friend class ASTReader;
2535 friend class ASTStmtWriter;
2538 /// CompoundLiteralExpr - [C99 6.5.2.5]
2540 class CompoundLiteralExpr : public Expr {
2541 /// LParenLoc - If non-null, this is the location of the left paren in a
2542 /// compound literal like "(int){4}". This can be null if this is a
2543 /// synthesized compound expression.
2544 SourceLocation LParenLoc;
2546 /// The type as written. This can be an incomplete array type, in
2547 /// which case the actual expression type will be different.
2548 /// The int part of the pair stores whether this expr is file scope.
2549 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope;
2552 CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
2553 QualType T, ExprValueKind VK, Expr *init, bool fileScope)
2554 : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary,
2555 tinfo->getType()->isDependentType(),
2556 init->isValueDependent(),
2557 (init->isInstantiationDependent() ||
2558 tinfo->getType()->isInstantiationDependentType()),
2559 init->containsUnexpandedParameterPack()),
2560 LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {}
2562 /// \brief Construct an empty compound literal.
2563 explicit CompoundLiteralExpr(EmptyShell Empty)
2564 : Expr(CompoundLiteralExprClass, Empty) { }
2566 const Expr *getInitializer() const { return cast<Expr>(Init); }
2567 Expr *getInitializer() { return cast<Expr>(Init); }
2568 void setInitializer(Expr *E) { Init = E; }
2570 bool isFileScope() const { return TInfoAndScope.getInt(); }
2571 void setFileScope(bool FS) { TInfoAndScope.setInt(FS); }
2573 SourceLocation getLParenLoc() const { return LParenLoc; }
2574 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2576 TypeSourceInfo *getTypeSourceInfo() const {
2577 return TInfoAndScope.getPointer();
2579 void setTypeSourceInfo(TypeSourceInfo *tinfo) {
2580 TInfoAndScope.setPointer(tinfo);
2583 SourceLocation getLocStart() const LLVM_READONLY {
2584 // FIXME: Init should never be null.
2586 return SourceLocation();
2587 if (LParenLoc.isInvalid())
2588 return Init->getLocStart();
2591 SourceLocation getLocEnd() const LLVM_READONLY {
2592 // FIXME: Init should never be null.
2594 return SourceLocation();
2595 return Init->getLocEnd();
2598 static bool classof(const Stmt *T) {
2599 return T->getStmtClass() == CompoundLiteralExprClass;
2603 child_range children() { return child_range(&Init, &Init+1); }
2606 /// CastExpr - Base class for type casts, including both implicit
2607 /// casts (ImplicitCastExpr) and explicit casts that have some
2608 /// representation in the source code (ExplicitCastExpr's derived
2610 class CastExpr : public Expr {
2614 bool CastConsistency() const;
2616 const CXXBaseSpecifier * const *path_buffer() const {
2617 return const_cast<CastExpr*>(this)->path_buffer();
2619 CXXBaseSpecifier **path_buffer();
2621 void setBasePathSize(unsigned basePathSize) {
2622 CastExprBits.BasePathSize = basePathSize;
2623 assert(CastExprBits.BasePathSize == basePathSize &&
2624 "basePathSize doesn't fit in bits of CastExprBits.BasePathSize!");
2628 CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, const CastKind kind,
2629 Expr *op, unsigned BasePathSize)
2630 : Expr(SC, ty, VK, OK_Ordinary,
2631 // Cast expressions are type-dependent if the type is
2632 // dependent (C++ [temp.dep.expr]p3).
2633 ty->isDependentType(),
2634 // Cast expressions are value-dependent if the type is
2635 // dependent or if the subexpression is value-dependent.
2636 ty->isDependentType() || (op && op->isValueDependent()),
2637 (ty->isInstantiationDependentType() ||
2638 (op && op->isInstantiationDependent())),
2639 // An implicit cast expression doesn't (lexically) contain an
2640 // unexpanded pack, even if its target type does.
2641 ((SC != ImplicitCastExprClass &&
2642 ty->containsUnexpandedParameterPack()) ||
2643 (op && op->containsUnexpandedParameterPack()))),
2645 assert(kind != CK_Invalid && "creating cast with invalid cast kind");
2646 CastExprBits.Kind = kind;
2647 setBasePathSize(BasePathSize);
2648 assert(CastConsistency());
2651 /// \brief Construct an empty cast.
2652 CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize)
2654 setBasePathSize(BasePathSize);
2658 CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
2659 void setCastKind(CastKind K) { CastExprBits.Kind = K; }
2660 const char *getCastKindName() const;
2662 Expr *getSubExpr() { return cast<Expr>(Op); }
2663 const Expr *getSubExpr() const { return cast<Expr>(Op); }
2664 void setSubExpr(Expr *E) { Op = E; }
2666 /// \brief Retrieve the cast subexpression as it was written in the source
2667 /// code, looking through any implicit casts or other intermediate nodes
2668 /// introduced by semantic analysis.
2669 Expr *getSubExprAsWritten();
2670 const Expr *getSubExprAsWritten() const {
2671 return const_cast<CastExpr *>(this)->getSubExprAsWritten();
2674 typedef CXXBaseSpecifier **path_iterator;
2675 typedef const CXXBaseSpecifier * const *path_const_iterator;
2676 bool path_empty() const { return CastExprBits.BasePathSize == 0; }
2677 unsigned path_size() const { return CastExprBits.BasePathSize; }
2678 path_iterator path_begin() { return path_buffer(); }
2679 path_iterator path_end() { return path_buffer() + path_size(); }
2680 path_const_iterator path_begin() const { return path_buffer(); }
2681 path_const_iterator path_end() const { return path_buffer() + path_size(); }
2683 static bool classof(const Stmt *T) {
2684 return T->getStmtClass() >= firstCastExprConstant &&
2685 T->getStmtClass() <= lastCastExprConstant;
2689 child_range children() { return child_range(&Op, &Op+1); }
2692 /// ImplicitCastExpr - Allows us to explicitly represent implicit type
2693 /// conversions, which have no direct representation in the original
2694 /// source code. For example: converting T[]->T*, void f()->void
2695 /// (*f)(), float->double, short->int, etc.
2697 /// In C, implicit casts always produce rvalues. However, in C++, an
2698 /// implicit cast whose result is being bound to a reference will be
2699 /// an lvalue or xvalue. For example:
2703 /// class Derived : public Base { };
2704 /// Derived &&ref();
2705 /// void f(Derived d) {
2706 /// Base& b = d; // initializer is an ImplicitCastExpr
2707 /// // to an lvalue of type Base
2708 /// Base&& r = ref(); // initializer is an ImplicitCastExpr
2709 /// // to an xvalue of type Base
2712 class ImplicitCastExpr final
2714 private llvm::TrailingObjects<ImplicitCastExpr, CXXBaseSpecifier *> {
2716 ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
2717 unsigned BasePathLength, ExprValueKind VK)
2718 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) {
2721 /// \brief Construct an empty implicit cast.
2722 explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize)
2723 : CastExpr(ImplicitCastExprClass, Shell, PathSize) { }
2726 enum OnStack_t { OnStack };
2727 ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
2729 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) {
2732 static ImplicitCastExpr *Create(const ASTContext &Context, QualType T,
2733 CastKind Kind, Expr *Operand,
2734 const CXXCastPath *BasePath,
2737 static ImplicitCastExpr *CreateEmpty(const ASTContext &Context,
2740 SourceLocation getLocStart() const LLVM_READONLY {
2741 return getSubExpr()->getLocStart();
2743 SourceLocation getLocEnd() const LLVM_READONLY {
2744 return getSubExpr()->getLocEnd();
2747 static bool classof(const Stmt *T) {
2748 return T->getStmtClass() == ImplicitCastExprClass;
2751 friend TrailingObjects;
2752 friend class CastExpr;
2755 inline Expr *Expr::IgnoreImpCasts() {
2757 while (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
2758 e = ice->getSubExpr();
2762 /// ExplicitCastExpr - An explicit cast written in the source
2765 /// This class is effectively an abstract class, because it provides
2766 /// the basic representation of an explicitly-written cast without
2767 /// specifying which kind of cast (C cast, functional cast, static
2768 /// cast, etc.) was written; specific derived classes represent the
2769 /// particular style of cast and its location information.
2771 /// Unlike implicit casts, explicit cast nodes have two different
2772 /// types: the type that was written into the source code, and the
2773 /// actual type of the expression as determined by semantic
2774 /// analysis. These types may differ slightly. For example, in C++ one
2775 /// can cast to a reference type, which indicates that the resulting
2776 /// expression will be an lvalue or xvalue. The reference type, however,
2777 /// will not be used as the type of the expression.
2778 class ExplicitCastExpr : public CastExpr {
2779 /// TInfo - Source type info for the (written) type
2780 /// this expression is casting to.
2781 TypeSourceInfo *TInfo;
2784 ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK,
2785 CastKind kind, Expr *op, unsigned PathSize,
2786 TypeSourceInfo *writtenTy)
2787 : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {}
2789 /// \brief Construct an empty explicit cast.
2790 ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
2791 : CastExpr(SC, Shell, PathSize) { }
2794 /// getTypeInfoAsWritten - Returns the type source info for the type
2795 /// that this expression is casting to.
2796 TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
2797 void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
2799 /// getTypeAsWritten - Returns the type that this expression is
2800 /// casting to, as written in the source code.
2801 QualType getTypeAsWritten() const { return TInfo->getType(); }
2803 static bool classof(const Stmt *T) {
2804 return T->getStmtClass() >= firstExplicitCastExprConstant &&
2805 T->getStmtClass() <= lastExplicitCastExprConstant;
2809 /// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
2810 /// cast in C++ (C++ [expr.cast]), which uses the syntax
2811 /// (Type)expr. For example: @c (int)f.
2812 class CStyleCastExpr final
2813 : public ExplicitCastExpr,
2814 private llvm::TrailingObjects<CStyleCastExpr, CXXBaseSpecifier *> {
2815 SourceLocation LPLoc; // the location of the left paren
2816 SourceLocation RPLoc; // the location of the right paren
2818 CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
2819 unsigned PathSize, TypeSourceInfo *writtenTy,
2820 SourceLocation l, SourceLocation r)
2821 : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
2822 writtenTy), LPLoc(l), RPLoc(r) {}
2824 /// \brief Construct an empty C-style explicit cast.
2825 explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize)
2826 : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { }
2829 static CStyleCastExpr *Create(const ASTContext &Context, QualType T,
2830 ExprValueKind VK, CastKind K,
2831 Expr *Op, const CXXCastPath *BasePath,
2832 TypeSourceInfo *WrittenTy, SourceLocation L,
2835 static CStyleCastExpr *CreateEmpty(const ASTContext &Context,
2838 SourceLocation getLParenLoc() const { return LPLoc; }
2839 void setLParenLoc(SourceLocation L) { LPLoc = L; }
2841 SourceLocation getRParenLoc() const { return RPLoc; }
2842 void setRParenLoc(SourceLocation L) { RPLoc = L; }
2844 SourceLocation getLocStart() const LLVM_READONLY { return LPLoc; }
2845 SourceLocation getLocEnd() const LLVM_READONLY {
2846 return getSubExpr()->getLocEnd();
2849 static bool classof(const Stmt *T) {
2850 return T->getStmtClass() == CStyleCastExprClass;
2853 friend TrailingObjects;
2854 friend class CastExpr;
2857 /// \brief A builtin binary operation expression such as "x + y" or "x <= y".
2859 /// This expression node kind describes a builtin binary operation,
2860 /// such as "x + y" for integer values "x" and "y". The operands will
2861 /// already have been converted to appropriate types (e.g., by
2862 /// performing promotions or conversions).
2864 /// In C++, where operators may be overloaded, a different kind of
2865 /// expression node (CXXOperatorCallExpr) is used to express the
2866 /// invocation of an overloaded operator with operator syntax. Within
2867 /// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
2868 /// used to store an expression "x + y" depends on the subexpressions
2869 /// for x and y. If neither x or y is type-dependent, and the "+"
2870 /// operator resolves to a built-in operation, BinaryOperator will be
2871 /// used to express the computation (x and y may still be
2872 /// value-dependent). If either x or y is type-dependent, or if the
2873 /// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
2874 /// be used to express the computation.
2875 class BinaryOperator : public Expr {
2877 typedef BinaryOperatorKind Opcode;
2882 // Records the FP_CONTRACT pragma status at the point that this binary
2883 // operator was parsed. This bit is only meaningful for operations on
2884 // floating point types. For all other types it should default to
2886 unsigned FPContractable : 1;
2887 SourceLocation OpLoc;
2889 enum { LHS, RHS, END_EXPR };
2890 Stmt* SubExprs[END_EXPR];
2893 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
2894 ExprValueKind VK, ExprObjectKind OK,
2895 SourceLocation opLoc, bool fpContractable)
2896 : Expr(BinaryOperatorClass, ResTy, VK, OK,
2897 lhs->isTypeDependent() || rhs->isTypeDependent(),
2898 lhs->isValueDependent() || rhs->isValueDependent(),
2899 (lhs->isInstantiationDependent() ||
2900 rhs->isInstantiationDependent()),
2901 (lhs->containsUnexpandedParameterPack() ||
2902 rhs->containsUnexpandedParameterPack())),
2903 Opc(opc), FPContractable(fpContractable), OpLoc(opLoc) {
2904 SubExprs[LHS] = lhs;
2905 SubExprs[RHS] = rhs;
2906 assert(!isCompoundAssignmentOp() &&
2907 "Use CompoundAssignOperator for compound assignments");
2910 /// \brief Construct an empty binary operator.
2911 explicit BinaryOperator(EmptyShell Empty)
2912 : Expr(BinaryOperatorClass, Empty), Opc(BO_Comma) { }
2914 SourceLocation getExprLoc() const LLVM_READONLY { return OpLoc; }
2915 SourceLocation getOperatorLoc() const { return OpLoc; }
2916 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2918 Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
2919 void setOpcode(Opcode O) { Opc = O; }
2921 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2922 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2923 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2924 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2926 SourceLocation getLocStart() const LLVM_READONLY {
2927 return getLHS()->getLocStart();
2929 SourceLocation getLocEnd() const LLVM_READONLY {
2930 return getRHS()->getLocEnd();
2933 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2934 /// corresponds to, e.g. "<<=".
2935 static StringRef getOpcodeStr(Opcode Op);
2937 StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
2939 /// \brief Retrieve the binary opcode that corresponds to the given
2940 /// overloaded operator.
2941 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
2943 /// \brief Retrieve the overloaded operator kind that corresponds to
2944 /// the given binary opcode.
2945 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
2947 /// predicates to categorize the respective opcodes.
2948 bool isPtrMemOp() const { return Opc == BO_PtrMemD || Opc == BO_PtrMemI; }
2949 static bool isMultiplicativeOp(Opcode Opc) {
2950 return Opc >= BO_Mul && Opc <= BO_Rem;
2952 bool isMultiplicativeOp() const { return isMultiplicativeOp(getOpcode()); }
2953 static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
2954 bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
2955 static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
2956 bool isShiftOp() const { return isShiftOp(getOpcode()); }
2958 static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
2959 bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
2961 static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
2962 bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
2964 static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
2965 bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
2967 static bool isComparisonOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_NE; }
2968 bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
2970 static Opcode negateComparisonOp(Opcode Opc) {
2973 llvm_unreachable("Not a comparsion operator.");
2974 case BO_LT: return BO_GE;
2975 case BO_GT: return BO_LE;
2976 case BO_LE: return BO_GT;
2977 case BO_GE: return BO_LT;
2978 case BO_EQ: return BO_NE;
2979 case BO_NE: return BO_EQ;
2983 static Opcode reverseComparisonOp(Opcode Opc) {
2986 llvm_unreachable("Not a comparsion operator.");
2987 case BO_LT: return BO_GT;
2988 case BO_GT: return BO_LT;
2989 case BO_LE: return BO_GE;
2990 case BO_GE: return BO_LE;
2997 static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
2998 bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
3000 static bool isAssignmentOp(Opcode Opc) {
3001 return Opc >= BO_Assign && Opc <= BO_OrAssign;
3003 bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); }
3005 static bool isCompoundAssignmentOp(Opcode Opc) {
3006 return Opc > BO_Assign && Opc <= BO_OrAssign;
3008 bool isCompoundAssignmentOp() const {
3009 return isCompoundAssignmentOp(getOpcode());
3011 static Opcode getOpForCompoundAssignment(Opcode Opc) {
3012 assert(isCompoundAssignmentOp(Opc));
3013 if (Opc >= BO_AndAssign)
3014 return Opcode(unsigned(Opc) - BO_AndAssign + BO_And);
3016 return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul);
3019 static bool isShiftAssignOp(Opcode Opc) {
3020 return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
3022 bool isShiftAssignOp() const {
3023 return isShiftAssignOp(getOpcode());
3026 static bool classof(const Stmt *S) {
3027 return S->getStmtClass() >= firstBinaryOperatorConstant &&
3028 S->getStmtClass() <= lastBinaryOperatorConstant;
3032 child_range children() {
3033 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3036 // Set the FP contractability status of this operator. Only meaningful for
3037 // operations on floating point types.
3038 void setFPContractable(bool FPC) { FPContractable = FPC; }
3040 // Get the FP contractability status of this operator. Only meaningful for
3041 // operations on floating point types.
3042 bool isFPContractable() const { return FPContractable; }
3045 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
3046 ExprValueKind VK, ExprObjectKind OK,
3047 SourceLocation opLoc, bool fpContractable, bool dead2)
3048 : Expr(CompoundAssignOperatorClass, ResTy, VK, OK,
3049 lhs->isTypeDependent() || rhs->isTypeDependent(),
3050 lhs->isValueDependent() || rhs->isValueDependent(),
3051 (lhs->isInstantiationDependent() ||
3052 rhs->isInstantiationDependent()),
3053 (lhs->containsUnexpandedParameterPack() ||
3054 rhs->containsUnexpandedParameterPack())),
3055 Opc(opc), FPContractable(fpContractable), OpLoc(opLoc) {
3056 SubExprs[LHS] = lhs;
3057 SubExprs[RHS] = rhs;
3060 BinaryOperator(StmtClass SC, EmptyShell Empty)
3061 : Expr(SC, Empty), Opc(BO_MulAssign) { }
3064 /// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
3065 /// track of the type the operation is performed in. Due to the semantics of
3066 /// these operators, the operands are promoted, the arithmetic performed, an
3067 /// implicit conversion back to the result type done, then the assignment takes
3068 /// place. This captures the intermediate type which the computation is done
3070 class CompoundAssignOperator : public BinaryOperator {
3071 QualType ComputationLHSType;
3072 QualType ComputationResultType;
3074 CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResType,
3075 ExprValueKind VK, ExprObjectKind OK,
3076 QualType CompLHSType, QualType CompResultType,
3077 SourceLocation OpLoc, bool fpContractable)
3078 : BinaryOperator(lhs, rhs, opc, ResType, VK, OK, OpLoc, fpContractable,
3080 ComputationLHSType(CompLHSType),
3081 ComputationResultType(CompResultType) {
3082 assert(isCompoundAssignmentOp() &&
3083 "Only should be used for compound assignments");
3086 /// \brief Build an empty compound assignment operator expression.
3087 explicit CompoundAssignOperator(EmptyShell Empty)
3088 : BinaryOperator(CompoundAssignOperatorClass, Empty) { }
3090 // The two computation types are the type the LHS is converted
3091 // to for the computation and the type of the result; the two are
3092 // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
3093 QualType getComputationLHSType() const { return ComputationLHSType; }
3094 void setComputationLHSType(QualType T) { ComputationLHSType = T; }
3096 QualType getComputationResultType() const { return ComputationResultType; }
3097 void setComputationResultType(QualType T) { ComputationResultType = T; }
3099 static bool classof(const Stmt *S) {
3100 return S->getStmtClass() == CompoundAssignOperatorClass;
3104 /// AbstractConditionalOperator - An abstract base class for
3105 /// ConditionalOperator and BinaryConditionalOperator.
3106 class AbstractConditionalOperator : public Expr {
3107 SourceLocation QuestionLoc, ColonLoc;
3108 friend class ASTStmtReader;
3111 AbstractConditionalOperator(StmtClass SC, QualType T,
3112 ExprValueKind VK, ExprObjectKind OK,
3113 bool TD, bool VD, bool ID,
3114 bool ContainsUnexpandedParameterPack,
3115 SourceLocation qloc,
3116 SourceLocation cloc)
3117 : Expr(SC, T, VK, OK, TD, VD, ID, ContainsUnexpandedParameterPack),
3118 QuestionLoc(qloc), ColonLoc(cloc) {}
3120 AbstractConditionalOperator(StmtClass SC, EmptyShell Empty)
3121 : Expr(SC, Empty) { }
3124 // getCond - Return the expression representing the condition for
3126 Expr *getCond() const;
3128 // getTrueExpr - Return the subexpression representing the value of
3129 // the expression if the condition evaluates to true.
3130 Expr *getTrueExpr() const;
3132 // getFalseExpr - Return the subexpression representing the value of
3133 // the expression if the condition evaluates to false. This is
3134 // the same as getRHS.
3135 Expr *getFalseExpr() const;
3137 SourceLocation getQuestionLoc() const { return QuestionLoc; }
3138 SourceLocation getColonLoc() const { return ColonLoc; }
3140 static bool classof(const Stmt *T) {
3141 return T->getStmtClass() == ConditionalOperatorClass ||
3142 T->getStmtClass() == BinaryConditionalOperatorClass;
3146 /// ConditionalOperator - The ?: ternary operator. The GNU "missing
3147 /// middle" extension is a BinaryConditionalOperator.
3148 class ConditionalOperator : public AbstractConditionalOperator {
3149 enum { COND, LHS, RHS, END_EXPR };
3150 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3152 friend class ASTStmtReader;
3154 ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
3155 SourceLocation CLoc, Expr *rhs,
3156 QualType t, ExprValueKind VK, ExprObjectKind OK)
3157 : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK,
3158 // FIXME: the type of the conditional operator doesn't
3159 // depend on the type of the conditional, but the standard
3160 // seems to imply that it could. File a bug!
3161 (lhs->isTypeDependent() || rhs->isTypeDependent()),
3162 (cond->isValueDependent() || lhs->isValueDependent() ||
3163 rhs->isValueDependent()),
3164 (cond->isInstantiationDependent() ||
3165 lhs->isInstantiationDependent() ||
3166 rhs->isInstantiationDependent()),
3167 (cond->containsUnexpandedParameterPack() ||
3168 lhs->containsUnexpandedParameterPack() ||
3169 rhs->containsUnexpandedParameterPack()),
3171 SubExprs[COND] = cond;
3172 SubExprs[LHS] = lhs;
3173 SubExprs[RHS] = rhs;
3176 /// \brief Build an empty conditional operator.
3177 explicit ConditionalOperator(EmptyShell Empty)
3178 : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
3180 // getCond - Return the expression representing the condition for
3182 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3184 // getTrueExpr - Return the subexpression representing the value of
3185 // the expression if the condition evaluates to true.
3186 Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); }
3188 // getFalseExpr - Return the subexpression representing the value of
3189 // the expression if the condition evaluates to false. This is
3190 // the same as getRHS.
3191 Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
3193 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3194 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3196 SourceLocation getLocStart() const LLVM_READONLY {
3197 return getCond()->getLocStart();
3199 SourceLocation getLocEnd() const LLVM_READONLY {
3200 return getRHS()->getLocEnd();
3203 static bool classof(const Stmt *T) {
3204 return T->getStmtClass() == ConditionalOperatorClass;
3208 child_range children() {
3209 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3213 /// BinaryConditionalOperator - The GNU extension to the conditional
3214 /// operator which allows the middle operand to be omitted.
3216 /// This is a different expression kind on the assumption that almost
3217 /// every client ends up needing to know that these are different.
3218 class BinaryConditionalOperator : public AbstractConditionalOperator {
3219 enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS };
3221 /// - the common condition/left-hand-side expression, which will be
3222 /// evaluated as the opaque value
3223 /// - the condition, expressed in terms of the opaque value
3224 /// - the left-hand-side, expressed in terms of the opaque value
3225 /// - the right-hand-side
3226 Stmt *SubExprs[NUM_SUBEXPRS];
3227 OpaqueValueExpr *OpaqueValue;
3229 friend class ASTStmtReader;
3231 BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue,
3232 Expr *cond, Expr *lhs, Expr *rhs,
3233 SourceLocation qloc, SourceLocation cloc,
3234 QualType t, ExprValueKind VK, ExprObjectKind OK)
3235 : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK,
3236 (common->isTypeDependent() || rhs->isTypeDependent()),
3237 (common->isValueDependent() || rhs->isValueDependent()),
3238 (common->isInstantiationDependent() ||
3239 rhs->isInstantiationDependent()),
3240 (common->containsUnexpandedParameterPack() ||
3241 rhs->containsUnexpandedParameterPack()),
3243 OpaqueValue(opaqueValue) {
3244 SubExprs[COMMON] = common;
3245 SubExprs[COND] = cond;
3246 SubExprs[LHS] = lhs;
3247 SubExprs[RHS] = rhs;
3248 assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value");
3251 /// \brief Build an empty conditional operator.
3252 explicit BinaryConditionalOperator(EmptyShell Empty)
3253 : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { }
3255 /// \brief getCommon - Return the common expression, written to the
3256 /// left of the condition. The opaque value will be bound to the
3257 /// result of this expression.
3258 Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); }
3260 /// \brief getOpaqueValue - Return the opaque value placeholder.
3261 OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
3263 /// \brief getCond - Return the condition expression; this is defined
3264 /// in terms of the opaque value.
3265 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3267 /// \brief getTrueExpr - Return the subexpression which will be
3268 /// evaluated if the condition evaluates to true; this is defined
3269 /// in terms of the opaque value.
3270 Expr *getTrueExpr() const {
3271 return cast<Expr>(SubExprs[LHS]);
3274 /// \brief getFalseExpr - Return the subexpression which will be
3275 /// evaluated if the condnition evaluates to false; this is
3276 /// defined in terms of the opaque value.
3277 Expr *getFalseExpr() const {
3278 return cast<Expr>(SubExprs[RHS]);
3281 SourceLocation getLocStart() const LLVM_READONLY {
3282 return getCommon()->getLocStart();
3284 SourceLocation getLocEnd() const LLVM_READONLY {
3285 return getFalseExpr()->getLocEnd();
3288 static bool classof(const Stmt *T) {
3289 return T->getStmtClass() == BinaryConditionalOperatorClass;
3293 child_range children() {
3294 return child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
3298 inline Expr *AbstractConditionalOperator::getCond() const {
3299 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3300 return co->getCond();
3301 return cast<BinaryConditionalOperator>(this)->getCond();
3304 inline Expr *AbstractConditionalOperator::getTrueExpr() const {
3305 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3306 return co->getTrueExpr();
3307 return cast<BinaryConditionalOperator>(this)->getTrueExpr();
3310 inline Expr *AbstractConditionalOperator::getFalseExpr() const {
3311 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3312 return co->getFalseExpr();
3313 return cast<BinaryConditionalOperator>(this)->getFalseExpr();
3316 /// AddrLabelExpr - The GNU address of label extension, representing &&label.
3317 class AddrLabelExpr : public Expr {
3318 SourceLocation AmpAmpLoc, LabelLoc;
3321 AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L,
3323 : Expr(AddrLabelExprClass, t, VK_RValue, OK_Ordinary, false, false, false,
3325 AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
3327 /// \brief Build an empty address of a label expression.
3328 explicit AddrLabelExpr(EmptyShell Empty)
3329 : Expr(AddrLabelExprClass, Empty) { }
3331 SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
3332 void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
3333 SourceLocation getLabelLoc() const { return LabelLoc; }
3334 void setLabelLoc(SourceLocation L) { LabelLoc = L; }
3336 SourceLocation getLocStart() const LLVM_READONLY { return AmpAmpLoc; }
3337 SourceLocation getLocEnd() const LLVM_READONLY { return LabelLoc; }
3339 LabelDecl *getLabel() const { return Label; }
3340 void setLabel(LabelDecl *L) { Label = L; }
3342 static bool classof(const Stmt *T) {
3343 return T->getStmtClass() == AddrLabelExprClass;
3347 child_range children() {
3348 return child_range(child_iterator(), child_iterator());
3352 /// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
3353 /// The StmtExpr contains a single CompoundStmt node, which it evaluates and
3354 /// takes the value of the last subexpression.
3356 /// A StmtExpr is always an r-value; values "returned" out of a
3357 /// StmtExpr will be copied.
3358 class StmtExpr : public Expr {
3360 SourceLocation LParenLoc, RParenLoc;
3362 // FIXME: Does type-dependence need to be computed differently?
3363 // FIXME: Do we need to compute instantiation instantiation-dependence for
3364 // statements? (ugh!)
3365 StmtExpr(CompoundStmt *substmt, QualType T,
3366 SourceLocation lp, SourceLocation rp) :
3367 Expr(StmtExprClass, T, VK_RValue, OK_Ordinary,
3368 T->isDependentType(), false, false, false),
3369 SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { }
3371 /// \brief Build an empty statement expression.
3372 explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
3374 CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
3375 const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
3376 void setSubStmt(CompoundStmt *S) { SubStmt = S; }
3378 SourceLocation getLocStart() const LLVM_READONLY { return LParenLoc; }
3379 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3381 SourceLocation getLParenLoc() const { return LParenLoc; }
3382 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3383 SourceLocation getRParenLoc() const { return RParenLoc; }
3384 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3386 static bool classof(const Stmt *T) {
3387 return T->getStmtClass() == StmtExprClass;
3391 child_range children() { return child_range(&SubStmt, &SubStmt+1); }
3394 /// ShuffleVectorExpr - clang-specific builtin-in function
3395 /// __builtin_shufflevector.
3396 /// This AST node represents a operator that does a constant
3397 /// shuffle, similar to LLVM's shufflevector instruction. It takes
3398 /// two vectors and a variable number of constant indices,
3399 /// and returns the appropriately shuffled vector.
3400 class ShuffleVectorExpr : public Expr {
3401 SourceLocation BuiltinLoc, RParenLoc;
3403 // SubExprs - the list of values passed to the __builtin_shufflevector
3404 // function. The first two are vectors, and the rest are constant
3405 // indices. The number of values in this list is always
3406 // 2+the number of indices in the vector type.
3411 ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args, QualType Type,
3412 SourceLocation BLoc, SourceLocation RP);
3414 /// \brief Build an empty vector-shuffle expression.
3415 explicit ShuffleVectorExpr(EmptyShell Empty)
3416 : Expr(ShuffleVectorExprClass, Empty), SubExprs(nullptr) { }
3418 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3419 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3421 SourceLocation getRParenLoc() const { return RParenLoc; }
3422 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3424 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3425 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3427 static bool classof(const Stmt *T) {
3428 return T->getStmtClass() == ShuffleVectorExprClass;
3431 /// getNumSubExprs - Return the size of the SubExprs array. This includes the
3432 /// constant expression, the actual arguments passed in, and the function
3434 unsigned getNumSubExprs() const { return NumExprs; }
3436 /// \brief Retrieve the array of expressions.
3437 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
3439 /// getExpr - Return the Expr at the specified index.
3440 Expr *getExpr(unsigned Index) {
3441 assert((Index < NumExprs) && "Arg access out of range!");
3442 return cast<Expr>(SubExprs[Index]);
3444 const Expr *getExpr(unsigned Index) const {
3445 assert((Index < NumExprs) && "Arg access out of range!");
3446 return cast<Expr>(SubExprs[Index]);
3449 void setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs);
3451 llvm::APSInt getShuffleMaskIdx(const ASTContext &Ctx, unsigned N) const {
3452 assert((N < NumExprs - 2) && "Shuffle idx out of range!");
3453 return getExpr(N+2)->EvaluateKnownConstInt(Ctx);
3457 child_range children() {
3458 return child_range(&SubExprs[0], &SubExprs[0]+NumExprs);
3462 /// ConvertVectorExpr - Clang builtin function __builtin_convertvector
3463 /// This AST node provides support for converting a vector type to another
3464 /// vector type of the same arity.
3465 class ConvertVectorExpr : public Expr {
3468 TypeSourceInfo *TInfo;
3469 SourceLocation BuiltinLoc, RParenLoc;
3471 friend class ASTReader;
3472 friend class ASTStmtReader;
3473 explicit ConvertVectorExpr(EmptyShell Empty) : Expr(ConvertVectorExprClass, Empty) {}
3476 ConvertVectorExpr(Expr* SrcExpr, TypeSourceInfo *TI, QualType DstType,
3477 ExprValueKind VK, ExprObjectKind OK,
3478 SourceLocation BuiltinLoc, SourceLocation RParenLoc)
3479 : Expr(ConvertVectorExprClass, DstType, VK, OK,
3480 DstType->isDependentType(),
3481 DstType->isDependentType() || SrcExpr->isValueDependent(),
3482 (DstType->isInstantiationDependentType() ||
3483 SrcExpr->isInstantiationDependent()),
3484 (DstType->containsUnexpandedParameterPack() ||
3485 SrcExpr->containsUnexpandedParameterPack())),
3486 SrcExpr(SrcExpr), TInfo(TI), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
3488 /// getSrcExpr - Return the Expr to be converted.
3489 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
3491 /// getTypeSourceInfo - Return the destination type.
3492 TypeSourceInfo *getTypeSourceInfo() const {
3495 void setTypeSourceInfo(TypeSourceInfo *ti) {
3499 /// getBuiltinLoc - Return the location of the __builtin_convertvector token.
3500 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3502 /// getRParenLoc - Return the location of final right parenthesis.
3503 SourceLocation getRParenLoc() const { return RParenLoc; }
3505 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3506 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3508 static bool classof(const Stmt *T) {
3509 return T->getStmtClass() == ConvertVectorExprClass;
3513 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
3516 /// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
3517 /// This AST node is similar to the conditional operator (?:) in C, with
3518 /// the following exceptions:
3519 /// - the test expression must be a integer constant expression.
3520 /// - the expression returned acts like the chosen subexpression in every
3521 /// visible way: the type is the same as that of the chosen subexpression,
3522 /// and all predicates (whether it's an l-value, whether it's an integer
3523 /// constant expression, etc.) return the same result as for the chosen
3525 class ChooseExpr : public Expr {
3526 enum { COND, LHS, RHS, END_EXPR };
3527 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3528 SourceLocation BuiltinLoc, RParenLoc;
3531 ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs,
3532 QualType t, ExprValueKind VK, ExprObjectKind OK,
3533 SourceLocation RP, bool condIsTrue,
3534 bool TypeDependent, bool ValueDependent)
3535 : Expr(ChooseExprClass, t, VK, OK, TypeDependent, ValueDependent,
3536 (cond->isInstantiationDependent() ||
3537 lhs->isInstantiationDependent() ||
3538 rhs->isInstantiationDependent()),
3539 (cond->containsUnexpandedParameterPack() ||
3540 lhs->containsUnexpandedParameterPack() ||
3541 rhs->containsUnexpandedParameterPack())),
3542 BuiltinLoc(BLoc), RParenLoc(RP), CondIsTrue(condIsTrue) {
3543 SubExprs[COND] = cond;
3544 SubExprs[LHS] = lhs;
3545 SubExprs[RHS] = rhs;
3548 /// \brief Build an empty __builtin_choose_expr.
3549 explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
3551 /// isConditionTrue - Return whether the condition is true (i.e. not
3553 bool isConditionTrue() const {
3554 assert(!isConditionDependent() &&
3555 "Dependent condition isn't true or false");
3558 void setIsConditionTrue(bool isTrue) { CondIsTrue = isTrue; }
3560 bool isConditionDependent() const {
3561 return getCond()->isTypeDependent() || getCond()->isValueDependent();
3564 /// getChosenSubExpr - Return the subexpression chosen according to the
3566 Expr *getChosenSubExpr() const {
3567 return isConditionTrue() ? getLHS() : getRHS();
3570 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3571 void setCond(Expr *E) { SubExprs[COND] = E; }
3572 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3573 void setLHS(Expr *E) { SubExprs[LHS] = E; }
3574 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3575 void setRHS(Expr *E) { SubExprs[RHS] = E; }
3577 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3578 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3580 SourceLocation getRParenLoc() const { return RParenLoc; }
3581 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3583 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3584 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3586 static bool classof(const Stmt *T) {
3587 return T->getStmtClass() == ChooseExprClass;
3591 child_range children() {
3592 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3596 /// GNUNullExpr - Implements the GNU __null extension, which is a name
3597 /// for a null pointer constant that has integral type (e.g., int or
3598 /// long) and is the same size and alignment as a pointer. The __null
3599 /// extension is typically only used by system headers, which define
3600 /// NULL as __null in C++ rather than using 0 (which is an integer
3601 /// that may not match the size of a pointer).
3602 class GNUNullExpr : public Expr {
3603 /// TokenLoc - The location of the __null keyword.
3604 SourceLocation TokenLoc;
3607 GNUNullExpr(QualType Ty, SourceLocation Loc)
3608 : Expr(GNUNullExprClass, Ty, VK_RValue, OK_Ordinary, false, false, false,
3612 /// \brief Build an empty GNU __null expression.
3613 explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
3615 /// getTokenLocation - The location of the __null token.
3616 SourceLocation getTokenLocation() const { return TokenLoc; }
3617 void setTokenLocation(SourceLocation L) { TokenLoc = L; }
3619 SourceLocation getLocStart() const LLVM_READONLY { return TokenLoc; }
3620 SourceLocation getLocEnd() const LLVM_READONLY { return TokenLoc; }
3622 static bool classof(const Stmt *T) {
3623 return T->getStmtClass() == GNUNullExprClass;
3627 child_range children() {
3628 return child_range(child_iterator(), child_iterator());
3632 /// Represents a call to the builtin function \c __builtin_va_arg.
3633 class VAArgExpr : public Expr {
3635 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfo;
3636 SourceLocation BuiltinLoc, RParenLoc;
3638 VAArgExpr(SourceLocation BLoc, Expr *e, TypeSourceInfo *TInfo,
3639 SourceLocation RPLoc, QualType t, bool IsMS)
3640 : Expr(VAArgExprClass, t, VK_RValue, OK_Ordinary, t->isDependentType(),
3641 false, (TInfo->getType()->isInstantiationDependentType() ||
3642 e->isInstantiationDependent()),
3643 (TInfo->getType()->containsUnexpandedParameterPack() ||
3644 e->containsUnexpandedParameterPack())),
3645 Val(e), TInfo(TInfo, IsMS), BuiltinLoc(BLoc), RParenLoc(RPLoc) {}
3647 /// Create an empty __builtin_va_arg expression.
3648 explicit VAArgExpr(EmptyShell Empty)
3649 : Expr(VAArgExprClass, Empty), Val(nullptr), TInfo(nullptr, false) {}
3651 const Expr *getSubExpr() const { return cast<Expr>(Val); }
3652 Expr *getSubExpr() { return cast<Expr>(Val); }
3653 void setSubExpr(Expr *E) { Val = E; }
3655 /// Returns whether this is really a Win64 ABI va_arg expression.
3656 bool isMicrosoftABI() const { return TInfo.getInt(); }
3657 void setIsMicrosoftABI(bool IsMS) { TInfo.setInt(IsMS); }
3659 TypeSourceInfo *getWrittenTypeInfo() const { return TInfo.getPointer(); }
3660 void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo.setPointer(TI); }
3662 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3663 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3665 SourceLocation getRParenLoc() const { return RParenLoc; }
3666 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3668 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3669 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3671 static bool classof(const Stmt *T) {
3672 return T->getStmtClass() == VAArgExprClass;
3676 child_range children() { return child_range(&Val, &Val+1); }
3679 /// @brief Describes an C or C++ initializer list.
3681 /// InitListExpr describes an initializer list, which can be used to
3682 /// initialize objects of different types, including
3683 /// struct/class/union types, arrays, and vectors. For example:
3686 /// struct foo x = { 1, { 2, 3 } };
3689 /// Prior to semantic analysis, an initializer list will represent the
3690 /// initializer list as written by the user, but will have the
3691 /// placeholder type "void". This initializer list is called the
3692 /// syntactic form of the initializer, and may contain C99 designated
3693 /// initializers (represented as DesignatedInitExprs), initializations
3694 /// of subobject members without explicit braces, and so on. Clients
3695 /// interested in the original syntax of the initializer list should
3696 /// use the syntactic form of the initializer list.
3698 /// After semantic analysis, the initializer list will represent the
3699 /// semantic form of the initializer, where the initializations of all
3700 /// subobjects are made explicit with nested InitListExpr nodes and
3701 /// C99 designators have been eliminated by placing the designated
3702 /// initializations into the subobject they initialize. Additionally,
3703 /// any "holes" in the initialization, where no initializer has been
3704 /// specified for a particular subobject, will be replaced with
3705 /// implicitly-generated ImplicitValueInitExpr expressions that
3706 /// value-initialize the subobjects. Note, however, that the
3707 /// initializer lists may still have fewer initializers than there are
3708 /// elements to initialize within the object.
3710 /// After semantic analysis has completed, given an initializer list,
3711 /// method isSemanticForm() returns true if and only if this is the
3712 /// semantic form of the initializer list (note: the same AST node
3713 /// may at the same time be the syntactic form).
3714 /// Given the semantic form of the initializer list, one can retrieve
3715 /// the syntactic form of that initializer list (when different)
3716 /// using method getSyntacticForm(); the method returns null if applied
3717 /// to a initializer list which is already in syntactic form.
3718 /// Similarly, given the syntactic form (i.e., an initializer list such
3719 /// that isSemanticForm() returns false), one can retrieve the semantic
3720 /// form using method getSemanticForm().
3721 /// Since many initializer lists have the same syntactic and semantic forms,
3722 /// getSyntacticForm() may return NULL, indicating that the current
3723 /// semantic initializer list also serves as its syntactic form.
3724 class InitListExpr : public Expr {
3725 // FIXME: Eliminate this vector in favor of ASTContext allocation
3726 typedef ASTVector<Stmt *> InitExprsTy;
3727 InitExprsTy InitExprs;
3728 SourceLocation LBraceLoc, RBraceLoc;
3730 /// The alternative form of the initializer list (if it exists).
3731 /// The int part of the pair stores whether this initializer list is
3732 /// in semantic form. If not null, the pointer points to:
3733 /// - the syntactic form, if this is in semantic form;
3734 /// - the semantic form, if this is in syntactic form.
3735 llvm::PointerIntPair<InitListExpr *, 1, bool> AltForm;
3738 /// If this initializer list initializes an array with more elements than
3739 /// there are initializers in the list, specifies an expression to be used
3740 /// for value initialization of the rest of the elements.
3742 /// If this initializer list initializes a union, specifies which
3743 /// field within the union will be initialized.
3744 llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit;
3747 InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
3748 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc);
3750 /// \brief Build an empty initializer list.
3751 explicit InitListExpr(EmptyShell Empty)
3752 : Expr(InitListExprClass, Empty) { }
3754 unsigned getNumInits() const { return InitExprs.size(); }
3756 /// \brief Retrieve the set of initializers.
3757 Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); }
3759 ArrayRef<Expr *> inits() {
3760 return llvm::makeArrayRef(getInits(), getNumInits());
3763 const Expr *getInit(unsigned Init) const {
3764 assert(Init < getNumInits() && "Initializer access out of range!");
3765 return cast_or_null<Expr>(InitExprs[Init]);
3768 Expr *getInit(unsigned Init) {
3769 assert(Init < getNumInits() && "Initializer access out of range!");
3770 return cast_or_null<Expr>(InitExprs[Init]);
3773 void setInit(unsigned Init, Expr *expr) {
3774 assert(Init < getNumInits() && "Initializer access out of range!");
3775 InitExprs[Init] = expr;
3778 ExprBits.TypeDependent |= expr->isTypeDependent();
3779 ExprBits.ValueDependent |= expr->isValueDependent();
3780 ExprBits.InstantiationDependent |= expr->isInstantiationDependent();
3781 ExprBits.ContainsUnexpandedParameterPack |=
3782 expr->containsUnexpandedParameterPack();
3786 /// \brief Reserve space for some number of initializers.
3787 void reserveInits(const ASTContext &C, unsigned NumInits);
3789 /// @brief Specify the number of initializers
3791 /// If there are more than @p NumInits initializers, the remaining
3792 /// initializers will be destroyed. If there are fewer than @p
3793 /// NumInits initializers, NULL expressions will be added for the
3794 /// unknown initializers.
3795 void resizeInits(const ASTContext &Context, unsigned NumInits);
3797 /// @brief Updates the initializer at index @p Init with the new
3798 /// expression @p expr, and returns the old expression at that
3801 /// When @p Init is out of range for this initializer list, the
3802 /// initializer list will be extended with NULL expressions to
3803 /// accommodate the new entry.
3804 Expr *updateInit(const ASTContext &C, unsigned Init, Expr *expr);
3806 /// \brief If this initializer list initializes an array with more elements
3807 /// than there are initializers in the list, specifies an expression to be
3808 /// used for value initialization of the rest of the elements.
3809 Expr *getArrayFiller() {
3810 return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>();
3812 const Expr *getArrayFiller() const {
3813 return const_cast<InitListExpr *>(this)->getArrayFiller();
3815 void setArrayFiller(Expr *filler);
3817 /// \brief Return true if this is an array initializer and its array "filler"
3819 bool hasArrayFiller() const { return getArrayFiller(); }
3821 /// \brief If this initializes a union, specifies which field in the
3822 /// union to initialize.
3824 /// Typically, this field is the first named field within the
3825 /// union. However, a designated initializer can specify the
3826 /// initialization of a different field within the union.
3827 FieldDecl *getInitializedFieldInUnion() {
3828 return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>();
3830 const FieldDecl *getInitializedFieldInUnion() const {
3831 return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion();
3833 void setInitializedFieldInUnion(FieldDecl *FD) {
3834 assert((FD == nullptr
3835 || getInitializedFieldInUnion() == nullptr
3836 || getInitializedFieldInUnion() == FD)
3837 && "Only one field of a union may be initialized at a time!");
3838 ArrayFillerOrUnionFieldInit = FD;
3841 // Explicit InitListExpr's originate from source code (and have valid source
3842 // locations). Implicit InitListExpr's are created by the semantic analyzer.
3844 return LBraceLoc.isValid() && RBraceLoc.isValid();
3847 // Is this an initializer for an array of characters, initialized by a string
3848 // literal or an @encode?
3849 bool isStringLiteralInit() const;
3851 SourceLocation getLBraceLoc() const { return LBraceLoc; }
3852 void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
3853 SourceLocation getRBraceLoc() const { return RBraceLoc; }
3854 void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
3856 bool isSemanticForm() const { return AltForm.getInt(); }
3857 InitListExpr *getSemanticForm() const {
3858 return isSemanticForm() ? nullptr : AltForm.getPointer();
3860 InitListExpr *getSyntacticForm() const {
3861 return isSemanticForm() ? AltForm.getPointer() : nullptr;
3864 void setSyntacticForm(InitListExpr *Init) {
3865 AltForm.setPointer(Init);
3866 AltForm.setInt(true);
3867 Init->AltForm.setPointer(this);
3868 Init->AltForm.setInt(false);
3871 bool hadArrayRangeDesignator() const {
3872 return InitListExprBits.HadArrayRangeDesignator != 0;
3874 void sawArrayRangeDesignator(bool ARD = true) {
3875 InitListExprBits.HadArrayRangeDesignator = ARD;
3878 SourceLocation getLocStart() const LLVM_READONLY;
3879 SourceLocation getLocEnd() const LLVM_READONLY;
3881 static bool classof(const Stmt *T) {
3882 return T->getStmtClass() == InitListExprClass;
3886 child_range children() {
3887 // FIXME: This does not include the array filler expression.
3888 if (InitExprs.empty())
3889 return child_range(child_iterator(), child_iterator());
3890 return child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size());
3893 typedef InitExprsTy::iterator iterator;
3894 typedef InitExprsTy::const_iterator const_iterator;
3895 typedef InitExprsTy::reverse_iterator reverse_iterator;
3896 typedef InitExprsTy::const_reverse_iterator const_reverse_iterator;
3898 iterator begin() { return InitExprs.begin(); }
3899 const_iterator begin() const { return InitExprs.begin(); }
3900 iterator end() { return InitExprs.end(); }
3901 const_iterator end() const { return InitExprs.end(); }
3902 reverse_iterator rbegin() { return InitExprs.rbegin(); }
3903 const_reverse_iterator rbegin() const { return InitExprs.rbegin(); }
3904 reverse_iterator rend() { return InitExprs.rend(); }
3905 const_reverse_iterator rend() const { return InitExprs.rend(); }
3907 friend class ASTStmtReader;
3908 friend class ASTStmtWriter;
3911 /// @brief Represents a C99 designated initializer expression.
3913 /// A designated initializer expression (C99 6.7.8) contains one or
3914 /// more designators (which can be field designators, array
3915 /// designators, or GNU array-range designators) followed by an
3916 /// expression that initializes the field or element(s) that the
3917 /// designators refer to. For example, given:
3924 /// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
3927 /// The InitListExpr contains three DesignatedInitExprs, the first of
3928 /// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
3929 /// designators, one array designator for @c [2] followed by one field
3930 /// designator for @c .y. The initialization expression will be 1.0.
3931 class DesignatedInitExpr final
3933 private llvm::TrailingObjects<DesignatedInitExpr, Stmt *> {
3935 /// \brief Forward declaration of the Designator class.
3939 /// The location of the '=' or ':' prior to the actual initializer
3941 SourceLocation EqualOrColonLoc;
3943 /// Whether this designated initializer used the GNU deprecated
3944 /// syntax rather than the C99 '=' syntax.
3947 /// The number of designators in this initializer expression.
3948 unsigned NumDesignators : 15;
3950 /// The number of subexpressions of this initializer expression,
3951 /// which contains both the initializer and any additional
3952 /// expressions used by array and array-range designators.
3953 unsigned NumSubExprs : 16;
3955 /// \brief The designators in this designated initialization
3957 Designator *Designators;
3960 DesignatedInitExpr(const ASTContext &C, QualType Ty, unsigned NumDesignators,
3961 const Designator *Designators,
3962 SourceLocation EqualOrColonLoc, bool GNUSyntax,
3963 ArrayRef<Expr*> IndexExprs, Expr *Init);
3965 explicit DesignatedInitExpr(unsigned NumSubExprs)
3966 : Expr(DesignatedInitExprClass, EmptyShell()),
3967 NumDesignators(0), NumSubExprs(NumSubExprs), Designators(nullptr) { }
3970 /// A field designator, e.g., ".x".
3971 struct FieldDesignator {
3972 /// Refers to the field that is being initialized. The low bit
3973 /// of this field determines whether this is actually a pointer
3974 /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
3975 /// initially constructed, a field designator will store an
3976 /// IdentifierInfo*. After semantic analysis has resolved that
3977 /// name, the field designator will instead store a FieldDecl*.
3978 uintptr_t NameOrField;
3980 /// The location of the '.' in the designated initializer.
3983 /// The location of the field name in the designated initializer.
3987 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
3988 struct ArrayOrRangeDesignator {
3989 /// Location of the first index expression within the designated
3990 /// initializer expression's list of subexpressions.
3992 /// The location of the '[' starting the array range designator.
3993 unsigned LBracketLoc;
3994 /// The location of the ellipsis separating the start and end
3995 /// indices. Only valid for GNU array-range designators.
3996 unsigned EllipsisLoc;
3997 /// The location of the ']' terminating the array range designator.
3998 unsigned RBracketLoc;
4001 /// @brief Represents a single C99 designator.
4003 /// @todo This class is infuriatingly similar to clang::Designator,
4004 /// but minor differences (storing indices vs. storing pointers)
4005 /// keep us from reusing it. Try harder, later, to rectify these
4008 /// @brief The kind of designator this describes.
4012 ArrayRangeDesignator
4016 /// A field designator, e.g., ".x".
4017 struct FieldDesignator Field;
4018 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
4019 struct ArrayOrRangeDesignator ArrayOrRange;
4021 friend class DesignatedInitExpr;
4026 /// @brief Initializes a field designator.
4027 Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
4028 SourceLocation FieldLoc)
4029 : Kind(FieldDesignator) {
4030 Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
4031 Field.DotLoc = DotLoc.getRawEncoding();
4032 Field.FieldLoc = FieldLoc.getRawEncoding();
4035 /// @brief Initializes an array designator.
4036 Designator(unsigned Index, SourceLocation LBracketLoc,
4037 SourceLocation RBracketLoc)
4038 : Kind(ArrayDesignator) {
4039 ArrayOrRange.Index = Index;
4040 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
4041 ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding();
4042 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
4045 /// @brief Initializes a GNU array-range designator.
4046 Designator(unsigned Index, SourceLocation LBracketLoc,
4047 SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
4048 : Kind(ArrayRangeDesignator) {
4049 ArrayOrRange.Index = Index;
4050 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
4051 ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding();
4052 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
4055 bool isFieldDesignator() const { return Kind == FieldDesignator; }
4056 bool isArrayDesignator() const { return Kind == ArrayDesignator; }
4057 bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
4059 IdentifierInfo *getFieldName() const;
4061 FieldDecl *getField() const {
4062 assert(Kind == FieldDesignator && "Only valid on a field designator");
4063 if (Field.NameOrField & 0x01)
4066 return reinterpret_cast<FieldDecl *>(Field.NameOrField);
4069 void setField(FieldDecl *FD) {
4070 assert(Kind == FieldDesignator && "Only valid on a field designator");
4071 Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
4074 SourceLocation getDotLoc() const {
4075 assert(Kind == FieldDesignator && "Only valid on a field designator");
4076 return SourceLocation::getFromRawEncoding(Field.DotLoc);
4079 SourceLocation getFieldLoc() const {
4080 assert(Kind == FieldDesignator && "Only valid on a field designator");
4081 return SourceLocation::getFromRawEncoding(Field.FieldLoc);
4084 SourceLocation getLBracketLoc() const {
4085 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4086 "Only valid on an array or array-range designator");
4087 return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc);
4090 SourceLocation getRBracketLoc() const {
4091 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4092 "Only valid on an array or array-range designator");
4093 return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc);
4096 SourceLocation getEllipsisLoc() const {
4097 assert(Kind == ArrayRangeDesignator &&
4098 "Only valid on an array-range designator");
4099 return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc);
4102 unsigned getFirstExprIndex() const {
4103 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4104 "Only valid on an array or array-range designator");
4105 return ArrayOrRange.Index;
4108 SourceLocation getLocStart() const LLVM_READONLY {
4109 if (Kind == FieldDesignator)
4110 return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc();
4112 return getLBracketLoc();
4114 SourceLocation getLocEnd() const LLVM_READONLY {
4115 return Kind == FieldDesignator ? getFieldLoc() : getRBracketLoc();
4117 SourceRange getSourceRange() const LLVM_READONLY {
4118 return SourceRange(getLocStart(), getLocEnd());
4122 static DesignatedInitExpr *Create(const ASTContext &C,
4123 Designator *Designators,
4124 unsigned NumDesignators,
4125 ArrayRef<Expr*> IndexExprs,
4126 SourceLocation EqualOrColonLoc,
4127 bool GNUSyntax, Expr *Init);
4129 static DesignatedInitExpr *CreateEmpty(const ASTContext &C,
4130 unsigned NumIndexExprs);
4132 /// @brief Returns the number of designators in this initializer.
4133 unsigned size() const { return NumDesignators; }
4135 // Iterator access to the designators.
4136 typedef Designator *designators_iterator;
4137 designators_iterator designators_begin() { return Designators; }
4138 designators_iterator designators_end() {
4139 return Designators + NumDesignators;
4142 typedef const Designator *const_designators_iterator;
4143 const_designators_iterator designators_begin() const { return Designators; }
4144 const_designators_iterator designators_end() const {
4145 return Designators + NumDesignators;
4148 typedef llvm::iterator_range<designators_iterator> designators_range;
4149 designators_range designators() {
4150 return designators_range(designators_begin(), designators_end());
4153 typedef llvm::iterator_range<const_designators_iterator>
4154 designators_const_range;
4155 designators_const_range designators() const {
4156 return designators_const_range(designators_begin(), designators_end());
4159 typedef std::reverse_iterator<designators_iterator>
4160 reverse_designators_iterator;
4161 reverse_designators_iterator designators_rbegin() {
4162 return reverse_designators_iterator(designators_end());
4164 reverse_designators_iterator designators_rend() {
4165 return reverse_designators_iterator(designators_begin());
4168 typedef std::reverse_iterator<const_designators_iterator>
4169 const_reverse_designators_iterator;
4170 const_reverse_designators_iterator designators_rbegin() const {
4171 return const_reverse_designators_iterator(designators_end());
4173 const_reverse_designators_iterator designators_rend() const {
4174 return const_reverse_designators_iterator(designators_begin());
4177 Designator *getDesignator(unsigned Idx) { return &designators_begin()[Idx]; }
4179 void setDesignators(const ASTContext &C, const Designator *Desigs,
4180 unsigned NumDesigs);
4182 Expr *getArrayIndex(const Designator &D) const;
4183 Expr *getArrayRangeStart(const Designator &D) const;
4184 Expr *getArrayRangeEnd(const Designator &D) const;
4186 /// @brief Retrieve the location of the '=' that precedes the
4187 /// initializer value itself, if present.
4188 SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
4189 void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
4191 /// @brief Determines whether this designated initializer used the
4192 /// deprecated GNU syntax for designated initializers.
4193 bool usesGNUSyntax() const { return GNUSyntax; }
4194 void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
4196 /// @brief Retrieve the initializer value.
4197 Expr *getInit() const {
4198 return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
4201 void setInit(Expr *init) {
4202 *child_begin() = init;
4205 /// \brief Retrieve the total number of subexpressions in this
4206 /// designated initializer expression, including the actual
4207 /// initialized value and any expressions that occur within array
4208 /// and array-range designators.
4209 unsigned getNumSubExprs() const { return NumSubExprs; }
4211 Expr *getSubExpr(unsigned Idx) const {
4212 assert(Idx < NumSubExprs && "Subscript out of range");
4213 return cast<Expr>(getTrailingObjects<Stmt *>()[Idx]);
4216 void setSubExpr(unsigned Idx, Expr *E) {
4217 assert(Idx < NumSubExprs && "Subscript out of range");
4218 getTrailingObjects<Stmt *>()[Idx] = E;
4221 /// \brief Replaces the designator at index @p Idx with the series
4222 /// of designators in [First, Last).
4223 void ExpandDesignator(const ASTContext &C, unsigned Idx,
4224 const Designator *First, const Designator *Last);
4226 SourceRange getDesignatorsSourceRange() const;
4228 SourceLocation getLocStart() const LLVM_READONLY;
4229 SourceLocation getLocEnd() const LLVM_READONLY;
4231 static bool classof(const Stmt *T) {
4232 return T->getStmtClass() == DesignatedInitExprClass;
4236 child_range children() {
4237 Stmt **begin = getTrailingObjects<Stmt *>();
4238 return child_range(begin, begin + NumSubExprs);
4241 friend TrailingObjects;
4244 /// \brief Represents a place-holder for an object not to be initialized by
4247 /// This only makes sense when it appears as part of an updater of a
4248 /// DesignatedInitUpdateExpr (see below). The base expression of a DIUE
4249 /// initializes a big object, and the NoInitExpr's mark the spots within the
4250 /// big object not to be overwritten by the updater.
4252 /// \see DesignatedInitUpdateExpr
4253 class NoInitExpr : public Expr {
4255 explicit NoInitExpr(QualType ty)
4256 : Expr(NoInitExprClass, ty, VK_RValue, OK_Ordinary,
4257 false, false, ty->isInstantiationDependentType(), false) { }
4259 explicit NoInitExpr(EmptyShell Empty)
4260 : Expr(NoInitExprClass, Empty) { }
4262 static bool classof(const Stmt *T) {
4263 return T->getStmtClass() == NoInitExprClass;
4266 SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
4267 SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
4270 child_range children() {
4271 return child_range(child_iterator(), child_iterator());
4276 // struct Q { int a, b, c; };
4279 // struct A { Q q; } a = { *getQ(), .q.b = 3 };
4282 // We will have an InitListExpr for a, with type A, and then a
4283 // DesignatedInitUpdateExpr for "a.q" with type Q. The "base" for this DIUE
4284 // is the call expression *getQ(); the "updater" for the DIUE is ".q.b = 3"
4286 class DesignatedInitUpdateExpr : public Expr {
4287 // BaseAndUpdaterExprs[0] is the base expression;
4288 // BaseAndUpdaterExprs[1] is an InitListExpr overwriting part of the base.
4289 Stmt *BaseAndUpdaterExprs[2];
4292 DesignatedInitUpdateExpr(const ASTContext &C, SourceLocation lBraceLoc,
4293 Expr *baseExprs, SourceLocation rBraceLoc);
4295 explicit DesignatedInitUpdateExpr(EmptyShell Empty)
4296 : Expr(DesignatedInitUpdateExprClass, Empty) { }
4298 SourceLocation getLocStart() const LLVM_READONLY;
4299 SourceLocation getLocEnd() const LLVM_READONLY;
4301 static bool classof(const Stmt *T) {
4302 return T->getStmtClass() == DesignatedInitUpdateExprClass;
4305 Expr *getBase() const { return cast<Expr>(BaseAndUpdaterExprs[0]); }
4306 void setBase(Expr *Base) { BaseAndUpdaterExprs[0] = Base; }
4308 InitListExpr *getUpdater() const {
4309 return cast<InitListExpr>(BaseAndUpdaterExprs[1]);
4311 void setUpdater(Expr *Updater) { BaseAndUpdaterExprs[1] = Updater; }
4314 // children = the base and the updater
4315 child_range children() {
4316 return child_range(&BaseAndUpdaterExprs[0], &BaseAndUpdaterExprs[0] + 2);
4320 /// \brief Represents an implicitly-generated value initialization of
4321 /// an object of a given type.
4323 /// Implicit value initializations occur within semantic initializer
4324 /// list expressions (InitListExpr) as placeholders for subobject
4325 /// initializations not explicitly specified by the user.
4327 /// \see InitListExpr
4328 class ImplicitValueInitExpr : public Expr {
4330 explicit ImplicitValueInitExpr(QualType ty)
4331 : Expr(ImplicitValueInitExprClass, ty, VK_RValue, OK_Ordinary,
4332 false, false, ty->isInstantiationDependentType(), false) { }
4334 /// \brief Construct an empty implicit value initialization.
4335 explicit ImplicitValueInitExpr(EmptyShell Empty)
4336 : Expr(ImplicitValueInitExprClass, Empty) { }
4338 static bool classof(const Stmt *T) {
4339 return T->getStmtClass() == ImplicitValueInitExprClass;
4342 SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
4343 SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
4346 child_range children() {
4347 return child_range(child_iterator(), child_iterator());
4351 class ParenListExpr : public Expr {
4354 SourceLocation LParenLoc, RParenLoc;
4357 ParenListExpr(const ASTContext& C, SourceLocation lparenloc,
4358 ArrayRef<Expr*> exprs, SourceLocation rparenloc);
4360 /// \brief Build an empty paren list.
4361 explicit ParenListExpr(EmptyShell Empty) : Expr(ParenListExprClass, Empty) { }
4363 unsigned getNumExprs() const { return NumExprs; }
4365 const Expr* getExpr(unsigned Init) const {
4366 assert(Init < getNumExprs() && "Initializer access out of range!");
4367 return cast_or_null<Expr>(Exprs[Init]);
4370 Expr* getExpr(unsigned Init) {
4371 assert(Init < getNumExprs() && "Initializer access out of range!");
4372 return cast_or_null<Expr>(Exprs[Init]);
4375 Expr **getExprs() { return reinterpret_cast<Expr **>(Exprs); }
4377 ArrayRef<Expr *> exprs() {
4378 return llvm::makeArrayRef(getExprs(), getNumExprs());
4381 SourceLocation getLParenLoc() const { return LParenLoc; }
4382 SourceLocation getRParenLoc() const { return RParenLoc; }
4384 SourceLocation getLocStart() const LLVM_READONLY { return LParenLoc; }
4385 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4387 static bool classof(const Stmt *T) {
4388 return T->getStmtClass() == ParenListExprClass;
4392 child_range children() {
4393 return child_range(&Exprs[0], &Exprs[0]+NumExprs);
4396 friend class ASTStmtReader;
4397 friend class ASTStmtWriter;
4400 /// \brief Represents a C11 generic selection.
4402 /// A generic selection (C11 6.5.1.1) contains an unevaluated controlling
4403 /// expression, followed by one or more generic associations. Each generic
4404 /// association specifies a type name and an expression, or "default" and an
4405 /// expression (in which case it is known as a default generic association).
4406 /// The type and value of the generic selection are identical to those of its
4407 /// result expression, which is defined as the expression in the generic
4408 /// association with a type name that is compatible with the type of the
4409 /// controlling expression, or the expression in the default generic association
4410 /// if no types are compatible. For example:
4413 /// _Generic(X, double: 1, float: 2, default: 3)
4416 /// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f
4417 /// or 3 if "hello".
4419 /// As an extension, generic selections are allowed in C++, where the following
4420 /// additional semantics apply:
4422 /// Any generic selection whose controlling expression is type-dependent or
4423 /// which names a dependent type in its association list is result-dependent,
4424 /// which means that the choice of result expression is dependent.
4425 /// Result-dependent generic associations are both type- and value-dependent.
4426 class GenericSelectionExpr : public Expr {
4427 enum { CONTROLLING, END_EXPR };
4428 TypeSourceInfo **AssocTypes;
4430 unsigned NumAssocs, ResultIndex;
4431 SourceLocation GenericLoc, DefaultLoc, RParenLoc;
4434 GenericSelectionExpr(const ASTContext &Context,
4435 SourceLocation GenericLoc, Expr *ControllingExpr,
4436 ArrayRef<TypeSourceInfo*> AssocTypes,
4437 ArrayRef<Expr*> AssocExprs,
4438 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4439 bool ContainsUnexpandedParameterPack,
4440 unsigned ResultIndex);
4442 /// This constructor is used in the result-dependent case.
4443 GenericSelectionExpr(const ASTContext &Context,
4444 SourceLocation GenericLoc, Expr *ControllingExpr,
4445 ArrayRef<TypeSourceInfo*> AssocTypes,
4446 ArrayRef<Expr*> AssocExprs,
4447 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4448 bool ContainsUnexpandedParameterPack);
4450 explicit GenericSelectionExpr(EmptyShell Empty)
4451 : Expr(GenericSelectionExprClass, Empty) { }
4453 unsigned getNumAssocs() const { return NumAssocs; }
4455 SourceLocation getGenericLoc() const { return GenericLoc; }
4456 SourceLocation getDefaultLoc() const { return DefaultLoc; }
4457 SourceLocation getRParenLoc() const { return RParenLoc; }
4459 const Expr *getAssocExpr(unsigned i) const {
4460 return cast<Expr>(SubExprs[END_EXPR+i]);
4462 Expr *getAssocExpr(unsigned i) { return cast<Expr>(SubExprs[END_EXPR+i]); }
4464 const TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) const {
4465 return AssocTypes[i];
4467 TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) { return AssocTypes[i]; }
4469 QualType getAssocType(unsigned i) const {
4470 if (const TypeSourceInfo *TS = getAssocTypeSourceInfo(i))
4471 return TS->getType();
4476 const Expr *getControllingExpr() const {
4477 return cast<Expr>(SubExprs[CONTROLLING]);
4479 Expr *getControllingExpr() { return cast<Expr>(SubExprs[CONTROLLING]); }
4481 /// Whether this generic selection is result-dependent.
4482 bool isResultDependent() const { return ResultIndex == -1U; }
4484 /// The zero-based index of the result expression's generic association in
4485 /// the generic selection's association list. Defined only if the
4486 /// generic selection is not result-dependent.
4487 unsigned getResultIndex() const {
4488 assert(!isResultDependent() && "Generic selection is result-dependent");
4492 /// The generic selection's result expression. Defined only if the
4493 /// generic selection is not result-dependent.
4494 const Expr *getResultExpr() const { return getAssocExpr(getResultIndex()); }
4495 Expr *getResultExpr() { return getAssocExpr(getResultIndex()); }
4497 SourceLocation getLocStart() const LLVM_READONLY { return GenericLoc; }
4498 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4500 static bool classof(const Stmt *T) {
4501 return T->getStmtClass() == GenericSelectionExprClass;
4504 child_range children() {
4505 return child_range(SubExprs, SubExprs+END_EXPR+NumAssocs);
4508 friend class ASTStmtReader;
4511 //===----------------------------------------------------------------------===//
4513 //===----------------------------------------------------------------------===//
4515 /// ExtVectorElementExpr - This represents access to specific elements of a
4516 /// vector, and may occur on the left hand side or right hand side. For example
4517 /// the following is legal: "V.xy = V.zw" if V is a 4 element extended vector.
4519 /// Note that the base may have either vector or pointer to vector type, just
4520 /// like a struct field reference.
4522 class ExtVectorElementExpr : public Expr {
4524 IdentifierInfo *Accessor;
4525 SourceLocation AccessorLoc;
4527 ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base,
4528 IdentifierInfo &accessor, SourceLocation loc)
4529 : Expr(ExtVectorElementExprClass, ty, VK,
4530 (VK == VK_RValue ? OK_Ordinary : OK_VectorComponent),
4531 base->isTypeDependent(), base->isValueDependent(),
4532 base->isInstantiationDependent(),
4533 base->containsUnexpandedParameterPack()),
4534 Base(base), Accessor(&accessor), AccessorLoc(loc) {}
4536 /// \brief Build an empty vector element expression.
4537 explicit ExtVectorElementExpr(EmptyShell Empty)
4538 : Expr(ExtVectorElementExprClass, Empty) { }
4540 const Expr *getBase() const { return cast<Expr>(Base); }
4541 Expr *getBase() { return cast<Expr>(Base); }
4542 void setBase(Expr *E) { Base = E; }
4544 IdentifierInfo &getAccessor() const { return *Accessor; }
4545 void setAccessor(IdentifierInfo *II) { Accessor = II; }
4547 SourceLocation getAccessorLoc() const { return AccessorLoc; }
4548 void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
4550 /// getNumElements - Get the number of components being selected.
4551 unsigned getNumElements() const;
4553 /// containsDuplicateElements - Return true if any element access is
4555 bool containsDuplicateElements() const;
4557 /// getEncodedElementAccess - Encode the elements accessed into an llvm
4558 /// aggregate Constant of ConstantInt(s).
4559 void getEncodedElementAccess(SmallVectorImpl<uint32_t> &Elts) const;
4561 SourceLocation getLocStart() const LLVM_READONLY {
4562 return getBase()->getLocStart();
4564 SourceLocation getLocEnd() const LLVM_READONLY { return AccessorLoc; }
4566 /// isArrow - Return true if the base expression is a pointer to vector,
4567 /// return false if the base expression is a vector.
4568 bool isArrow() const;
4570 static bool classof(const Stmt *T) {
4571 return T->getStmtClass() == ExtVectorElementExprClass;
4575 child_range children() { return child_range(&Base, &Base+1); }
4578 /// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
4579 /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
4580 class BlockExpr : public Expr {
4582 BlockDecl *TheBlock;
4584 BlockExpr(BlockDecl *BD, QualType ty)
4585 : Expr(BlockExprClass, ty, VK_RValue, OK_Ordinary,
4586 ty->isDependentType(), ty->isDependentType(),
4587 ty->isInstantiationDependentType() || BD->isDependentContext(),
4591 /// \brief Build an empty block expression.
4592 explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
4594 const BlockDecl *getBlockDecl() const { return TheBlock; }
4595 BlockDecl *getBlockDecl() { return TheBlock; }
4596 void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
4598 // Convenience functions for probing the underlying BlockDecl.
4599 SourceLocation getCaretLocation() const;
4600 const Stmt *getBody() const;
4603 SourceLocation getLocStart() const LLVM_READONLY { return getCaretLocation(); }
4604 SourceLocation getLocEnd() const LLVM_READONLY { return getBody()->getLocEnd(); }
4606 /// getFunctionType - Return the underlying function type for this block.
4607 const FunctionProtoType *getFunctionType() const;
4609 static bool classof(const Stmt *T) {
4610 return T->getStmtClass() == BlockExprClass;
4614 child_range children() {
4615 return child_range(child_iterator(), child_iterator());
4619 /// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2]
4620 /// This AST node provides support for reinterpreting a type to another
4621 /// type of the same size.
4622 class AsTypeExpr : public Expr {
4625 SourceLocation BuiltinLoc, RParenLoc;
4627 friend class ASTReader;
4628 friend class ASTStmtReader;
4629 explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {}
4632 AsTypeExpr(Expr* SrcExpr, QualType DstType,
4633 ExprValueKind VK, ExprObjectKind OK,
4634 SourceLocation BuiltinLoc, SourceLocation RParenLoc)
4635 : Expr(AsTypeExprClass, DstType, VK, OK,
4636 DstType->isDependentType(),
4637 DstType->isDependentType() || SrcExpr->isValueDependent(),
4638 (DstType->isInstantiationDependentType() ||
4639 SrcExpr->isInstantiationDependent()),
4640 (DstType->containsUnexpandedParameterPack() ||
4641 SrcExpr->containsUnexpandedParameterPack())),
4642 SrcExpr(SrcExpr), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
4644 /// getSrcExpr - Return the Expr to be converted.
4645 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
4647 /// getBuiltinLoc - Return the location of the __builtin_astype token.
4648 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4650 /// getRParenLoc - Return the location of final right parenthesis.
4651 SourceLocation getRParenLoc() const { return RParenLoc; }
4653 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
4654 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4656 static bool classof(const Stmt *T) {
4657 return T->getStmtClass() == AsTypeExprClass;
4661 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
4664 /// PseudoObjectExpr - An expression which accesses a pseudo-object
4665 /// l-value. A pseudo-object is an abstract object, accesses to which
4666 /// are translated to calls. The pseudo-object expression has a
4667 /// syntactic form, which shows how the expression was actually
4668 /// written in the source code, and a semantic form, which is a series
4669 /// of expressions to be executed in order which detail how the
4670 /// operation is actually evaluated. Optionally, one of the semantic
4671 /// forms may also provide a result value for the expression.
4673 /// If any of the semantic-form expressions is an OpaqueValueExpr,
4674 /// that OVE is required to have a source expression, and it is bound
4675 /// to the result of that source expression. Such OVEs may appear
4676 /// only in subsequent semantic-form expressions and as
4677 /// sub-expressions of the syntactic form.
4679 /// PseudoObjectExpr should be used only when an operation can be
4680 /// usefully described in terms of fairly simple rewrite rules on
4681 /// objects and functions that are meant to be used by end-developers.
4682 /// For example, under the Itanium ABI, dynamic casts are implemented
4683 /// as a call to a runtime function called __dynamic_cast; using this
4684 /// class to describe that would be inappropriate because that call is
4685 /// not really part of the user-visible semantics, and instead the
4686 /// cast is properly reflected in the AST and IR-generation has been
4687 /// taught to generate the call as necessary. In contrast, an
4688 /// Objective-C property access is semantically defined to be
4689 /// equivalent to a particular message send, and this is very much
4690 /// part of the user model. The name of this class encourages this
4691 /// modelling design.
4692 class PseudoObjectExpr final
4694 private llvm::TrailingObjects<PseudoObjectExpr, Expr *> {
4695 // PseudoObjectExprBits.NumSubExprs - The number of sub-expressions.
4696 // Always at least two, because the first sub-expression is the
4699 // PseudoObjectExprBits.ResultIndex - The index of the
4700 // sub-expression holding the result. 0 means the result is void,
4701 // which is unambiguous because it's the index of the syntactic
4702 // form. Note that this is therefore 1 higher than the value passed
4703 // in to Create, which is an index within the semantic forms.
4704 // Note also that ASTStmtWriter assumes this encoding.
4706 Expr **getSubExprsBuffer() { return getTrailingObjects<Expr *>(); }
4707 const Expr * const *getSubExprsBuffer() const {
4708 return getTrailingObjects<Expr *>();
4711 PseudoObjectExpr(QualType type, ExprValueKind VK,
4712 Expr *syntactic, ArrayRef<Expr*> semantic,
4713 unsigned resultIndex);
4715 PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs);
4717 unsigned getNumSubExprs() const {
4718 return PseudoObjectExprBits.NumSubExprs;
4722 /// NoResult - A value for the result index indicating that there is
4723 /// no semantic result.
4724 enum : unsigned { NoResult = ~0U };
4726 static PseudoObjectExpr *Create(const ASTContext &Context, Expr *syntactic,
4727 ArrayRef<Expr*> semantic,
4728 unsigned resultIndex);
4730 static PseudoObjectExpr *Create(const ASTContext &Context, EmptyShell shell,
4731 unsigned numSemanticExprs);
4733 /// Return the syntactic form of this expression, i.e. the
4734 /// expression it actually looks like. Likely to be expressed in
4735 /// terms of OpaqueValueExprs bound in the semantic form.
4736 Expr *getSyntacticForm() { return getSubExprsBuffer()[0]; }
4737 const Expr *getSyntacticForm() const { return getSubExprsBuffer()[0]; }
4739 /// Return the index of the result-bearing expression into the semantics
4740 /// expressions, or PseudoObjectExpr::NoResult if there is none.
4741 unsigned getResultExprIndex() const {
4742 if (PseudoObjectExprBits.ResultIndex == 0) return NoResult;
4743 return PseudoObjectExprBits.ResultIndex - 1;
4746 /// Return the result-bearing expression, or null if there is none.
4747 Expr *getResultExpr() {
4748 if (PseudoObjectExprBits.ResultIndex == 0)
4750 return getSubExprsBuffer()[PseudoObjectExprBits.ResultIndex];
4752 const Expr *getResultExpr() const {
4753 return const_cast<PseudoObjectExpr*>(this)->getResultExpr();
4756 unsigned getNumSemanticExprs() const { return getNumSubExprs() - 1; }
4758 typedef Expr * const *semantics_iterator;
4759 typedef const Expr * const *const_semantics_iterator;
4760 semantics_iterator semantics_begin() {
4761 return getSubExprsBuffer() + 1;
4763 const_semantics_iterator semantics_begin() const {
4764 return getSubExprsBuffer() + 1;
4766 semantics_iterator semantics_end() {
4767 return getSubExprsBuffer() + getNumSubExprs();
4769 const_semantics_iterator semantics_end() const {
4770 return getSubExprsBuffer() + getNumSubExprs();
4773 llvm::iterator_range<semantics_iterator> semantics() {
4774 return llvm::make_range(semantics_begin(), semantics_end());
4776 llvm::iterator_range<const_semantics_iterator> semantics() const {
4777 return llvm::make_range(semantics_begin(), semantics_end());
4780 Expr *getSemanticExpr(unsigned index) {
4781 assert(index + 1 < getNumSubExprs());
4782 return getSubExprsBuffer()[index + 1];
4784 const Expr *getSemanticExpr(unsigned index) const {
4785 return const_cast<PseudoObjectExpr*>(this)->getSemanticExpr(index);
4788 SourceLocation getExprLoc() const LLVM_READONLY {
4789 return getSyntacticForm()->getExprLoc();
4792 SourceLocation getLocStart() const LLVM_READONLY {
4793 return getSyntacticForm()->getLocStart();
4795 SourceLocation getLocEnd() const LLVM_READONLY {
4796 return getSyntacticForm()->getLocEnd();
4799 child_range children() {
4800 Stmt **cs = reinterpret_cast<Stmt**>(getSubExprsBuffer());
4801 return child_range(cs, cs + getNumSubExprs());
4804 static bool classof(const Stmt *T) {
4805 return T->getStmtClass() == PseudoObjectExprClass;
4808 friend TrailingObjects;
4809 friend class ASTStmtReader;
4812 /// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*,
4813 /// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the
4814 /// similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>.
4815 /// All of these instructions take one primary pointer and at least one memory
4817 class AtomicExpr : public Expr {
4820 #define BUILTIN(ID, TYPE, ATTRS)
4821 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) AO ## ID,
4822 #include "clang/Basic/Builtins.def"
4823 // Avoid trailing comma
4827 // The ABI values for various atomic memory orderings.
4828 enum AtomicOrderingKind {
4829 AO_ABI_memory_order_relaxed = 0,
4830 AO_ABI_memory_order_consume = 1,
4831 AO_ABI_memory_order_acquire = 2,
4832 AO_ABI_memory_order_release = 3,
4833 AO_ABI_memory_order_acq_rel = 4,
4834 AO_ABI_memory_order_seq_cst = 5
4838 enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, WEAK, END_EXPR };
4839 Stmt* SubExprs[END_EXPR];
4840 unsigned NumSubExprs;
4841 SourceLocation BuiltinLoc, RParenLoc;
4844 friend class ASTStmtReader;
4847 AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args, QualType t,
4848 AtomicOp op, SourceLocation RP);
4850 /// \brief Determine the number of arguments the specified atomic builtin
4852 static unsigned getNumSubExprs(AtomicOp Op);
4854 /// \brief Build an empty AtomicExpr.
4855 explicit AtomicExpr(EmptyShell Empty) : Expr(AtomicExprClass, Empty) { }
4857 Expr *getPtr() const {
4858 return cast<Expr>(SubExprs[PTR]);
4860 Expr *getOrder() const {
4861 return cast<Expr>(SubExprs[ORDER]);
4863 Expr *getVal1() const {
4864 if (Op == AO__c11_atomic_init)
4865 return cast<Expr>(SubExprs[ORDER]);
4866 assert(NumSubExprs > VAL1);
4867 return cast<Expr>(SubExprs[VAL1]);
4869 Expr *getOrderFail() const {
4870 assert(NumSubExprs > ORDER_FAIL);
4871 return cast<Expr>(SubExprs[ORDER_FAIL]);
4873 Expr *getVal2() const {
4874 if (Op == AO__atomic_exchange)
4875 return cast<Expr>(SubExprs[ORDER_FAIL]);
4876 assert(NumSubExprs > VAL2);
4877 return cast<Expr>(SubExprs[VAL2]);
4879 Expr *getWeak() const {
4880 assert(NumSubExprs > WEAK);
4881 return cast<Expr>(SubExprs[WEAK]);
4884 AtomicOp getOp() const { return Op; }
4885 unsigned getNumSubExprs() { return NumSubExprs; }
4887 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
4889 bool isVolatile() const {
4890 return getPtr()->getType()->getPointeeType().isVolatileQualified();
4893 bool isCmpXChg() const {
4894 return getOp() == AO__c11_atomic_compare_exchange_strong ||
4895 getOp() == AO__c11_atomic_compare_exchange_weak ||
4896 getOp() == AO__atomic_compare_exchange ||
4897 getOp() == AO__atomic_compare_exchange_n;
4900 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4901 SourceLocation getRParenLoc() const { return RParenLoc; }
4903 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
4904 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4906 static bool classof(const Stmt *T) {
4907 return T->getStmtClass() == AtomicExprClass;
4911 child_range children() {
4912 return child_range(SubExprs, SubExprs+NumSubExprs);
4916 /// TypoExpr - Internal placeholder for expressions where typo correction
4917 /// still needs to be performed and/or an error diagnostic emitted.
4918 class TypoExpr : public Expr {
4920 TypoExpr(QualType T)
4921 : Expr(TypoExprClass, T, VK_LValue, OK_Ordinary,
4922 /*isTypeDependent*/ true,
4923 /*isValueDependent*/ true,
4924 /*isInstantiationDependent*/ true,
4925 /*containsUnexpandedParameterPack*/ false) {
4926 assert(T->isDependentType() && "TypoExpr given a non-dependent type");
4929 child_range children() {
4930 return child_range(child_iterator(), child_iterator());
4932 SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
4933 SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
4935 static bool classof(const Stmt *T) {
4936 return T->getStmtClass() == TypoExprClass;
4940 } // end namespace clang
4942 #endif // LLVM_CLANG_AST_EXPR_H