1 //===--- Expr.h - Classes for representing expressions ----------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file defines the Expr interface and subclasses.
11 //===----------------------------------------------------------------------===//
13 #ifndef LLVM_CLANG_AST_EXPR_H
14 #define LLVM_CLANG_AST_EXPR_H
16 #include "clang/AST/APValue.h"
17 #include "clang/AST/ASTVector.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclAccessPair.h"
20 #include "clang/AST/OperationKinds.h"
21 #include "clang/AST/Stmt.h"
22 #include "clang/AST/TemplateBase.h"
23 #include "clang/AST/Type.h"
24 #include "clang/Basic/CharInfo.h"
25 #include "clang/Basic/FixedPoint.h"
26 #include "clang/Basic/LangOptions.h"
27 #include "clang/Basic/SyncScope.h"
28 #include "clang/Basic/TypeTraits.h"
29 #include "llvm/ADT/APFloat.h"
30 #include "llvm/ADT/APSInt.h"
31 #include "llvm/ADT/iterator.h"
32 #include "llvm/ADT/iterator_range.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/StringRef.h"
35 #include "llvm/Support/AtomicOrdering.h"
36 #include "llvm/Support/Compiler.h"
37 #include "llvm/Support/TrailingObjects.h"
43 class CXXBaseSpecifier;
44 class CXXMemberCallExpr;
45 class CXXOperatorCallExpr;
49 class MaterializeTemporaryExpr;
51 class ObjCPropertyRefExpr;
52 class OpaqueValueExpr;
58 /// A simple array of base specifiers.
59 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
61 /// An adjustment to be made to the temporary created when emitting a
62 /// reference binding, which accesses a particular subobject of that temporary.
63 struct SubobjectAdjustment {
65 DerivedToBaseAdjustment,
67 MemberPointerAdjustment
71 const CastExpr *BasePath;
72 const CXXRecordDecl *DerivedClass;
76 const MemberPointerType *MPT;
81 struct DTB DerivedToBase;
86 SubobjectAdjustment(const CastExpr *BasePath,
87 const CXXRecordDecl *DerivedClass)
88 : Kind(DerivedToBaseAdjustment) {
89 DerivedToBase.BasePath = BasePath;
90 DerivedToBase.DerivedClass = DerivedClass;
93 SubobjectAdjustment(FieldDecl *Field)
94 : Kind(FieldAdjustment) {
98 SubobjectAdjustment(const MemberPointerType *MPT, Expr *RHS)
99 : Kind(MemberPointerAdjustment) {
105 /// This represents one expression. Note that Expr's are subclasses of Stmt.
106 /// This allows an expression to be transparently used any place a Stmt is
108 class Expr : public ValueStmt {
113 Expr(const Expr&) = delete;
114 Expr(Expr &&) = delete;
115 Expr &operator=(const Expr&) = delete;
116 Expr &operator=(Expr&&) = delete;
119 Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK,
120 bool TD, bool VD, bool ID, bool ContainsUnexpandedParameterPack)
123 ExprBits.TypeDependent = TD;
124 ExprBits.ValueDependent = VD;
125 ExprBits.InstantiationDependent = ID;
126 ExprBits.ValueKind = VK;
127 ExprBits.ObjectKind = OK;
128 assert(ExprBits.ObjectKind == OK && "truncated kind");
129 ExprBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
133 /// Construct an empty expression.
134 explicit Expr(StmtClass SC, EmptyShell) : ValueStmt(SC) { }
137 QualType getType() const { return TR; }
138 void setType(QualType t) {
139 // In C++, the type of an expression is always adjusted so that it
140 // will not have reference type (C++ [expr]p6). Use
141 // QualType::getNonReferenceType() to retrieve the non-reference
142 // type. Additionally, inspect Expr::isLvalue to determine whether
143 // an expression that is adjusted in this manner should be
144 // considered an lvalue.
145 assert((t.isNull() || !t->isReferenceType()) &&
146 "Expressions can't have reference type");
151 /// isValueDependent - Determines whether this expression is
152 /// value-dependent (C++ [temp.dep.constexpr]). For example, the
153 /// array bound of "Chars" in the following example is
156 /// template<int Size, char (&Chars)[Size]> struct meta_string;
158 bool isValueDependent() const { return ExprBits.ValueDependent; }
160 /// Set whether this expression is value-dependent or not.
161 void setValueDependent(bool VD) {
162 ExprBits.ValueDependent = VD;
165 /// isTypeDependent - Determines whether this expression is
166 /// type-dependent (C++ [temp.dep.expr]), which means that its type
167 /// could change from one template instantiation to the next. For
168 /// example, the expressions "x" and "x + y" are type-dependent in
169 /// the following code, but "y" is not type-dependent:
171 /// template<typename T>
172 /// void add(T x, int y) {
176 bool isTypeDependent() const { return ExprBits.TypeDependent; }
178 /// Set whether this expression is type-dependent or not.
179 void setTypeDependent(bool TD) {
180 ExprBits.TypeDependent = TD;
183 /// Whether this expression is instantiation-dependent, meaning that
184 /// it depends in some way on a template parameter, even if neither its type
185 /// nor (constant) value can change due to the template instantiation.
187 /// In the following example, the expression \c sizeof(sizeof(T() + T())) is
188 /// instantiation-dependent (since it involves a template parameter \c T), but
189 /// is neither type- nor value-dependent, since the type of the inner
190 /// \c sizeof is known (\c std::size_t) and therefore the size of the outer
191 /// \c sizeof is known.
194 /// template<typename T>
195 /// void f(T x, T y) {
196 /// sizeof(sizeof(T() + T());
200 bool isInstantiationDependent() const {
201 return ExprBits.InstantiationDependent;
204 /// Set whether this expression is instantiation-dependent or not.
205 void setInstantiationDependent(bool ID) {
206 ExprBits.InstantiationDependent = ID;
209 /// Whether this expression contains an unexpanded parameter
210 /// pack (for C++11 variadic templates).
212 /// Given the following function template:
215 /// template<typename F, typename ...Types>
216 /// void forward(const F &f, Types &&...args) {
217 /// f(static_cast<Types&&>(args)...);
221 /// The expressions \c args and \c static_cast<Types&&>(args) both
222 /// contain parameter packs.
223 bool containsUnexpandedParameterPack() const {
224 return ExprBits.ContainsUnexpandedParameterPack;
227 /// Set the bit that describes whether this expression
228 /// contains an unexpanded parameter pack.
229 void setContainsUnexpandedParameterPack(bool PP = true) {
230 ExprBits.ContainsUnexpandedParameterPack = PP;
233 /// getExprLoc - Return the preferred location for the arrow when diagnosing
234 /// a problem with a generic expression.
235 SourceLocation getExprLoc() const LLVM_READONLY;
237 /// isUnusedResultAWarning - Return true if this immediate expression should
238 /// be warned about if the result is unused. If so, fill in expr, location,
239 /// and ranges with expr to warn on and source locations/ranges appropriate
241 bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc,
242 SourceRange &R1, SourceRange &R2,
243 ASTContext &Ctx) const;
245 /// isLValue - True if this expression is an "l-value" according to
246 /// the rules of the current language. C and C++ give somewhat
247 /// different rules for this concept, but in general, the result of
248 /// an l-value expression identifies a specific object whereas the
249 /// result of an r-value expression is a value detached from any
250 /// specific storage.
252 /// C++11 divides the concept of "r-value" into pure r-values
253 /// ("pr-values") and so-called expiring values ("x-values"), which
254 /// identify specific objects that can be safely cannibalized for
255 /// their resources. This is an unfortunate abuse of terminology on
256 /// the part of the C++ committee. In Clang, when we say "r-value",
257 /// we generally mean a pr-value.
258 bool isLValue() const { return getValueKind() == VK_LValue; }
259 bool isRValue() const { return getValueKind() == VK_RValue; }
260 bool isXValue() const { return getValueKind() == VK_XValue; }
261 bool isGLValue() const { return getValueKind() != VK_RValue; }
263 enum LValueClassification {
266 LV_IncompleteVoidType,
267 LV_DuplicateVectorComponents,
268 LV_InvalidExpression,
269 LV_InvalidMessageExpression,
271 LV_SubObjCPropertySetting,
275 /// Reasons why an expression might not be an l-value.
276 LValueClassification ClassifyLValue(ASTContext &Ctx) const;
278 enum isModifiableLvalueResult {
281 MLV_IncompleteVoidType,
282 MLV_DuplicateVectorComponents,
283 MLV_InvalidExpression,
284 MLV_LValueCast, // Specialized form of MLV_InvalidExpression.
287 MLV_ConstQualifiedField,
290 MLV_NoSetterProperty,
292 MLV_SubObjCPropertySetting,
293 MLV_InvalidMessageExpression,
297 /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
298 /// does not have an incomplete type, does not have a const-qualified type,
299 /// and if it is a structure or union, does not have any member (including,
300 /// recursively, any member or element of all contained aggregates or unions)
301 /// with a const-qualified type.
303 /// \param Loc [in,out] - A source location which *may* be filled
304 /// in with the location of the expression making this a
305 /// non-modifiable lvalue, if specified.
306 isModifiableLvalueResult
307 isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc = nullptr) const;
309 /// The return type of classify(). Represents the C++11 expression
311 class Classification {
313 /// The various classification results. Most of these mean prvalue.
317 CL_Function, // Functions cannot be lvalues in C.
318 CL_Void, // Void cannot be an lvalue in C.
319 CL_AddressableVoid, // Void expression whose address can be taken in C.
320 CL_DuplicateVectorComponents, // A vector shuffle with dupes.
321 CL_MemberFunction, // An expression referring to a member function
322 CL_SubObjCPropertySetting,
323 CL_ClassTemporary, // A temporary of class type, or subobject thereof.
324 CL_ArrayTemporary, // A temporary of array type.
325 CL_ObjCMessageRValue, // ObjC message is an rvalue
326 CL_PRValue // A prvalue for any other reason, of any other type
328 /// The results of modification testing.
329 enum ModifiableType {
330 CM_Untested, // testModifiable was false.
332 CM_RValue, // Not modifiable because it's an rvalue
333 CM_Function, // Not modifiable because it's a function; C++ only
334 CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext
335 CM_NoSetterProperty,// Implicit assignment to ObjC property without setter
337 CM_ConstQualifiedField,
347 unsigned short Modifiable;
349 explicit Classification(Kinds k, ModifiableType m)
350 : Kind(k), Modifiable(m)
356 Kinds getKind() const { return static_cast<Kinds>(Kind); }
357 ModifiableType getModifiable() const {
358 assert(Modifiable != CM_Untested && "Did not test for modifiability.");
359 return static_cast<ModifiableType>(Modifiable);
361 bool isLValue() const { return Kind == CL_LValue; }
362 bool isXValue() const { return Kind == CL_XValue; }
363 bool isGLValue() const { return Kind <= CL_XValue; }
364 bool isPRValue() const { return Kind >= CL_Function; }
365 bool isRValue() const { return Kind >= CL_XValue; }
366 bool isModifiable() const { return getModifiable() == CM_Modifiable; }
368 /// Create a simple, modifiably lvalue
369 static Classification makeSimpleLValue() {
370 return Classification(CL_LValue, CM_Modifiable);
374 /// Classify - Classify this expression according to the C++11
375 /// expression taxonomy.
377 /// C++11 defines ([basic.lval]) a new taxonomy of expressions to replace the
378 /// old lvalue vs rvalue. This function determines the type of expression this
379 /// is. There are three expression types:
380 /// - lvalues are classical lvalues as in C++03.
381 /// - prvalues are equivalent to rvalues in C++03.
382 /// - xvalues are expressions yielding unnamed rvalue references, e.g. a
383 /// function returning an rvalue reference.
384 /// lvalues and xvalues are collectively referred to as glvalues, while
385 /// prvalues and xvalues together form rvalues.
386 Classification Classify(ASTContext &Ctx) const {
387 return ClassifyImpl(Ctx, nullptr);
390 /// ClassifyModifiable - Classify this expression according to the
391 /// C++11 expression taxonomy, and see if it is valid on the left side
392 /// of an assignment.
394 /// This function extends classify in that it also tests whether the
395 /// expression is modifiable (C99 6.3.2.1p1).
396 /// \param Loc A source location that might be filled with a relevant location
397 /// if the expression is not modifiable.
398 Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{
399 return ClassifyImpl(Ctx, &Loc);
402 /// getValueKindForType - Given a formal return or parameter type,
403 /// give its value kind.
404 static ExprValueKind getValueKindForType(QualType T) {
405 if (const ReferenceType *RT = T->getAs<ReferenceType>())
406 return (isa<LValueReferenceType>(RT)
408 : (RT->getPointeeType()->isFunctionType()
409 ? VK_LValue : VK_XValue));
413 /// getValueKind - The value kind that this expression produces.
414 ExprValueKind getValueKind() const {
415 return static_cast<ExprValueKind>(ExprBits.ValueKind);
418 /// getObjectKind - The object kind that this expression produces.
419 /// Object kinds are meaningful only for expressions that yield an
420 /// l-value or x-value.
421 ExprObjectKind getObjectKind() const {
422 return static_cast<ExprObjectKind>(ExprBits.ObjectKind);
425 bool isOrdinaryOrBitFieldObject() const {
426 ExprObjectKind OK = getObjectKind();
427 return (OK == OK_Ordinary || OK == OK_BitField);
430 /// setValueKind - Set the value kind produced by this expression.
431 void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; }
433 /// setObjectKind - Set the object kind produced by this expression.
434 void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; }
437 Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const;
441 /// Returns true if this expression is a gl-value that
442 /// potentially refers to a bit-field.
444 /// In C++, whether a gl-value refers to a bitfield is essentially
445 /// an aspect of the value-kind type system.
446 bool refersToBitField() const { return getObjectKind() == OK_BitField; }
448 /// If this expression refers to a bit-field, retrieve the
449 /// declaration of that bit-field.
451 /// Note that this returns a non-null pointer in subtly different
452 /// places than refersToBitField returns true. In particular, this can
453 /// return a non-null pointer even for r-values loaded from
454 /// bit-fields, but it will return null for a conditional bit-field.
455 FieldDecl *getSourceBitField();
457 const FieldDecl *getSourceBitField() const {
458 return const_cast<Expr*>(this)->getSourceBitField();
461 Decl *getReferencedDeclOfCallee();
462 const Decl *getReferencedDeclOfCallee() const {
463 return const_cast<Expr*>(this)->getReferencedDeclOfCallee();
466 /// If this expression is an l-value for an Objective C
467 /// property, find the underlying property reference expression.
468 const ObjCPropertyRefExpr *getObjCProperty() const;
470 /// Check if this expression is the ObjC 'self' implicit parameter.
471 bool isObjCSelfExpr() const;
473 /// Returns whether this expression refers to a vector element.
474 bool refersToVectorElement() const;
476 /// Returns whether this expression refers to a global register
478 bool refersToGlobalRegisterVar() const;
480 /// Returns whether this expression has a placeholder type.
481 bool hasPlaceholderType() const {
482 return getType()->isPlaceholderType();
485 /// Returns whether this expression has a specific placeholder type.
486 bool hasPlaceholderType(BuiltinType::Kind K) const {
487 assert(BuiltinType::isPlaceholderTypeKind(K));
488 if (const BuiltinType *BT = dyn_cast<BuiltinType>(getType()))
489 return BT->getKind() == K;
493 /// isKnownToHaveBooleanValue - Return true if this is an integer expression
494 /// that is known to return 0 or 1. This happens for _Bool/bool expressions
495 /// but also int expressions which are produced by things like comparisons in
497 bool isKnownToHaveBooleanValue() const;
499 /// isIntegerConstantExpr - Return true if this expression is a valid integer
500 /// constant expression, and, if so, return its value in Result. If not a
501 /// valid i-c-e, return false and fill in Loc (if specified) with the location
502 /// of the invalid expression.
504 /// Note: This does not perform the implicit conversions required by C++11
506 bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx,
507 SourceLocation *Loc = nullptr,
508 bool isEvaluated = true) const;
509 bool isIntegerConstantExpr(const ASTContext &Ctx,
510 SourceLocation *Loc = nullptr) const;
512 /// isCXX98IntegralConstantExpr - Return true if this expression is an
513 /// integral constant expression in C++98. Can only be used in C++.
514 bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const;
516 /// isCXX11ConstantExpr - Return true if this expression is a constant
517 /// expression in C++11. Can only be used in C++.
519 /// Note: This does not perform the implicit conversions required by C++11
521 bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result = nullptr,
522 SourceLocation *Loc = nullptr) const;
524 /// isPotentialConstantExpr - Return true if this function's definition
525 /// might be usable in a constant expression in C++11, if it were marked
526 /// constexpr. Return false if the function can never produce a constant
527 /// expression, along with diagnostics describing why not.
528 static bool isPotentialConstantExpr(const FunctionDecl *FD,
530 PartialDiagnosticAt> &Diags);
532 /// isPotentialConstantExprUnevaluted - Return true if this expression might
533 /// be usable in a constant expression in C++11 in an unevaluated context, if
534 /// it were in function FD marked constexpr. Return false if the function can
535 /// never produce a constant expression, along with diagnostics describing
537 static bool isPotentialConstantExprUnevaluated(Expr *E,
538 const FunctionDecl *FD,
540 PartialDiagnosticAt> &Diags);
542 /// isConstantInitializer - Returns true if this expression can be emitted to
543 /// IR as a constant, and thus can be used as a constant initializer in C.
544 /// If this expression is not constant and Culprit is non-null,
545 /// it is used to store the address of first non constant expr.
546 bool isConstantInitializer(ASTContext &Ctx, bool ForRef,
547 const Expr **Culprit = nullptr) const;
549 /// EvalStatus is a struct with detailed info about an evaluation in progress.
551 /// Whether the evaluated expression has side effects.
552 /// For example, (f() && 0) can be folded, but it still has side effects.
555 /// Whether the evaluation hit undefined behavior.
556 /// For example, 1.0 / 0.0 can be folded to Inf, but has undefined behavior.
557 /// Likewise, INT_MAX + 1 can be folded to INT_MIN, but has UB.
558 bool HasUndefinedBehavior;
560 /// Diag - If this is non-null, it will be filled in with a stack of notes
561 /// indicating why evaluation failed (or why it failed to produce a constant
563 /// If the expression is unfoldable, the notes will indicate why it's not
564 /// foldable. If the expression is foldable, but not a constant expression,
565 /// the notes will describes why it isn't a constant expression. If the
566 /// expression *is* a constant expression, no notes will be produced.
567 SmallVectorImpl<PartialDiagnosticAt> *Diag;
570 : HasSideEffects(false), HasUndefinedBehavior(false), Diag(nullptr) {}
572 // hasSideEffects - Return true if the evaluated expression has
574 bool hasSideEffects() const {
575 return HasSideEffects;
579 /// EvalResult is a struct with detailed info about an evaluated expression.
580 struct EvalResult : EvalStatus {
581 /// Val - This is the value the expression can be folded to.
584 // isGlobalLValue - Return true if the evaluated lvalue expression
586 bool isGlobalLValue() const;
589 /// EvaluateAsRValue - Return true if this is a constant which we can fold to
590 /// an rvalue using any crazy technique (that has nothing to do with language
591 /// standards) that we want to, even if the expression has side-effects. If
592 /// this function returns true, it returns the folded constant in Result. If
593 /// the expression is a glvalue, an lvalue-to-rvalue conversion will be
595 bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
596 bool InConstantContext = false) const;
598 /// EvaluateAsBooleanCondition - Return true if this is a constant
599 /// which we can fold and convert to a boolean condition using
600 /// any crazy technique that we want to, even if the expression has
602 bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
603 bool InConstantContext = false) const;
605 enum SideEffectsKind {
606 SE_NoSideEffects, ///< Strictly evaluate the expression.
607 SE_AllowUndefinedBehavior, ///< Allow UB that we can give a value, but not
608 ///< arbitrary unmodeled side effects.
609 SE_AllowSideEffects ///< Allow any unmodeled side effect.
612 /// EvaluateAsInt - Return true if this is a constant which we can fold and
613 /// convert to an integer, using any crazy technique that we want to.
614 bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
615 SideEffectsKind AllowSideEffects = SE_NoSideEffects,
616 bool InConstantContext = false) const;
618 /// EvaluateAsFloat - Return true if this is a constant which we can fold and
619 /// convert to a floating point value, using any crazy technique that we
621 bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx,
622 SideEffectsKind AllowSideEffects = SE_NoSideEffects,
623 bool InConstantContext = false) const;
625 /// EvaluateAsFloat - Return true if this is a constant which we can fold and
626 /// convert to a fixed point value.
627 bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
628 SideEffectsKind AllowSideEffects = SE_NoSideEffects,
629 bool InConstantContext = false) const;
631 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
632 /// constant folded without side-effects, but discard the result.
633 bool isEvaluatable(const ASTContext &Ctx,
634 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
636 /// HasSideEffects - This routine returns true for all those expressions
637 /// which have any effect other than producing a value. Example is a function
638 /// call, volatile variable read, or throwing an exception. If
639 /// IncludePossibleEffects is false, this call treats certain expressions with
640 /// potential side effects (such as function call-like expressions,
641 /// instantiation-dependent expressions, or invocations from a macro) as not
642 /// having side effects.
643 bool HasSideEffects(const ASTContext &Ctx,
644 bool IncludePossibleEffects = true) const;
646 /// Determine whether this expression involves a call to any function
647 /// that is not trivial.
648 bool hasNonTrivialCall(const ASTContext &Ctx) const;
650 /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded
651 /// integer. This must be called on an expression that constant folds to an
653 llvm::APSInt EvaluateKnownConstInt(
654 const ASTContext &Ctx,
655 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
657 llvm::APSInt EvaluateKnownConstIntCheckOverflow(
658 const ASTContext &Ctx,
659 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
661 void EvaluateForOverflow(const ASTContext &Ctx) const;
663 /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an
664 /// lvalue with link time known address, with no side-effects.
665 bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
666 bool InConstantContext = false) const;
668 /// EvaluateAsInitializer - Evaluate an expression as if it were the
669 /// initializer of the given declaration. Returns true if the initializer
670 /// can be folded to a constant, and produces any relevant notes. In C++11,
671 /// notes will be produced if the expression is not a constant expression.
672 bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx,
674 SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
676 /// EvaluateWithSubstitution - Evaluate an expression as if from the context
677 /// of a call to the given function with the given arguments, inside an
678 /// unevaluated context. Returns true if the expression could be folded to a
680 bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
681 const FunctionDecl *Callee,
682 ArrayRef<const Expr*> Args,
683 const Expr *This = nullptr) const;
685 /// Indicates how the constant expression will be used.
686 enum ConstExprUsage { EvaluateForCodeGen, EvaluateForMangling };
688 /// Evaluate an expression that is required to be a constant expression.
689 bool EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
690 const ASTContext &Ctx) const;
692 /// If the current Expr is a pointer, this will try to statically
693 /// determine the number of bytes available where the pointer is pointing.
694 /// Returns true if all of the above holds and we were able to figure out the
695 /// size, false otherwise.
697 /// \param Type - How to evaluate the size of the Expr, as defined by the
698 /// "type" parameter of __builtin_object_size
699 bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
700 unsigned Type) const;
702 /// Enumeration used to describe the kind of Null pointer constant
703 /// returned from \c isNullPointerConstant().
704 enum NullPointerConstantKind {
705 /// Expression is not a Null pointer constant.
708 /// Expression is a Null pointer constant built from a zero integer
709 /// expression that is not a simple, possibly parenthesized, zero literal.
710 /// C++ Core Issue 903 will classify these expressions as "not pointers"
711 /// once it is adopted.
712 /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
715 /// Expression is a Null pointer constant built from a literal zero.
718 /// Expression is a C++11 nullptr.
721 /// Expression is a GNU-style __null constant.
725 /// Enumeration used to describe how \c isNullPointerConstant()
726 /// should cope with value-dependent expressions.
727 enum NullPointerConstantValueDependence {
728 /// Specifies that the expression should never be value-dependent.
729 NPC_NeverValueDependent = 0,
731 /// Specifies that a value-dependent expression of integral or
732 /// dependent type should be considered a null pointer constant.
733 NPC_ValueDependentIsNull,
735 /// Specifies that a value-dependent expression should be considered
736 /// to never be a null pointer constant.
737 NPC_ValueDependentIsNotNull
740 /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to
741 /// a Null pointer constant. The return value can further distinguish the
742 /// kind of NULL pointer constant that was detected.
743 NullPointerConstantKind isNullPointerConstant(
745 NullPointerConstantValueDependence NPC) const;
747 /// isOBJCGCCandidate - Return true if this expression may be used in a read/
749 bool isOBJCGCCandidate(ASTContext &Ctx) const;
751 /// Returns true if this expression is a bound member function.
752 bool isBoundMemberFunction(ASTContext &Ctx) const;
754 /// Given an expression of bound-member type, find the type
755 /// of the member. Returns null if this is an *overloaded* bound
756 /// member expression.
757 static QualType findBoundMemberType(const Expr *expr);
759 /// Skip past any implicit casts which might surround this expression until
760 /// reaching a fixed point. Skips:
761 /// * ImplicitCastExpr
763 Expr *IgnoreImpCasts() LLVM_READONLY;
764 const Expr *IgnoreImpCasts() const {
765 return const_cast<Expr *>(this)->IgnoreImpCasts();
768 /// Skip past any casts which might surround this expression until reaching
769 /// a fixed point. Skips:
772 /// * MaterializeTemporaryExpr
773 /// * SubstNonTypeTemplateParmExpr
774 Expr *IgnoreCasts() LLVM_READONLY;
775 const Expr *IgnoreCasts() const {
776 return const_cast<Expr *>(this)->IgnoreCasts();
779 /// Skip past any implicit AST nodes which might surround this expression
780 /// until reaching a fixed point. Skips:
781 /// * What IgnoreImpCasts() skips
782 /// * MaterializeTemporaryExpr
783 /// * CXXBindTemporaryExpr
784 Expr *IgnoreImplicit() LLVM_READONLY;
785 const Expr *IgnoreImplicit() const {
786 return const_cast<Expr *>(this)->IgnoreImplicit();
789 /// Skip past any parentheses which might surround this expression until
790 /// reaching a fixed point. Skips:
792 /// * UnaryOperator if `UO_Extension`
793 /// * GenericSelectionExpr if `!isResultDependent()`
794 /// * ChooseExpr if `!isConditionDependent()`
796 Expr *IgnoreParens() LLVM_READONLY;
797 const Expr *IgnoreParens() const {
798 return const_cast<Expr *>(this)->IgnoreParens();
801 /// Skip past any parentheses and implicit casts which might surround this
802 /// expression until reaching a fixed point.
803 /// FIXME: IgnoreParenImpCasts really ought to be equivalent to
804 /// IgnoreParens() + IgnoreImpCasts() until reaching a fixed point. However
805 /// this is currently not the case. Instead IgnoreParenImpCasts() skips:
806 /// * What IgnoreParens() skips
807 /// * What IgnoreImpCasts() skips
808 /// * MaterializeTemporaryExpr
809 /// * SubstNonTypeTemplateParmExpr
810 Expr *IgnoreParenImpCasts() LLVM_READONLY;
811 const Expr *IgnoreParenImpCasts() const {
812 return const_cast<Expr *>(this)->IgnoreParenImpCasts();
815 /// Skip past any parentheses and casts which might surround this expression
816 /// until reaching a fixed point. Skips:
817 /// * What IgnoreParens() skips
818 /// * What IgnoreCasts() skips
819 Expr *IgnoreParenCasts() LLVM_READONLY;
820 const Expr *IgnoreParenCasts() const {
821 return const_cast<Expr *>(this)->IgnoreParenCasts();
824 /// Skip conversion operators. If this Expr is a call to a conversion
825 /// operator, return the argument.
826 Expr *IgnoreConversionOperator() LLVM_READONLY;
827 const Expr *IgnoreConversionOperator() const {
828 return const_cast<Expr *>(this)->IgnoreConversionOperator();
831 /// Skip past any parentheses and lvalue casts which might surround this
832 /// expression until reaching a fixed point. Skips:
833 /// * What IgnoreParens() skips
834 /// * What IgnoreCasts() skips, except that only lvalue-to-rvalue
835 /// casts are skipped
836 /// FIXME: This is intended purely as a temporary workaround for code
837 /// that hasn't yet been rewritten to do the right thing about those
838 /// casts, and may disappear along with the last internal use.
839 Expr *IgnoreParenLValueCasts() LLVM_READONLY;
840 const Expr *IgnoreParenLValueCasts() const {
841 return const_cast<Expr *>(this)->IgnoreParenLValueCasts();
844 /// Skip past any parenthese and casts which do not change the value
845 /// (including ptr->int casts of the same size) until reaching a fixed point.
847 /// * What IgnoreParens() skips
848 /// * CastExpr which do not change the value
849 /// * SubstNonTypeTemplateParmExpr
850 Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY;
851 const Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) const {
852 return const_cast<Expr *>(this)->IgnoreParenNoopCasts(Ctx);
855 /// Skip past any parentheses and derived-to-base casts until reaching a
856 /// fixed point. Skips:
857 /// * What IgnoreParens() skips
858 /// * CastExpr which represent a derived-to-base cast (CK_DerivedToBase,
859 /// CK_UncheckedDerivedToBase and CK_NoOp)
860 Expr *ignoreParenBaseCasts() LLVM_READONLY;
861 const Expr *ignoreParenBaseCasts() const {
862 return const_cast<Expr *>(this)->ignoreParenBaseCasts();
865 /// Determine whether this expression is a default function argument.
867 /// Default arguments are implicitly generated in the abstract syntax tree
868 /// by semantic analysis for function calls, object constructions, etc. in
869 /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
870 /// this routine also looks through any implicit casts to determine whether
871 /// the expression is a default argument.
872 bool isDefaultArgument() const;
874 /// Determine whether the result of this expression is a
875 /// temporary object of the given class type.
876 bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const;
878 /// Whether this expression is an implicit reference to 'this' in C++.
879 bool isImplicitCXXThis() const;
881 static bool hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs);
883 /// For an expression of class type or pointer to class type,
884 /// return the most derived class decl the expression is known to refer to.
886 /// If this expression is a cast, this method looks through it to find the
887 /// most derived decl that can be inferred from the expression.
888 /// This is valid because derived-to-base conversions have undefined
889 /// behavior if the object isn't dynamically of the derived type.
890 const CXXRecordDecl *getBestDynamicClassType() const;
892 /// Get the inner expression that determines the best dynamic class.
893 /// If this is a prvalue, we guarantee that it is of the most-derived type
894 /// for the object itself.
895 const Expr *getBestDynamicClassTypeExpr() const;
897 /// Walk outwards from an expression we want to bind a reference to and
898 /// find the expression whose lifetime needs to be extended. Record
899 /// the LHSs of comma expressions and adjustments needed along the path.
900 const Expr *skipRValueSubobjectAdjustments(
901 SmallVectorImpl<const Expr *> &CommaLHS,
902 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const;
903 const Expr *skipRValueSubobjectAdjustments() const {
904 SmallVector<const Expr *, 8> CommaLHSs;
905 SmallVector<SubobjectAdjustment, 8> Adjustments;
906 return skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
909 static bool classof(const Stmt *T) {
910 return T->getStmtClass() >= firstExprConstant &&
911 T->getStmtClass() <= lastExprConstant;
915 //===----------------------------------------------------------------------===//
916 // Wrapper Expressions.
917 //===----------------------------------------------------------------------===//
919 /// FullExpr - Represents a "full-expression" node.
920 class FullExpr : public Expr {
924 FullExpr(StmtClass SC, Expr *subexpr)
925 : Expr(SC, subexpr->getType(),
926 subexpr->getValueKind(), subexpr->getObjectKind(),
927 subexpr->isTypeDependent(), subexpr->isValueDependent(),
928 subexpr->isInstantiationDependent(),
929 subexpr->containsUnexpandedParameterPack()), SubExpr(subexpr) {}
930 FullExpr(StmtClass SC, EmptyShell Empty)
933 const Expr *getSubExpr() const { return cast<Expr>(SubExpr); }
934 Expr *getSubExpr() { return cast<Expr>(SubExpr); }
936 /// As with any mutator of the AST, be very careful when modifying an
937 /// existing AST to preserve its invariants.
938 void setSubExpr(Expr *E) { SubExpr = E; }
940 static bool classof(const Stmt *T) {
941 return T->getStmtClass() >= firstFullExprConstant &&
942 T->getStmtClass() <= lastFullExprConstant;
946 /// ConstantExpr - An expression that occurs in a constant context and
947 /// optionally the result of evaluating the expression.
948 class ConstantExpr final
950 private llvm::TrailingObjects<ConstantExpr, APValue, uint64_t> {
951 static_assert(std::is_same<uint64_t, llvm::APInt::WordType>::value,
952 "this class assumes llvm::APInt::WordType is uint64_t for "
953 "trail-allocated storage");
956 /// Describes the kind of result that can be trail-allocated.
957 enum ResultStorageKind { RSK_None, RSK_Int64, RSK_APValue };
960 size_t numTrailingObjects(OverloadToken<APValue>) const {
961 return ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue;
963 size_t numTrailingObjects(OverloadToken<uint64_t>) const {
964 return ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64;
967 void DefaultInit(ResultStorageKind StorageKind);
968 uint64_t &Int64Result() {
969 assert(ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64 &&
971 return *getTrailingObjects<uint64_t>();
973 const uint64_t &Int64Result() const {
974 return const_cast<ConstantExpr *>(this)->Int64Result();
976 APValue &APValueResult() {
977 assert(ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue &&
979 return *getTrailingObjects<APValue>();
981 const APValue &APValueResult() const {
982 return const_cast<ConstantExpr *>(this)->APValueResult();
985 ConstantExpr(Expr *subexpr, ResultStorageKind StorageKind);
986 ConstantExpr(ResultStorageKind StorageKind, EmptyShell Empty);
989 friend TrailingObjects;
990 friend class ASTStmtReader;
991 friend class ASTStmtWriter;
992 static ConstantExpr *Create(const ASTContext &Context, Expr *E,
993 const APValue &Result);
994 static ConstantExpr *Create(const ASTContext &Context, Expr *E,
995 ResultStorageKind Storage = RSK_None);
996 static ConstantExpr *CreateEmpty(const ASTContext &Context,
997 ResultStorageKind StorageKind,
1000 static ResultStorageKind getStorageKind(const APValue &Value);
1001 static ResultStorageKind getStorageKind(const Type *T,
1002 const ASTContext &Context);
1004 SourceLocation getBeginLoc() const LLVM_READONLY {
1005 return SubExpr->getBeginLoc();
1007 SourceLocation getEndLoc() const LLVM_READONLY {
1008 return SubExpr->getEndLoc();
1011 static bool classof(const Stmt *T) {
1012 return T->getStmtClass() == ConstantExprClass;
1015 void SetResult(APValue Value, const ASTContext &Context) {
1016 MoveIntoResult(Value, Context);
1018 void MoveIntoResult(APValue &Value, const ASTContext &Context);
1020 APValue::ValueKind getResultAPValueKind() const {
1021 return static_cast<APValue::ValueKind>(ConstantExprBits.APValueKind);
1023 ResultStorageKind getResultStorageKind() const {
1024 return static_cast<ResultStorageKind>(ConstantExprBits.ResultKind);
1026 APValue getAPValueResult() const;
1027 const APValue &getResultAsAPValue() const { return APValueResult(); }
1028 llvm::APSInt getResultAsAPSInt() const;
1030 child_range children() { return child_range(&SubExpr, &SubExpr+1); }
1031 const_child_range children() const {
1032 return const_child_range(&SubExpr, &SubExpr + 1);
1036 //===----------------------------------------------------------------------===//
1037 // Primary Expressions.
1038 //===----------------------------------------------------------------------===//
1040 /// OpaqueValueExpr - An expression referring to an opaque object of a
1041 /// fixed type and value class. These don't correspond to concrete
1042 /// syntax; instead they're used to express operations (usually copy
1043 /// operations) on values whose source is generally obvious from
1045 class OpaqueValueExpr : public Expr {
1046 friend class ASTStmtReader;
1050 OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK,
1051 ExprObjectKind OK = OK_Ordinary,
1052 Expr *SourceExpr = nullptr)
1053 : Expr(OpaqueValueExprClass, T, VK, OK,
1054 T->isDependentType() ||
1055 (SourceExpr && SourceExpr->isTypeDependent()),
1056 T->isDependentType() ||
1057 (SourceExpr && SourceExpr->isValueDependent()),
1058 T->isInstantiationDependentType() ||
1059 (SourceExpr && SourceExpr->isInstantiationDependent()),
1061 SourceExpr(SourceExpr) {
1063 OpaqueValueExprBits.Loc = Loc;
1066 /// Given an expression which invokes a copy constructor --- i.e. a
1067 /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups ---
1068 /// find the OpaqueValueExpr that's the source of the construction.
1069 static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr);
1071 explicit OpaqueValueExpr(EmptyShell Empty)
1072 : Expr(OpaqueValueExprClass, Empty) {}
1074 /// Retrieve the location of this expression.
1075 SourceLocation getLocation() const { return OpaqueValueExprBits.Loc; }
1077 SourceLocation getBeginLoc() const LLVM_READONLY {
1078 return SourceExpr ? SourceExpr->getBeginLoc() : getLocation();
1080 SourceLocation getEndLoc() const LLVM_READONLY {
1081 return SourceExpr ? SourceExpr->getEndLoc() : getLocation();
1083 SourceLocation getExprLoc() const LLVM_READONLY {
1084 return SourceExpr ? SourceExpr->getExprLoc() : getLocation();
1087 child_range children() {
1088 return child_range(child_iterator(), child_iterator());
1091 const_child_range children() const {
1092 return const_child_range(const_child_iterator(), const_child_iterator());
1095 /// The source expression of an opaque value expression is the
1096 /// expression which originally generated the value. This is
1097 /// provided as a convenience for analyses that don't wish to
1098 /// precisely model the execution behavior of the program.
1100 /// The source expression is typically set when building the
1101 /// expression which binds the opaque value expression in the first
1103 Expr *getSourceExpr() const { return SourceExpr; }
1105 void setIsUnique(bool V) {
1106 assert((!V || SourceExpr) &&
1107 "unique OVEs are expected to have source expressions");
1108 OpaqueValueExprBits.IsUnique = V;
1111 bool isUnique() const { return OpaqueValueExprBits.IsUnique; }
1113 static bool classof(const Stmt *T) {
1114 return T->getStmtClass() == OpaqueValueExprClass;
1118 /// A reference to a declared variable, function, enum, etc.
1121 /// This encodes all the information about how a declaration is referenced
1122 /// within an expression.
1124 /// There are several optional constructs attached to DeclRefExprs only when
1125 /// they apply in order to conserve memory. These are laid out past the end of
1126 /// the object, and flags in the DeclRefExprBitfield track whether they exist:
1128 /// DeclRefExprBits.HasQualifier:
1129 /// Specifies when this declaration reference expression has a C++
1130 /// nested-name-specifier.
1131 /// DeclRefExprBits.HasFoundDecl:
1132 /// Specifies when this declaration reference expression has a record of
1133 /// a NamedDecl (different from the referenced ValueDecl) which was found
1134 /// during name lookup and/or overload resolution.
1135 /// DeclRefExprBits.HasTemplateKWAndArgsInfo:
1136 /// Specifies when this declaration reference expression has an explicit
1137 /// C++ template keyword and/or template argument list.
1138 /// DeclRefExprBits.RefersToEnclosingVariableOrCapture
1139 /// Specifies when this declaration reference expression (validly)
1140 /// refers to an enclosed local or a captured variable.
1141 class DeclRefExpr final
1143 private llvm::TrailingObjects<DeclRefExpr, NestedNameSpecifierLoc,
1144 NamedDecl *, ASTTemplateKWAndArgsInfo,
1145 TemplateArgumentLoc> {
1146 friend class ASTStmtReader;
1147 friend class ASTStmtWriter;
1148 friend TrailingObjects;
1150 /// The declaration that we are referencing.
1153 /// Provides source/type location info for the declaration name
1155 DeclarationNameLoc DNLoc;
1157 size_t numTrailingObjects(OverloadToken<NestedNameSpecifierLoc>) const {
1158 return hasQualifier();
1161 size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
1162 return hasFoundDecl();
1165 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
1166 return hasTemplateKWAndArgsInfo();
1169 /// Test whether there is a distinct FoundDecl attached to the end of
1171 bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; }
1173 DeclRefExpr(const ASTContext &Ctx, NestedNameSpecifierLoc QualifierLoc,
1174 SourceLocation TemplateKWLoc, ValueDecl *D,
1175 bool RefersToEnlosingVariableOrCapture,
1176 const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
1177 const TemplateArgumentListInfo *TemplateArgs, QualType T,
1178 ExprValueKind VK, NonOdrUseReason NOUR);
1180 /// Construct an empty declaration reference expression.
1181 explicit DeclRefExpr(EmptyShell Empty) : Expr(DeclRefExprClass, Empty) {}
1183 /// Computes the type- and value-dependence flags for this
1184 /// declaration reference expression.
1185 void computeDependence(const ASTContext &Ctx);
1188 DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
1189 bool RefersToEnclosingVariableOrCapture, QualType T,
1190 ExprValueKind VK, SourceLocation L,
1191 const DeclarationNameLoc &LocInfo = DeclarationNameLoc(),
1192 NonOdrUseReason NOUR = NOUR_None);
1194 static DeclRefExpr *
1195 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1196 SourceLocation TemplateKWLoc, ValueDecl *D,
1197 bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc,
1198 QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr,
1199 const TemplateArgumentListInfo *TemplateArgs = nullptr,
1200 NonOdrUseReason NOUR = NOUR_None);
1202 static DeclRefExpr *
1203 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1204 SourceLocation TemplateKWLoc, ValueDecl *D,
1205 bool RefersToEnclosingVariableOrCapture,
1206 const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK,
1207 NamedDecl *FoundD = nullptr,
1208 const TemplateArgumentListInfo *TemplateArgs = nullptr,
1209 NonOdrUseReason NOUR = NOUR_None);
1211 /// Construct an empty declaration reference expression.
1212 static DeclRefExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier,
1214 bool HasTemplateKWAndArgsInfo,
1215 unsigned NumTemplateArgs);
1217 ValueDecl *getDecl() { return D; }
1218 const ValueDecl *getDecl() const { return D; }
1219 void setDecl(ValueDecl *NewD) { D = NewD; }
1221 DeclarationNameInfo getNameInfo() const {
1222 return DeclarationNameInfo(getDecl()->getDeclName(), getLocation(), DNLoc);
1225 SourceLocation getLocation() const { return DeclRefExprBits.Loc; }
1226 void setLocation(SourceLocation L) { DeclRefExprBits.Loc = L; }
1227 SourceLocation getBeginLoc() const LLVM_READONLY;
1228 SourceLocation getEndLoc() const LLVM_READONLY;
1230 /// Determine whether this declaration reference was preceded by a
1231 /// C++ nested-name-specifier, e.g., \c N::foo.
1232 bool hasQualifier() const { return DeclRefExprBits.HasQualifier; }
1234 /// If the name was qualified, retrieves the nested-name-specifier
1235 /// that precedes the name, with source-location information.
1236 NestedNameSpecifierLoc getQualifierLoc() const {
1237 if (!hasQualifier())
1238 return NestedNameSpecifierLoc();
1239 return *getTrailingObjects<NestedNameSpecifierLoc>();
1242 /// If the name was qualified, retrieves the nested-name-specifier
1243 /// that precedes the name. Otherwise, returns NULL.
1244 NestedNameSpecifier *getQualifier() const {
1245 return getQualifierLoc().getNestedNameSpecifier();
1248 /// Get the NamedDecl through which this reference occurred.
1250 /// This Decl may be different from the ValueDecl actually referred to in the
1251 /// presence of using declarations, etc. It always returns non-NULL, and may
1252 /// simple return the ValueDecl when appropriate.
1254 NamedDecl *getFoundDecl() {
1255 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1258 /// Get the NamedDecl through which this reference occurred.
1259 /// See non-const variant.
1260 const NamedDecl *getFoundDecl() const {
1261 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1264 bool hasTemplateKWAndArgsInfo() const {
1265 return DeclRefExprBits.HasTemplateKWAndArgsInfo;
1268 /// Retrieve the location of the template keyword preceding
1269 /// this name, if any.
1270 SourceLocation getTemplateKeywordLoc() const {
1271 if (!hasTemplateKWAndArgsInfo())
1272 return SourceLocation();
1273 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
1276 /// Retrieve the location of the left angle bracket starting the
1277 /// explicit template argument list following the name, if any.
1278 SourceLocation getLAngleLoc() const {
1279 if (!hasTemplateKWAndArgsInfo())
1280 return SourceLocation();
1281 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
1284 /// Retrieve the location of the right angle bracket ending the
1285 /// explicit template argument list following the name, if any.
1286 SourceLocation getRAngleLoc() const {
1287 if (!hasTemplateKWAndArgsInfo())
1288 return SourceLocation();
1289 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
1292 /// Determines whether the name in this declaration reference
1293 /// was preceded by the template keyword.
1294 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
1296 /// Determines whether this declaration reference was followed by an
1297 /// explicit template argument list.
1298 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
1300 /// Copies the template arguments (if present) into the given
1302 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
1303 if (hasExplicitTemplateArgs())
1304 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
1305 getTrailingObjects<TemplateArgumentLoc>(), List);
1308 /// Retrieve the template arguments provided as part of this
1310 const TemplateArgumentLoc *getTemplateArgs() const {
1311 if (!hasExplicitTemplateArgs())
1313 return getTrailingObjects<TemplateArgumentLoc>();
1316 /// Retrieve the number of template arguments provided as part of this
1318 unsigned getNumTemplateArgs() const {
1319 if (!hasExplicitTemplateArgs())
1321 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
1324 ArrayRef<TemplateArgumentLoc> template_arguments() const {
1325 return {getTemplateArgs(), getNumTemplateArgs()};
1328 /// Returns true if this expression refers to a function that
1329 /// was resolved from an overloaded set having size greater than 1.
1330 bool hadMultipleCandidates() const {
1331 return DeclRefExprBits.HadMultipleCandidates;
1333 /// Sets the flag telling whether this expression refers to
1334 /// a function that was resolved from an overloaded set having size
1336 void setHadMultipleCandidates(bool V = true) {
1337 DeclRefExprBits.HadMultipleCandidates = V;
1340 /// Is this expression a non-odr-use reference, and if so, why?
1341 NonOdrUseReason isNonOdrUse() const {
1342 return static_cast<NonOdrUseReason>(DeclRefExprBits.NonOdrUseReason);
1345 /// Does this DeclRefExpr refer to an enclosing local or a captured
1347 bool refersToEnclosingVariableOrCapture() const {
1348 return DeclRefExprBits.RefersToEnclosingVariableOrCapture;
1351 static bool classof(const Stmt *T) {
1352 return T->getStmtClass() == DeclRefExprClass;
1356 child_range children() {
1357 return child_range(child_iterator(), child_iterator());
1360 const_child_range children() const {
1361 return const_child_range(const_child_iterator(), const_child_iterator());
1365 /// Used by IntegerLiteral/FloatingLiteral to store the numeric without
1368 /// For large floats/integers, APFloat/APInt will allocate memory from the heap
1369 /// to represent these numbers. Unfortunately, when we use a BumpPtrAllocator
1370 /// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with
1371 /// the APFloat/APInt values will never get freed. APNumericStorage uses
1372 /// ASTContext's allocator for memory allocation.
1373 class APNumericStorage {
1375 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
1376 uint64_t *pVal; ///< Used to store the >64 bits integer value.
1380 bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; }
1382 APNumericStorage(const APNumericStorage &) = delete;
1383 void operator=(const APNumericStorage &) = delete;
1386 APNumericStorage() : VAL(0), BitWidth(0) { }
1388 llvm::APInt getIntValue() const {
1389 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1391 return llvm::APInt(BitWidth, NumWords, pVal);
1393 return llvm::APInt(BitWidth, VAL);
1395 void setIntValue(const ASTContext &C, const llvm::APInt &Val);
1398 class APIntStorage : private APNumericStorage {
1400 llvm::APInt getValue() const { return getIntValue(); }
1401 void setValue(const ASTContext &C, const llvm::APInt &Val) {
1402 setIntValue(C, Val);
1406 class APFloatStorage : private APNumericStorage {
1408 llvm::APFloat getValue(const llvm::fltSemantics &Semantics) const {
1409 return llvm::APFloat(Semantics, getIntValue());
1411 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1412 setIntValue(C, Val.bitcastToAPInt());
1416 class IntegerLiteral : public Expr, public APIntStorage {
1419 /// Construct an empty integer literal.
1420 explicit IntegerLiteral(EmptyShell Empty)
1421 : Expr(IntegerLiteralClass, Empty) { }
1424 // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
1425 // or UnsignedLongLongTy
1426 IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1429 /// Returns a new integer literal with value 'V' and type 'type'.
1430 /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy,
1431 /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V
1432 /// \param V - the value that the returned integer literal contains.
1433 static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V,
1434 QualType type, SourceLocation l);
1435 /// Returns a new empty integer literal.
1436 static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty);
1438 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1439 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1441 /// Retrieve the location of the literal.
1442 SourceLocation getLocation() const { return Loc; }
1444 void setLocation(SourceLocation Location) { Loc = Location; }
1446 static bool classof(const Stmt *T) {
1447 return T->getStmtClass() == IntegerLiteralClass;
1451 child_range children() {
1452 return child_range(child_iterator(), child_iterator());
1454 const_child_range children() const {
1455 return const_child_range(const_child_iterator(), const_child_iterator());
1459 class FixedPointLiteral : public Expr, public APIntStorage {
1463 /// \brief Construct an empty integer literal.
1464 explicit FixedPointLiteral(EmptyShell Empty)
1465 : Expr(FixedPointLiteralClass, Empty) {}
1468 FixedPointLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1469 SourceLocation l, unsigned Scale);
1471 // Store the int as is without any bit shifting.
1472 static FixedPointLiteral *CreateFromRawInt(const ASTContext &C,
1473 const llvm::APInt &V,
1474 QualType type, SourceLocation l,
1477 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1478 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1480 /// \brief Retrieve the location of the literal.
1481 SourceLocation getLocation() const { return Loc; }
1483 void setLocation(SourceLocation Location) { Loc = Location; }
1485 static bool classof(const Stmt *T) {
1486 return T->getStmtClass() == FixedPointLiteralClass;
1489 std::string getValueAsString(unsigned Radix) const;
1492 child_range children() {
1493 return child_range(child_iterator(), child_iterator());
1495 const_child_range children() const {
1496 return const_child_range(const_child_iterator(), const_child_iterator());
1500 class CharacterLiteral : public Expr {
1502 enum CharacterKind {
1514 // type should be IntTy
1515 CharacterLiteral(unsigned value, CharacterKind kind, QualType type,
1517 : Expr(CharacterLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
1519 Value(value), Loc(l) {
1520 CharacterLiteralBits.Kind = kind;
1523 /// Construct an empty character literal.
1524 CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
1526 SourceLocation getLocation() const { return Loc; }
1527 CharacterKind getKind() const {
1528 return static_cast<CharacterKind>(CharacterLiteralBits.Kind);
1531 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1532 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1534 unsigned getValue() const { return Value; }
1536 void setLocation(SourceLocation Location) { Loc = Location; }
1537 void setKind(CharacterKind kind) { CharacterLiteralBits.Kind = kind; }
1538 void setValue(unsigned Val) { Value = Val; }
1540 static bool classof(const Stmt *T) {
1541 return T->getStmtClass() == CharacterLiteralClass;
1545 child_range children() {
1546 return child_range(child_iterator(), child_iterator());
1548 const_child_range children() const {
1549 return const_child_range(const_child_iterator(), const_child_iterator());
1553 class FloatingLiteral : public Expr, private APFloatStorage {
1556 FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact,
1557 QualType Type, SourceLocation L);
1559 /// Construct an empty floating-point literal.
1560 explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty);
1563 static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V,
1564 bool isexact, QualType Type, SourceLocation L);
1565 static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty);
1567 llvm::APFloat getValue() const {
1568 return APFloatStorage::getValue(getSemantics());
1570 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1571 assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics");
1572 APFloatStorage::setValue(C, Val);
1575 /// Get a raw enumeration value representing the floating-point semantics of
1576 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1577 llvm::APFloatBase::Semantics getRawSemantics() const {
1578 return static_cast<llvm::APFloatBase::Semantics>(
1579 FloatingLiteralBits.Semantics);
1582 /// Set the raw enumeration value representing the floating-point semantics of
1583 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1584 void setRawSemantics(llvm::APFloatBase::Semantics Sem) {
1585 FloatingLiteralBits.Semantics = Sem;
1588 /// Return the APFloat semantics this literal uses.
1589 const llvm::fltSemantics &getSemantics() const {
1590 return llvm::APFloatBase::EnumToSemantics(
1591 static_cast<llvm::APFloatBase::Semantics>(
1592 FloatingLiteralBits.Semantics));
1595 /// Set the APFloat semantics this literal uses.
1596 void setSemantics(const llvm::fltSemantics &Sem) {
1597 FloatingLiteralBits.Semantics = llvm::APFloatBase::SemanticsToEnum(Sem);
1600 bool isExact() const { return FloatingLiteralBits.IsExact; }
1601 void setExact(bool E) { FloatingLiteralBits.IsExact = E; }
1603 /// getValueAsApproximateDouble - This returns the value as an inaccurate
1604 /// double. Note that this may cause loss of precision, but is useful for
1605 /// debugging dumps, etc.
1606 double getValueAsApproximateDouble() const;
1608 SourceLocation getLocation() const { return Loc; }
1609 void setLocation(SourceLocation L) { Loc = L; }
1611 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1612 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1614 static bool classof(const Stmt *T) {
1615 return T->getStmtClass() == FloatingLiteralClass;
1619 child_range children() {
1620 return child_range(child_iterator(), child_iterator());
1622 const_child_range children() const {
1623 return const_child_range(const_child_iterator(), const_child_iterator());
1627 /// ImaginaryLiteral - We support imaginary integer and floating point literals,
1628 /// like "1.0i". We represent these as a wrapper around FloatingLiteral and
1629 /// IntegerLiteral classes. Instances of this class always have a Complex type
1630 /// whose element type matches the subexpression.
1632 class ImaginaryLiteral : public Expr {
1635 ImaginaryLiteral(Expr *val, QualType Ty)
1636 : Expr(ImaginaryLiteralClass, Ty, VK_RValue, OK_Ordinary, false, false,
1640 /// Build an empty imaginary literal.
1641 explicit ImaginaryLiteral(EmptyShell Empty)
1642 : Expr(ImaginaryLiteralClass, Empty) { }
1644 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1645 Expr *getSubExpr() { return cast<Expr>(Val); }
1646 void setSubExpr(Expr *E) { Val = E; }
1648 SourceLocation getBeginLoc() const LLVM_READONLY {
1649 return Val->getBeginLoc();
1651 SourceLocation getEndLoc() const LLVM_READONLY { return Val->getEndLoc(); }
1653 static bool classof(const Stmt *T) {
1654 return T->getStmtClass() == ImaginaryLiteralClass;
1658 child_range children() { return child_range(&Val, &Val+1); }
1659 const_child_range children() const {
1660 return const_child_range(&Val, &Val + 1);
1664 /// StringLiteral - This represents a string literal expression, e.g. "foo"
1665 /// or L"bar" (wide strings). The actual string data can be obtained with
1666 /// getBytes() and is NOT null-terminated. The length of the string data is
1667 /// determined by calling getByteLength().
1669 /// The C type for a string is always a ConstantArrayType. In C++, the char
1670 /// type is const qualified, in C it is not.
1672 /// Note that strings in C can be formed by concatenation of multiple string
1673 /// literal pptokens in translation phase #6. This keeps track of the locations
1674 /// of each of these pieces.
1676 /// Strings in C can also be truncated and extended by assigning into arrays,
1677 /// e.g. with constructs like:
1678 /// char X[2] = "foobar";
1679 /// In this case, getByteLength() will return 6, but the string literal will
1680 /// have type "char[2]".
1681 class StringLiteral final
1683 private llvm::TrailingObjects<StringLiteral, unsigned, SourceLocation,
1685 friend class ASTStmtReader;
1686 friend TrailingObjects;
1688 /// StringLiteral is followed by several trailing objects. They are in order:
1690 /// * A single unsigned storing the length in characters of this string. The
1691 /// length in bytes is this length times the width of a single character.
1692 /// Always present and stored as a trailing objects because storing it in
1693 /// StringLiteral would increase the size of StringLiteral by sizeof(void *)
1694 /// due to alignment requirements. If you add some data to StringLiteral,
1695 /// consider moving it inside StringLiteral.
1697 /// * An array of getNumConcatenated() SourceLocation, one for each of the
1698 /// token this string is made of.
1700 /// * An array of getByteLength() char used to store the string data.
1703 enum StringKind { Ascii, Wide, UTF8, UTF16, UTF32 };
1706 unsigned numTrailingObjects(OverloadToken<unsigned>) const { return 1; }
1707 unsigned numTrailingObjects(OverloadToken<SourceLocation>) const {
1708 return getNumConcatenated();
1711 unsigned numTrailingObjects(OverloadToken<char>) const {
1712 return getByteLength();
1715 char *getStrDataAsChar() { return getTrailingObjects<char>(); }
1716 const char *getStrDataAsChar() const { return getTrailingObjects<char>(); }
1718 const uint16_t *getStrDataAsUInt16() const {
1719 return reinterpret_cast<const uint16_t *>(getTrailingObjects<char>());
1722 const uint32_t *getStrDataAsUInt32() const {
1723 return reinterpret_cast<const uint32_t *>(getTrailingObjects<char>());
1726 /// Build a string literal.
1727 StringLiteral(const ASTContext &Ctx, StringRef Str, StringKind Kind,
1728 bool Pascal, QualType Ty, const SourceLocation *Loc,
1729 unsigned NumConcatenated);
1731 /// Build an empty string literal.
1732 StringLiteral(EmptyShell Empty, unsigned NumConcatenated, unsigned Length,
1733 unsigned CharByteWidth);
1735 /// Map a target and string kind to the appropriate character width.
1736 static unsigned mapCharByteWidth(TargetInfo const &Target, StringKind SK);
1738 /// Set one of the string literal token.
1739 void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1740 assert(TokNum < getNumConcatenated() && "Invalid tok number");
1741 getTrailingObjects<SourceLocation>()[TokNum] = L;
1745 /// This is the "fully general" constructor that allows representation of
1746 /// strings formed from multiple concatenated tokens.
1747 static StringLiteral *Create(const ASTContext &Ctx, StringRef Str,
1748 StringKind Kind, bool Pascal, QualType Ty,
1749 const SourceLocation *Loc,
1750 unsigned NumConcatenated);
1752 /// Simple constructor for string literals made from one token.
1753 static StringLiteral *Create(const ASTContext &Ctx, StringRef Str,
1754 StringKind Kind, bool Pascal, QualType Ty,
1755 SourceLocation Loc) {
1756 return Create(Ctx, Str, Kind, Pascal, Ty, &Loc, 1);
1759 /// Construct an empty string literal.
1760 static StringLiteral *CreateEmpty(const ASTContext &Ctx,
1761 unsigned NumConcatenated, unsigned Length,
1762 unsigned CharByteWidth);
1764 StringRef getString() const {
1765 assert(getCharByteWidth() == 1 &&
1766 "This function is used in places that assume strings use char");
1767 return StringRef(getStrDataAsChar(), getByteLength());
1770 /// Allow access to clients that need the byte representation, such as
1771 /// ASTWriterStmt::VisitStringLiteral().
1772 StringRef getBytes() const {
1773 // FIXME: StringRef may not be the right type to use as a result for this.
1774 return StringRef(getStrDataAsChar(), getByteLength());
1777 void outputString(raw_ostream &OS) const;
1779 uint32_t getCodeUnit(size_t i) const {
1780 assert(i < getLength() && "out of bounds access");
1781 switch (getCharByteWidth()) {
1783 return static_cast<unsigned char>(getStrDataAsChar()[i]);
1785 return getStrDataAsUInt16()[i];
1787 return getStrDataAsUInt32()[i];
1789 llvm_unreachable("Unsupported character width!");
1792 unsigned getByteLength() const { return getCharByteWidth() * getLength(); }
1793 unsigned getLength() const { return *getTrailingObjects<unsigned>(); }
1794 unsigned getCharByteWidth() const { return StringLiteralBits.CharByteWidth; }
1796 StringKind getKind() const {
1797 return static_cast<StringKind>(StringLiteralBits.Kind);
1800 bool isAscii() const { return getKind() == Ascii; }
1801 bool isWide() const { return getKind() == Wide; }
1802 bool isUTF8() const { return getKind() == UTF8; }
1803 bool isUTF16() const { return getKind() == UTF16; }
1804 bool isUTF32() const { return getKind() == UTF32; }
1805 bool isPascal() const { return StringLiteralBits.IsPascal; }
1807 bool containsNonAscii() const {
1808 for (auto c : getString())
1814 bool containsNonAsciiOrNull() const {
1815 for (auto c : getString())
1816 if (!isASCII(c) || !c)
1821 /// getNumConcatenated - Get the number of string literal tokens that were
1822 /// concatenated in translation phase #6 to form this string literal.
1823 unsigned getNumConcatenated() const {
1824 return StringLiteralBits.NumConcatenated;
1827 /// Get one of the string literal token.
1828 SourceLocation getStrTokenLoc(unsigned TokNum) const {
1829 assert(TokNum < getNumConcatenated() && "Invalid tok number");
1830 return getTrailingObjects<SourceLocation>()[TokNum];
1833 /// getLocationOfByte - Return a source location that points to the specified
1834 /// byte of this string literal.
1836 /// Strings are amazingly complex. They can be formed from multiple tokens
1837 /// and can have escape sequences in them in addition to the usual trigraph
1838 /// and escaped newline business. This routine handles this complexity.
1841 getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1842 const LangOptions &Features, const TargetInfo &Target,
1843 unsigned *StartToken = nullptr,
1844 unsigned *StartTokenByteOffset = nullptr) const;
1846 typedef const SourceLocation *tokloc_iterator;
1848 tokloc_iterator tokloc_begin() const {
1849 return getTrailingObjects<SourceLocation>();
1852 tokloc_iterator tokloc_end() const {
1853 return getTrailingObjects<SourceLocation>() + getNumConcatenated();
1856 SourceLocation getBeginLoc() const LLVM_READONLY { return *tokloc_begin(); }
1857 SourceLocation getEndLoc() const LLVM_READONLY { return *(tokloc_end() - 1); }
1859 static bool classof(const Stmt *T) {
1860 return T->getStmtClass() == StringLiteralClass;
1864 child_range children() {
1865 return child_range(child_iterator(), child_iterator());
1867 const_child_range children() const {
1868 return const_child_range(const_child_iterator(), const_child_iterator());
1872 /// [C99 6.4.2.2] - A predefined identifier such as __func__.
1873 class PredefinedExpr final
1875 private llvm::TrailingObjects<PredefinedExpr, Stmt *> {
1876 friend class ASTStmtReader;
1877 friend TrailingObjects;
1879 // PredefinedExpr is optionally followed by a single trailing
1880 // "Stmt *" for the predefined identifier. It is present if and only if
1881 // hasFunctionName() is true and is always a "StringLiteral *".
1887 LFunction, // Same as Function, but as wide string.
1890 LFuncSig, // Same as FuncSig, but as as wide string
1892 /// The same as PrettyFunction, except that the
1893 /// 'virtual' keyword is omitted for virtual member functions.
1894 PrettyFunctionNoVirtual
1898 PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK,
1901 explicit PredefinedExpr(EmptyShell Empty, bool HasFunctionName);
1903 /// True if this PredefinedExpr has storage for a function name.
1904 bool hasFunctionName() const { return PredefinedExprBits.HasFunctionName; }
1906 void setFunctionName(StringLiteral *SL) {
1907 assert(hasFunctionName() &&
1908 "This PredefinedExpr has no storage for a function name!");
1909 *getTrailingObjects<Stmt *>() = SL;
1913 /// Create a PredefinedExpr.
1914 static PredefinedExpr *Create(const ASTContext &Ctx, SourceLocation L,
1915 QualType FNTy, IdentKind IK, StringLiteral *SL);
1917 /// Create an empty PredefinedExpr.
1918 static PredefinedExpr *CreateEmpty(const ASTContext &Ctx,
1919 bool HasFunctionName);
1921 IdentKind getIdentKind() const {
1922 return static_cast<IdentKind>(PredefinedExprBits.Kind);
1925 SourceLocation getLocation() const { return PredefinedExprBits.Loc; }
1926 void setLocation(SourceLocation L) { PredefinedExprBits.Loc = L; }
1928 StringLiteral *getFunctionName() {
1929 return hasFunctionName()
1930 ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>())
1934 const StringLiteral *getFunctionName() const {
1935 return hasFunctionName()
1936 ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>())
1940 static StringRef getIdentKindName(IdentKind IK);
1941 static std::string ComputeName(IdentKind IK, const Decl *CurrentDecl);
1943 SourceLocation getBeginLoc() const { return getLocation(); }
1944 SourceLocation getEndLoc() const { return getLocation(); }
1946 static bool classof(const Stmt *T) {
1947 return T->getStmtClass() == PredefinedExprClass;
1951 child_range children() {
1952 return child_range(getTrailingObjects<Stmt *>(),
1953 getTrailingObjects<Stmt *>() + hasFunctionName());
1956 const_child_range children() const {
1957 return const_child_range(getTrailingObjects<Stmt *>(),
1958 getTrailingObjects<Stmt *>() + hasFunctionName());
1962 /// ParenExpr - This represents a parethesized expression, e.g. "(1)". This
1963 /// AST node is only formed if full location information is requested.
1964 class ParenExpr : public Expr {
1965 SourceLocation L, R;
1968 ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
1969 : Expr(ParenExprClass, val->getType(),
1970 val->getValueKind(), val->getObjectKind(),
1971 val->isTypeDependent(), val->isValueDependent(),
1972 val->isInstantiationDependent(),
1973 val->containsUnexpandedParameterPack()),
1974 L(l), R(r), Val(val) {}
1976 /// Construct an empty parenthesized expression.
1977 explicit ParenExpr(EmptyShell Empty)
1978 : Expr(ParenExprClass, Empty) { }
1980 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1981 Expr *getSubExpr() { return cast<Expr>(Val); }
1982 void setSubExpr(Expr *E) { Val = E; }
1984 SourceLocation getBeginLoc() const LLVM_READONLY { return L; }
1985 SourceLocation getEndLoc() const LLVM_READONLY { return R; }
1987 /// Get the location of the left parentheses '('.
1988 SourceLocation getLParen() const { return L; }
1989 void setLParen(SourceLocation Loc) { L = Loc; }
1991 /// Get the location of the right parentheses ')'.
1992 SourceLocation getRParen() const { return R; }
1993 void setRParen(SourceLocation Loc) { R = Loc; }
1995 static bool classof(const Stmt *T) {
1996 return T->getStmtClass() == ParenExprClass;
2000 child_range children() { return child_range(&Val, &Val+1); }
2001 const_child_range children() const {
2002 return const_child_range(&Val, &Val + 1);
2006 /// UnaryOperator - This represents the unary-expression's (except sizeof and
2007 /// alignof), the postinc/postdec operators from postfix-expression, and various
2010 /// Notes on various nodes:
2012 /// Real/Imag - These return the real/imag part of a complex operand. If
2013 /// applied to a non-complex value, the former returns its operand and the
2014 /// later returns zero in the type of the operand.
2016 class UnaryOperator : public Expr {
2020 typedef UnaryOperatorKind Opcode;
2022 UnaryOperator(Expr *input, Opcode opc, QualType type, ExprValueKind VK,
2023 ExprObjectKind OK, SourceLocation l, bool CanOverflow)
2024 : Expr(UnaryOperatorClass, type, VK, OK,
2025 input->isTypeDependent() || type->isDependentType(),
2026 input->isValueDependent(),
2027 (input->isInstantiationDependent() ||
2028 type->isInstantiationDependentType()),
2029 input->containsUnexpandedParameterPack()),
2031 UnaryOperatorBits.Opc = opc;
2032 UnaryOperatorBits.CanOverflow = CanOverflow;
2033 UnaryOperatorBits.Loc = l;
2036 /// Build an empty unary operator.
2037 explicit UnaryOperator(EmptyShell Empty) : Expr(UnaryOperatorClass, Empty) {
2038 UnaryOperatorBits.Opc = UO_AddrOf;
2041 Opcode getOpcode() const {
2042 return static_cast<Opcode>(UnaryOperatorBits.Opc);
2044 void setOpcode(Opcode Opc) { UnaryOperatorBits.Opc = Opc; }
2046 Expr *getSubExpr() const { return cast<Expr>(Val); }
2047 void setSubExpr(Expr *E) { Val = E; }
2049 /// getOperatorLoc - Return the location of the operator.
2050 SourceLocation getOperatorLoc() const { return UnaryOperatorBits.Loc; }
2051 void setOperatorLoc(SourceLocation L) { UnaryOperatorBits.Loc = L; }
2053 /// Returns true if the unary operator can cause an overflow. For instance,
2054 /// signed int i = INT_MAX; i++;
2055 /// signed char c = CHAR_MAX; c++;
2056 /// Due to integer promotions, c++ is promoted to an int before the postfix
2057 /// increment, and the result is an int that cannot overflow. However, i++
2059 bool canOverflow() const { return UnaryOperatorBits.CanOverflow; }
2060 void setCanOverflow(bool C) { UnaryOperatorBits.CanOverflow = C; }
2062 /// isPostfix - Return true if this is a postfix operation, like x++.
2063 static bool isPostfix(Opcode Op) {
2064 return Op == UO_PostInc || Op == UO_PostDec;
2067 /// isPrefix - Return true if this is a prefix operation, like --x.
2068 static bool isPrefix(Opcode Op) {
2069 return Op == UO_PreInc || Op == UO_PreDec;
2072 bool isPrefix() const { return isPrefix(getOpcode()); }
2073 bool isPostfix() const { return isPostfix(getOpcode()); }
2075 static bool isIncrementOp(Opcode Op) {
2076 return Op == UO_PreInc || Op == UO_PostInc;
2078 bool isIncrementOp() const {
2079 return isIncrementOp(getOpcode());
2082 static bool isDecrementOp(Opcode Op) {
2083 return Op == UO_PreDec || Op == UO_PostDec;
2085 bool isDecrementOp() const {
2086 return isDecrementOp(getOpcode());
2089 static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; }
2090 bool isIncrementDecrementOp() const {
2091 return isIncrementDecrementOp(getOpcode());
2094 static bool isArithmeticOp(Opcode Op) {
2095 return Op >= UO_Plus && Op <= UO_LNot;
2097 bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
2099 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2100 /// corresponds to, e.g. "sizeof" or "[pre]++"
2101 static StringRef getOpcodeStr(Opcode Op);
2103 /// Retrieve the unary opcode that corresponds to the given
2104 /// overloaded operator.
2105 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
2107 /// Retrieve the overloaded operator kind that corresponds to
2108 /// the given unary opcode.
2109 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
2111 SourceLocation getBeginLoc() const LLVM_READONLY {
2112 return isPostfix() ? Val->getBeginLoc() : getOperatorLoc();
2114 SourceLocation getEndLoc() const LLVM_READONLY {
2115 return isPostfix() ? getOperatorLoc() : Val->getEndLoc();
2117 SourceLocation getExprLoc() const { return getOperatorLoc(); }
2119 static bool classof(const Stmt *T) {
2120 return T->getStmtClass() == UnaryOperatorClass;
2124 child_range children() { return child_range(&Val, &Val+1); }
2125 const_child_range children() const {
2126 return const_child_range(&Val, &Val + 1);
2130 /// Helper class for OffsetOfExpr.
2132 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
2133 class OffsetOfNode {
2135 /// The kind of offsetof node we have.
2137 /// An index into an array.
2141 /// A field in a dependent type, known only by its name.
2143 /// An implicit indirection through a C++ base class, when the
2144 /// field found is in a base class.
2149 enum { MaskBits = 2, Mask = 0x03 };
2151 /// The source range that covers this part of the designator.
2154 /// The data describing the designator, which comes in three
2155 /// different forms, depending on the lower two bits.
2156 /// - An unsigned index into the array of Expr*'s stored after this node
2157 /// in memory, for [constant-expression] designators.
2158 /// - A FieldDecl*, for references to a known field.
2159 /// - An IdentifierInfo*, for references to a field with a given name
2160 /// when the class type is dependent.
2161 /// - A CXXBaseSpecifier*, for references that look at a field in a
2166 /// Create an offsetof node that refers to an array element.
2167 OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
2168 SourceLocation RBracketLoc)
2169 : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) {}
2171 /// Create an offsetof node that refers to a field.
2172 OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field, SourceLocation NameLoc)
2173 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
2174 Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) {}
2176 /// Create an offsetof node that refers to an identifier.
2177 OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
2178 SourceLocation NameLoc)
2179 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
2180 Data(reinterpret_cast<uintptr_t>(Name) | Identifier) {}
2182 /// Create an offsetof node that refers into a C++ base class.
2183 explicit OffsetOfNode(const CXXBaseSpecifier *Base)
2184 : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
2186 /// Determine what kind of offsetof node this is.
2187 Kind getKind() const { return static_cast<Kind>(Data & Mask); }
2189 /// For an array element node, returns the index into the array
2191 unsigned getArrayExprIndex() const {
2192 assert(getKind() == Array);
2196 /// For a field offsetof node, returns the field.
2197 FieldDecl *getField() const {
2198 assert(getKind() == Field);
2199 return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
2202 /// For a field or identifier offsetof node, returns the name of
2204 IdentifierInfo *getFieldName() const;
2206 /// For a base class node, returns the base specifier.
2207 CXXBaseSpecifier *getBase() const {
2208 assert(getKind() == Base);
2209 return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
2212 /// Retrieve the source range that covers this offsetof node.
2214 /// For an array element node, the source range contains the locations of
2215 /// the square brackets. For a field or identifier node, the source range
2216 /// contains the location of the period (if there is one) and the
2218 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
2219 SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); }
2220 SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); }
2223 /// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
2224 /// offsetof(record-type, member-designator). For example, given:
2235 /// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
2237 class OffsetOfExpr final
2239 private llvm::TrailingObjects<OffsetOfExpr, OffsetOfNode, Expr *> {
2240 SourceLocation OperatorLoc, RParenLoc;
2242 TypeSourceInfo *TSInfo;
2243 // Number of sub-components (i.e. instances of OffsetOfNode).
2245 // Number of sub-expressions (i.e. array subscript expressions).
2248 size_t numTrailingObjects(OverloadToken<OffsetOfNode>) const {
2252 OffsetOfExpr(const ASTContext &C, QualType type,
2253 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
2254 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
2255 SourceLocation RParenLoc);
2257 explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
2258 : Expr(OffsetOfExprClass, EmptyShell()),
2259 TSInfo(nullptr), NumComps(numComps), NumExprs(numExprs) {}
2263 static OffsetOfExpr *Create(const ASTContext &C, QualType type,
2264 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
2265 ArrayRef<OffsetOfNode> comps,
2266 ArrayRef<Expr*> exprs, SourceLocation RParenLoc);
2268 static OffsetOfExpr *CreateEmpty(const ASTContext &C,
2269 unsigned NumComps, unsigned NumExprs);
2271 /// getOperatorLoc - Return the location of the operator.
2272 SourceLocation getOperatorLoc() const { return OperatorLoc; }
2273 void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
2275 /// Return the location of the right parentheses.
2276 SourceLocation getRParenLoc() const { return RParenLoc; }
2277 void setRParenLoc(SourceLocation R) { RParenLoc = R; }
2279 TypeSourceInfo *getTypeSourceInfo() const {
2282 void setTypeSourceInfo(TypeSourceInfo *tsi) {
2286 const OffsetOfNode &getComponent(unsigned Idx) const {
2287 assert(Idx < NumComps && "Subscript out of range");
2288 return getTrailingObjects<OffsetOfNode>()[Idx];
2291 void setComponent(unsigned Idx, OffsetOfNode ON) {
2292 assert(Idx < NumComps && "Subscript out of range");
2293 getTrailingObjects<OffsetOfNode>()[Idx] = ON;
2296 unsigned getNumComponents() const {
2300 Expr* getIndexExpr(unsigned Idx) {
2301 assert(Idx < NumExprs && "Subscript out of range");
2302 return getTrailingObjects<Expr *>()[Idx];
2305 const Expr *getIndexExpr(unsigned Idx) const {
2306 assert(Idx < NumExprs && "Subscript out of range");
2307 return getTrailingObjects<Expr *>()[Idx];
2310 void setIndexExpr(unsigned Idx, Expr* E) {
2311 assert(Idx < NumComps && "Subscript out of range");
2312 getTrailingObjects<Expr *>()[Idx] = E;
2315 unsigned getNumExpressions() const {
2319 SourceLocation getBeginLoc() const LLVM_READONLY { return OperatorLoc; }
2320 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
2322 static bool classof(const Stmt *T) {
2323 return T->getStmtClass() == OffsetOfExprClass;
2327 child_range children() {
2328 Stmt **begin = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>());
2329 return child_range(begin, begin + NumExprs);
2331 const_child_range children() const {
2332 Stmt *const *begin =
2333 reinterpret_cast<Stmt *const *>(getTrailingObjects<Expr *>());
2334 return const_child_range(begin, begin + NumExprs);
2336 friend TrailingObjects;
2339 /// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
2340 /// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and
2341 /// vec_step (OpenCL 1.1 6.11.12).
2342 class UnaryExprOrTypeTraitExpr : public Expr {
2347 SourceLocation OpLoc, RParenLoc;
2350 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo,
2351 QualType resultType, SourceLocation op,
2352 SourceLocation rp) :
2353 Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
2354 false, // Never type-dependent (C++ [temp.dep.expr]p3).
2355 // Value-dependent if the argument is type-dependent.
2356 TInfo->getType()->isDependentType(),
2357 TInfo->getType()->isInstantiationDependentType(),
2358 TInfo->getType()->containsUnexpandedParameterPack()),
2359 OpLoc(op), RParenLoc(rp) {
2360 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
2361 UnaryExprOrTypeTraitExprBits.IsType = true;
2362 Argument.Ty = TInfo;
2365 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E,
2366 QualType resultType, SourceLocation op,
2369 /// Construct an empty sizeof/alignof expression.
2370 explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty)
2371 : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
2373 UnaryExprOrTypeTrait getKind() const {
2374 return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind);
2376 void setKind(UnaryExprOrTypeTrait K) { UnaryExprOrTypeTraitExprBits.Kind = K;}
2378 bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; }
2379 QualType getArgumentType() const {
2380 return getArgumentTypeInfo()->getType();
2382 TypeSourceInfo *getArgumentTypeInfo() const {
2383 assert(isArgumentType() && "calling getArgumentType() when arg is expr");
2386 Expr *getArgumentExpr() {
2387 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
2388 return static_cast<Expr*>(Argument.Ex);
2390 const Expr *getArgumentExpr() const {
2391 return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
2394 void setArgument(Expr *E) {
2396 UnaryExprOrTypeTraitExprBits.IsType = false;
2398 void setArgument(TypeSourceInfo *TInfo) {
2399 Argument.Ty = TInfo;
2400 UnaryExprOrTypeTraitExprBits.IsType = true;
2403 /// Gets the argument type, or the type of the argument expression, whichever
2405 QualType getTypeOfArgument() const {
2406 return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
2409 SourceLocation getOperatorLoc() const { return OpLoc; }
2410 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2412 SourceLocation getRParenLoc() const { return RParenLoc; }
2413 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2415 SourceLocation getBeginLoc() const LLVM_READONLY { return OpLoc; }
2416 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
2418 static bool classof(const Stmt *T) {
2419 return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
2423 child_range children();
2424 const_child_range children() const;
2427 //===----------------------------------------------------------------------===//
2428 // Postfix Operators.
2429 //===----------------------------------------------------------------------===//
2431 /// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
2432 class ArraySubscriptExpr : public Expr {
2433 enum { LHS, RHS, END_EXPR };
2434 Stmt *SubExprs[END_EXPR];
2436 bool lhsIsBase() const { return getRHS()->getType()->isIntegerType(); }
2439 ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
2440 ExprValueKind VK, ExprObjectKind OK,
2441 SourceLocation rbracketloc)
2442 : Expr(ArraySubscriptExprClass, t, VK, OK,
2443 lhs->isTypeDependent() || rhs->isTypeDependent(),
2444 lhs->isValueDependent() || rhs->isValueDependent(),
2445 (lhs->isInstantiationDependent() ||
2446 rhs->isInstantiationDependent()),
2447 (lhs->containsUnexpandedParameterPack() ||
2448 rhs->containsUnexpandedParameterPack())) {
2449 SubExprs[LHS] = lhs;
2450 SubExprs[RHS] = rhs;
2451 ArraySubscriptExprBits.RBracketLoc = rbracketloc;
2454 /// Create an empty array subscript expression.
2455 explicit ArraySubscriptExpr(EmptyShell Shell)
2456 : Expr(ArraySubscriptExprClass, Shell) { }
2458 /// An array access can be written A[4] or 4[A] (both are equivalent).
2459 /// - getBase() and getIdx() always present the normalized view: A[4].
2460 /// In this case getBase() returns "A" and getIdx() returns "4".
2461 /// - getLHS() and getRHS() present the syntactic view. e.g. for
2462 /// 4[A] getLHS() returns "4".
2463 /// Note: Because vector element access is also written A[4] we must
2464 /// predicate the format conversion in getBase and getIdx only on the
2465 /// the type of the RHS, as it is possible for the LHS to be a vector of
2467 Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
2468 const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2469 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2471 Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
2472 const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2473 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2475 Expr *getBase() { return lhsIsBase() ? getLHS() : getRHS(); }
2476 const Expr *getBase() const { return lhsIsBase() ? getLHS() : getRHS(); }
2478 Expr *getIdx() { return lhsIsBase() ? getRHS() : getLHS(); }
2479 const Expr *getIdx() const { return lhsIsBase() ? getRHS() : getLHS(); }
2481 SourceLocation getBeginLoc() const LLVM_READONLY {
2482 return getLHS()->getBeginLoc();
2484 SourceLocation getEndLoc() const { return getRBracketLoc(); }
2486 SourceLocation getRBracketLoc() const {
2487 return ArraySubscriptExprBits.RBracketLoc;
2489 void setRBracketLoc(SourceLocation L) {
2490 ArraySubscriptExprBits.RBracketLoc = L;
2493 SourceLocation getExprLoc() const LLVM_READONLY {
2494 return getBase()->getExprLoc();
2497 static bool classof(const Stmt *T) {
2498 return T->getStmtClass() == ArraySubscriptExprClass;
2502 child_range children() {
2503 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2505 const_child_range children() const {
2506 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2510 /// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
2511 /// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
2512 /// while its subclasses may represent alternative syntax that (semantically)
2513 /// results in a function call. For example, CXXOperatorCallExpr is
2514 /// a subclass for overloaded operator calls that use operator syntax, e.g.,
2515 /// "str1 + str2" to resolve to a function call.
2516 class CallExpr : public Expr {
2517 enum { FN = 0, PREARGS_START = 1 };
2519 /// The number of arguments in the call expression.
2522 /// The location of the right parenthese. This has a different meaning for
2523 /// the derived classes of CallExpr.
2524 SourceLocation RParenLoc;
2526 void updateDependenciesFromArg(Expr *Arg);
2528 // CallExpr store some data in trailing objects. However since CallExpr
2529 // is used a base of other expression classes we cannot use
2530 // llvm::TrailingObjects. Instead we manually perform the pointer arithmetic
2533 // The trailing objects are in order:
2535 // * A single "Stmt *" for the callee expression.
2537 // * An array of getNumPreArgs() "Stmt *" for the pre-argument expressions.
2539 // * An array of getNumArgs() "Stmt *" for the argument expressions.
2541 // Note that we store the offset in bytes from the this pointer to the start
2542 // of the trailing objects. It would be perfectly possible to compute it
2543 // based on the dynamic kind of the CallExpr. However 1.) we have plenty of
2544 // space in the bit-fields of Stmt. 2.) It was benchmarked to be faster to
2545 // compute this once and then load the offset from the bit-fields of Stmt,
2546 // instead of re-computing the offset each time the trailing objects are
2549 /// Return a pointer to the start of the trailing array of "Stmt *".
2550 Stmt **getTrailingStmts() {
2551 return reinterpret_cast<Stmt **>(reinterpret_cast<char *>(this) +
2552 CallExprBits.OffsetToTrailingObjects);
2554 Stmt *const *getTrailingStmts() const {
2555 return const_cast<CallExpr *>(this)->getTrailingStmts();
2558 /// Map a statement class to the appropriate offset in bytes from the
2559 /// this pointer to the trailing objects.
2560 static unsigned offsetToTrailingObjects(StmtClass SC);
2563 enum class ADLCallKind : bool { NotADL, UsesADL };
2564 static constexpr ADLCallKind NotADL = ADLCallKind::NotADL;
2565 static constexpr ADLCallKind UsesADL = ADLCallKind::UsesADL;
2568 /// Build a call expression, assuming that appropriate storage has been
2569 /// allocated for the trailing objects.
2570 CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs,
2571 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
2572 SourceLocation RParenLoc, unsigned MinNumArgs, ADLCallKind UsesADL);
2574 /// Build an empty call expression, for deserialization.
2575 CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
2578 /// Return the size in bytes needed for the trailing objects.
2579 /// Used by the derived classes to allocate the right amount of storage.
2580 static unsigned sizeOfTrailingObjects(unsigned NumPreArgs, unsigned NumArgs) {
2581 return (1 + NumPreArgs + NumArgs) * sizeof(Stmt *);
2584 Stmt *getPreArg(unsigned I) {
2585 assert(I < getNumPreArgs() && "Prearg access out of range!");
2586 return getTrailingStmts()[PREARGS_START + I];
2588 const Stmt *getPreArg(unsigned I) const {
2589 assert(I < getNumPreArgs() && "Prearg access out of range!");
2590 return getTrailingStmts()[PREARGS_START + I];
2592 void setPreArg(unsigned I, Stmt *PreArg) {
2593 assert(I < getNumPreArgs() && "Prearg access out of range!");
2594 getTrailingStmts()[PREARGS_START + I] = PreArg;
2597 unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
2600 /// Create a call expression. Fn is the callee expression, Args is the
2601 /// argument array, Ty is the type of the call expression (which is *not*
2602 /// the return type in general), VK is the value kind of the call expression
2603 /// (lvalue, rvalue, ...), and RParenLoc is the location of the right
2604 /// parenthese in the call expression. MinNumArgs specifies the minimum
2605 /// number of arguments. The actual number of arguments will be the greater
2606 /// of Args.size() and MinNumArgs. This is used in a few places to allocate
2607 /// enough storage for the default arguments. UsesADL specifies whether the
2608 /// callee was found through argument-dependent lookup.
2610 /// Note that you can use CreateTemporary if you need a temporary call
2611 /// expression on the stack.
2612 static CallExpr *Create(const ASTContext &Ctx, Expr *Fn,
2613 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
2614 SourceLocation RParenLoc, unsigned MinNumArgs = 0,
2615 ADLCallKind UsesADL = NotADL);
2617 /// Create a temporary call expression with no arguments in the memory
2618 /// pointed to by Mem. Mem must points to at least sizeof(CallExpr)
2619 /// + sizeof(Stmt *) bytes of storage, aligned to alignof(CallExpr):
2622 /// llvm::AlignedCharArray<alignof(CallExpr),
2623 /// sizeof(CallExpr) + sizeof(Stmt *)> Buffer;
2624 /// CallExpr *TheCall = CallExpr::CreateTemporary(Buffer.buffer, etc);
2626 static CallExpr *CreateTemporary(void *Mem, Expr *Fn, QualType Ty,
2627 ExprValueKind VK, SourceLocation RParenLoc,
2628 ADLCallKind UsesADL = NotADL);
2630 /// Create an empty call expression, for deserialization.
2631 static CallExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
2634 Expr *getCallee() { return cast<Expr>(getTrailingStmts()[FN]); }
2635 const Expr *getCallee() const { return cast<Expr>(getTrailingStmts()[FN]); }
2636 void setCallee(Expr *F) { getTrailingStmts()[FN] = F; }
2638 ADLCallKind getADLCallKind() const {
2639 return static_cast<ADLCallKind>(CallExprBits.UsesADL);
2641 void setADLCallKind(ADLCallKind V = UsesADL) {
2642 CallExprBits.UsesADL = static_cast<bool>(V);
2644 bool usesADL() const { return getADLCallKind() == UsesADL; }
2646 Decl *getCalleeDecl() { return getCallee()->getReferencedDeclOfCallee(); }
2647 const Decl *getCalleeDecl() const {
2648 return getCallee()->getReferencedDeclOfCallee();
2651 /// If the callee is a FunctionDecl, return it. Otherwise return null.
2652 FunctionDecl *getDirectCallee() {
2653 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
2655 const FunctionDecl *getDirectCallee() const {
2656 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
2659 /// getNumArgs - Return the number of actual arguments to this call.
2660 unsigned getNumArgs() const { return NumArgs; }
2662 /// Retrieve the call arguments.
2664 return reinterpret_cast<Expr **>(getTrailingStmts() + PREARGS_START +
2667 const Expr *const *getArgs() const {
2668 return reinterpret_cast<const Expr *const *>(
2669 getTrailingStmts() + PREARGS_START + getNumPreArgs());
2672 /// getArg - Return the specified argument.
2673 Expr *getArg(unsigned Arg) {
2674 assert(Arg < getNumArgs() && "Arg access out of range!");
2675 return getArgs()[Arg];
2677 const Expr *getArg(unsigned Arg) const {
2678 assert(Arg < getNumArgs() && "Arg access out of range!");
2679 return getArgs()[Arg];
2682 /// setArg - Set the specified argument.
2683 void setArg(unsigned Arg, Expr *ArgExpr) {
2684 assert(Arg < getNumArgs() && "Arg access out of range!");
2685 getArgs()[Arg] = ArgExpr;
2688 /// Reduce the number of arguments in this call expression. This is used for
2689 /// example during error recovery to drop extra arguments. There is no way
2690 /// to perform the opposite because: 1.) We don't track how much storage
2691 /// we have for the argument array 2.) This would potentially require growing
2692 /// the argument array, something we cannot support since the arguments are
2693 /// stored in a trailing array.
2694 void shrinkNumArgs(unsigned NewNumArgs) {
2695 assert((NewNumArgs <= getNumArgs()) &&
2696 "shrinkNumArgs cannot increase the number of arguments!");
2697 NumArgs = NewNumArgs;
2700 /// Bluntly set a new number of arguments without doing any checks whatsoever.
2701 /// Only used during construction of a CallExpr in a few places in Sema.
2702 /// FIXME: Find a way to remove it.
2703 void setNumArgsUnsafe(unsigned NewNumArgs) { NumArgs = NewNumArgs; }
2705 typedef ExprIterator arg_iterator;
2706 typedef ConstExprIterator const_arg_iterator;
2707 typedef llvm::iterator_range<arg_iterator> arg_range;
2708 typedef llvm::iterator_range<const_arg_iterator> const_arg_range;
2710 arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
2711 const_arg_range arguments() const {
2712 return const_arg_range(arg_begin(), arg_end());
2715 arg_iterator arg_begin() {
2716 return getTrailingStmts() + PREARGS_START + getNumPreArgs();
2718 arg_iterator arg_end() { return arg_begin() + getNumArgs(); }
2720 const_arg_iterator arg_begin() const {
2721 return getTrailingStmts() + PREARGS_START + getNumPreArgs();
2723 const_arg_iterator arg_end() const { return arg_begin() + getNumArgs(); }
2725 /// This method provides fast access to all the subexpressions of
2726 /// a CallExpr without going through the slower virtual child_iterator
2727 /// interface. This provides efficient reverse iteration of the
2728 /// subexpressions. This is currently used for CFG construction.
2729 ArrayRef<Stmt *> getRawSubExprs() {
2730 return llvm::makeArrayRef(getTrailingStmts(),
2731 PREARGS_START + getNumPreArgs() + getNumArgs());
2734 /// getNumCommas - Return the number of commas that must have been present in
2735 /// this function call.
2736 unsigned getNumCommas() const { return getNumArgs() ? getNumArgs() - 1 : 0; }
2738 /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID
2739 /// of the callee. If not, return 0.
2740 unsigned getBuiltinCallee() const;
2742 /// Returns \c true if this is a call to a builtin which does not
2743 /// evaluate side-effects within its arguments.
2744 bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const;
2746 /// getCallReturnType - Get the return type of the call expr. This is not
2747 /// always the type of the expr itself, if the return type is a reference
2749 QualType getCallReturnType(const ASTContext &Ctx) const;
2751 /// Returns the WarnUnusedResultAttr that is either declared on the called
2752 /// function, or its return type declaration.
2753 const Attr *getUnusedResultAttr(const ASTContext &Ctx) const;
2755 /// Returns true if this call expression should warn on unused results.
2756 bool hasUnusedResultAttr(const ASTContext &Ctx) const {
2757 return getUnusedResultAttr(Ctx) != nullptr;
2760 SourceLocation getRParenLoc() const { return RParenLoc; }
2761 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2763 SourceLocation getBeginLoc() const LLVM_READONLY;
2764 SourceLocation getEndLoc() const LLVM_READONLY;
2766 /// Return true if this is a call to __assume() or __builtin_assume() with
2767 /// a non-value-dependent constant parameter evaluating as false.
2768 bool isBuiltinAssumeFalse(const ASTContext &Ctx) const;
2770 bool isCallToStdMove() const {
2771 const FunctionDecl *FD = getDirectCallee();
2772 return getNumArgs() == 1 && FD && FD->isInStdNamespace() &&
2773 FD->getIdentifier() && FD->getIdentifier()->isStr("move");
2776 static bool classof(const Stmt *T) {
2777 return T->getStmtClass() >= firstCallExprConstant &&
2778 T->getStmtClass() <= lastCallExprConstant;
2782 child_range children() {
2783 return child_range(getTrailingStmts(), getTrailingStmts() + PREARGS_START +
2784 getNumPreArgs() + getNumArgs());
2787 const_child_range children() const {
2788 return const_child_range(getTrailingStmts(),
2789 getTrailingStmts() + PREARGS_START +
2790 getNumPreArgs() + getNumArgs());
2794 /// Extra data stored in some MemberExpr objects.
2795 struct MemberExprNameQualifier {
2796 /// The nested-name-specifier that qualifies the name, including
2797 /// source-location information.
2798 NestedNameSpecifierLoc QualifierLoc;
2800 /// The DeclAccessPair through which the MemberDecl was found due to
2801 /// name qualifiers.
2802 DeclAccessPair FoundDecl;
2805 /// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F.
2807 class MemberExpr final
2809 private llvm::TrailingObjects<MemberExpr, MemberExprNameQualifier,
2810 ASTTemplateKWAndArgsInfo,
2811 TemplateArgumentLoc> {
2812 friend class ASTReader;
2813 friend class ASTStmtReader;
2814 friend class ASTStmtWriter;
2815 friend TrailingObjects;
2817 /// Base - the expression for the base pointer or structure references. In
2818 /// X.F, this is "X".
2821 /// MemberDecl - This is the decl being referenced by the field/member name.
2822 /// In X.F, this is the decl referenced by F.
2823 ValueDecl *MemberDecl;
2825 /// MemberDNLoc - Provides source/type location info for the
2826 /// declaration name embedded in MemberDecl.
2827 DeclarationNameLoc MemberDNLoc;
2829 /// MemberLoc - This is the location of the member name.
2830 SourceLocation MemberLoc;
2832 size_t numTrailingObjects(OverloadToken<MemberExprNameQualifier>) const {
2833 return hasQualifierOrFoundDecl();
2836 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
2837 return hasTemplateKWAndArgsInfo();
2840 bool hasQualifierOrFoundDecl() const {
2841 return MemberExprBits.HasQualifierOrFoundDecl;
2844 bool hasTemplateKWAndArgsInfo() const {
2845 return MemberExprBits.HasTemplateKWAndArgsInfo;
2848 MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
2849 ValueDecl *MemberDecl, const DeclarationNameInfo &NameInfo,
2850 QualType T, ExprValueKind VK, ExprObjectKind OK,
2851 NonOdrUseReason NOUR);
2852 MemberExpr(EmptyShell Empty)
2853 : Expr(MemberExprClass, Empty), Base(), MemberDecl() {}
2856 static MemberExpr *Create(const ASTContext &C, Expr *Base, bool IsArrow,
2857 SourceLocation OperatorLoc,
2858 NestedNameSpecifierLoc QualifierLoc,
2859 SourceLocation TemplateKWLoc, ValueDecl *MemberDecl,
2860 DeclAccessPair FoundDecl,
2861 DeclarationNameInfo MemberNameInfo,
2862 const TemplateArgumentListInfo *TemplateArgs,
2863 QualType T, ExprValueKind VK, ExprObjectKind OK,
2864 NonOdrUseReason NOUR);
2866 /// Create an implicit MemberExpr, with no location, qualifier, template
2867 /// arguments, and so on. Suitable only for non-static member access.
2868 static MemberExpr *CreateImplicit(const ASTContext &C, Expr *Base,
2869 bool IsArrow, ValueDecl *MemberDecl,
2870 QualType T, ExprValueKind VK,
2871 ExprObjectKind OK) {
2872 return Create(C, Base, IsArrow, SourceLocation(), NestedNameSpecifierLoc(),
2873 SourceLocation(), MemberDecl,
2874 DeclAccessPair::make(MemberDecl, MemberDecl->getAccess()),
2875 DeclarationNameInfo(), nullptr, T, VK, OK, NOUR_None);
2878 static MemberExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier,
2880 bool HasTemplateKWAndArgsInfo,
2881 unsigned NumTemplateArgs);
2883 void setBase(Expr *E) { Base = E; }
2884 Expr *getBase() const { return cast<Expr>(Base); }
2886 /// Retrieve the member declaration to which this expression refers.
2888 /// The returned declaration will be a FieldDecl or (in C++) a VarDecl (for
2889 /// static data members), a CXXMethodDecl, or an EnumConstantDecl.
2890 ValueDecl *getMemberDecl() const { return MemberDecl; }
2891 void setMemberDecl(ValueDecl *D) { MemberDecl = D; }
2893 /// Retrieves the declaration found by lookup.
2894 DeclAccessPair getFoundDecl() const {
2895 if (!hasQualifierOrFoundDecl())
2896 return DeclAccessPair::make(getMemberDecl(),
2897 getMemberDecl()->getAccess());
2898 return getTrailingObjects<MemberExprNameQualifier>()->FoundDecl;
2901 /// Determines whether this member expression actually had
2902 /// a C++ nested-name-specifier prior to the name of the member, e.g.,
2904 bool hasQualifier() const { return getQualifier() != nullptr; }
2906 /// If the member name was qualified, retrieves the
2907 /// nested-name-specifier that precedes the member name, with source-location
2909 NestedNameSpecifierLoc getQualifierLoc() const {
2910 if (!hasQualifierOrFoundDecl())
2911 return NestedNameSpecifierLoc();
2912 return getTrailingObjects<MemberExprNameQualifier>()->QualifierLoc;
2915 /// If the member name was qualified, retrieves the
2916 /// nested-name-specifier that precedes the member name. Otherwise, returns
2918 NestedNameSpecifier *getQualifier() const {
2919 return getQualifierLoc().getNestedNameSpecifier();
2922 /// Retrieve the location of the template keyword preceding
2923 /// the member name, if any.
2924 SourceLocation getTemplateKeywordLoc() const {
2925 if (!hasTemplateKWAndArgsInfo())
2926 return SourceLocation();
2927 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
2930 /// Retrieve the location of the left angle bracket starting the
2931 /// explicit template argument list following the member name, if any.
2932 SourceLocation getLAngleLoc() const {
2933 if (!hasTemplateKWAndArgsInfo())
2934 return SourceLocation();
2935 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
2938 /// Retrieve the location of the right angle bracket ending the
2939 /// explicit template argument list following the member name, if any.
2940 SourceLocation getRAngleLoc() const {
2941 if (!hasTemplateKWAndArgsInfo())
2942 return SourceLocation();
2943 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
2946 /// Determines whether the member name was preceded by the template keyword.
2947 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
2949 /// Determines whether the member name was followed by an
2950 /// explicit template argument list.
2951 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
2953 /// Copies the template arguments (if present) into the given
2955 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
2956 if (hasExplicitTemplateArgs())
2957 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
2958 getTrailingObjects<TemplateArgumentLoc>(), List);
2961 /// Retrieve the template arguments provided as part of this
2963 const TemplateArgumentLoc *getTemplateArgs() const {
2964 if (!hasExplicitTemplateArgs())
2967 return getTrailingObjects<TemplateArgumentLoc>();
2970 /// Retrieve the number of template arguments provided as part of this
2972 unsigned getNumTemplateArgs() const {
2973 if (!hasExplicitTemplateArgs())
2976 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
2979 ArrayRef<TemplateArgumentLoc> template_arguments() const {
2980 return {getTemplateArgs(), getNumTemplateArgs()};
2983 /// Retrieve the member declaration name info.
2984 DeclarationNameInfo getMemberNameInfo() const {
2985 return DeclarationNameInfo(MemberDecl->getDeclName(),
2986 MemberLoc, MemberDNLoc);
2989 SourceLocation getOperatorLoc() const { return MemberExprBits.OperatorLoc; }
2991 bool isArrow() const { return MemberExprBits.IsArrow; }
2992 void setArrow(bool A) { MemberExprBits.IsArrow = A; }
2994 /// getMemberLoc - Return the location of the "member", in X->F, it is the
2995 /// location of 'F'.
2996 SourceLocation getMemberLoc() const { return MemberLoc; }
2997 void setMemberLoc(SourceLocation L) { MemberLoc = L; }
2999 SourceLocation getBeginLoc() const LLVM_READONLY;
3000 SourceLocation getEndLoc() const LLVM_READONLY;
3002 SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; }
3004 /// Determine whether the base of this explicit is implicit.
3005 bool isImplicitAccess() const {
3006 return getBase() && getBase()->isImplicitCXXThis();
3009 /// Returns true if this member expression refers to a method that
3010 /// was resolved from an overloaded set having size greater than 1.
3011 bool hadMultipleCandidates() const {
3012 return MemberExprBits.HadMultipleCandidates;
3014 /// Sets the flag telling whether this expression refers to
3015 /// a method that was resolved from an overloaded set having size
3017 void setHadMultipleCandidates(bool V = true) {
3018 MemberExprBits.HadMultipleCandidates = V;
3021 /// Returns true if virtual dispatch is performed.
3022 /// If the member access is fully qualified, (i.e. X::f()), virtual
3023 /// dispatching is not performed. In -fapple-kext mode qualified
3024 /// calls to virtual method will still go through the vtable.
3025 bool performsVirtualDispatch(const LangOptions &LO) const {
3026 return LO.AppleKext || !hasQualifier();
3029 /// Is this expression a non-odr-use reference, and if so, why?
3030 /// This is only meaningful if the named member is a static member.
3031 NonOdrUseReason isNonOdrUse() const {
3032 return static_cast<NonOdrUseReason>(MemberExprBits.NonOdrUseReason);
3035 static bool classof(const Stmt *T) {
3036 return T->getStmtClass() == MemberExprClass;
3040 child_range children() { return child_range(&Base, &Base+1); }
3041 const_child_range children() const {
3042 return const_child_range(&Base, &Base + 1);
3046 /// CompoundLiteralExpr - [C99 6.5.2.5]
3048 class CompoundLiteralExpr : public Expr {
3049 /// LParenLoc - If non-null, this is the location of the left paren in a
3050 /// compound literal like "(int){4}". This can be null if this is a
3051 /// synthesized compound expression.
3052 SourceLocation LParenLoc;
3054 /// The type as written. This can be an incomplete array type, in
3055 /// which case the actual expression type will be different.
3056 /// The int part of the pair stores whether this expr is file scope.
3057 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope;
3060 CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
3061 QualType T, ExprValueKind VK, Expr *init, bool fileScope)
3062 : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary,
3063 tinfo->getType()->isDependentType(),
3064 init->isValueDependent(),
3065 (init->isInstantiationDependent() ||
3066 tinfo->getType()->isInstantiationDependentType()),
3067 init->containsUnexpandedParameterPack()),
3068 LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {}
3070 /// Construct an empty compound literal.
3071 explicit CompoundLiteralExpr(EmptyShell Empty)
3072 : Expr(CompoundLiteralExprClass, Empty) { }
3074 const Expr *getInitializer() const { return cast<Expr>(Init); }
3075 Expr *getInitializer() { return cast<Expr>(Init); }
3076 void setInitializer(Expr *E) { Init = E; }
3078 bool isFileScope() const { return TInfoAndScope.getInt(); }
3079 void setFileScope(bool FS) { TInfoAndScope.setInt(FS); }
3081 SourceLocation getLParenLoc() const { return LParenLoc; }
3082 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3084 TypeSourceInfo *getTypeSourceInfo() const {
3085 return TInfoAndScope.getPointer();
3087 void setTypeSourceInfo(TypeSourceInfo *tinfo) {
3088 TInfoAndScope.setPointer(tinfo);
3091 SourceLocation getBeginLoc() const LLVM_READONLY {
3092 // FIXME: Init should never be null.
3094 return SourceLocation();
3095 if (LParenLoc.isInvalid())
3096 return Init->getBeginLoc();
3099 SourceLocation getEndLoc() const LLVM_READONLY {
3100 // FIXME: Init should never be null.
3102 return SourceLocation();
3103 return Init->getEndLoc();
3106 static bool classof(const Stmt *T) {
3107 return T->getStmtClass() == CompoundLiteralExprClass;
3111 child_range children() { return child_range(&Init, &Init+1); }
3112 const_child_range children() const {
3113 return const_child_range(&Init, &Init + 1);
3117 /// CastExpr - Base class for type casts, including both implicit
3118 /// casts (ImplicitCastExpr) and explicit casts that have some
3119 /// representation in the source code (ExplicitCastExpr's derived
3121 class CastExpr : public Expr {
3124 bool CastConsistency() const;
3126 const CXXBaseSpecifier * const *path_buffer() const {
3127 return const_cast<CastExpr*>(this)->path_buffer();
3129 CXXBaseSpecifier **path_buffer();
3132 CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, const CastKind kind,
3133 Expr *op, unsigned BasePathSize)
3134 : Expr(SC, ty, VK, OK_Ordinary,
3135 // Cast expressions are type-dependent if the type is
3136 // dependent (C++ [temp.dep.expr]p3).
3137 ty->isDependentType(),
3138 // Cast expressions are value-dependent if the type is
3139 // dependent or if the subexpression is value-dependent.
3140 ty->isDependentType() || (op && op->isValueDependent()),
3141 (ty->isInstantiationDependentType() ||
3142 (op && op->isInstantiationDependent())),
3143 // An implicit cast expression doesn't (lexically) contain an
3144 // unexpanded pack, even if its target type does.
3145 ((SC != ImplicitCastExprClass &&
3146 ty->containsUnexpandedParameterPack()) ||
3147 (op && op->containsUnexpandedParameterPack()))),
3149 CastExprBits.Kind = kind;
3150 CastExprBits.PartOfExplicitCast = false;
3151 CastExprBits.BasePathSize = BasePathSize;
3152 assert((CastExprBits.BasePathSize == BasePathSize) &&
3153 "BasePathSize overflow!");
3154 assert(CastConsistency());
3157 /// Construct an empty cast.
3158 CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize)
3160 CastExprBits.PartOfExplicitCast = false;
3161 CastExprBits.BasePathSize = BasePathSize;
3162 assert((CastExprBits.BasePathSize == BasePathSize) &&
3163 "BasePathSize overflow!");
3167 CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
3168 void setCastKind(CastKind K) { CastExprBits.Kind = K; }
3170 static const char *getCastKindName(CastKind CK);
3171 const char *getCastKindName() const { return getCastKindName(getCastKind()); }
3173 Expr *getSubExpr() { return cast<Expr>(Op); }
3174 const Expr *getSubExpr() const { return cast<Expr>(Op); }
3175 void setSubExpr(Expr *E) { Op = E; }
3177 /// Retrieve the cast subexpression as it was written in the source
3178 /// code, looking through any implicit casts or other intermediate nodes
3179 /// introduced by semantic analysis.
3180 Expr *getSubExprAsWritten();
3181 const Expr *getSubExprAsWritten() const {
3182 return const_cast<CastExpr *>(this)->getSubExprAsWritten();
3185 /// If this cast applies a user-defined conversion, retrieve the conversion
3186 /// function that it invokes.
3187 NamedDecl *getConversionFunction() const;
3189 typedef CXXBaseSpecifier **path_iterator;
3190 typedef const CXXBaseSpecifier *const *path_const_iterator;
3191 bool path_empty() const { return path_size() == 0; }
3192 unsigned path_size() const { return CastExprBits.BasePathSize; }
3193 path_iterator path_begin() { return path_buffer(); }
3194 path_iterator path_end() { return path_buffer() + path_size(); }
3195 path_const_iterator path_begin() const { return path_buffer(); }
3196 path_const_iterator path_end() const { return path_buffer() + path_size(); }
3198 llvm::iterator_range<path_iterator> path() {
3199 return llvm::make_range(path_begin(), path_end());
3201 llvm::iterator_range<path_const_iterator> path() const {
3202 return llvm::make_range(path_begin(), path_end());
3205 const FieldDecl *getTargetUnionField() const {
3206 assert(getCastKind() == CK_ToUnion);
3207 return getTargetFieldForToUnionCast(getType(), getSubExpr()->getType());
3210 static const FieldDecl *getTargetFieldForToUnionCast(QualType unionType,
3212 static const FieldDecl *getTargetFieldForToUnionCast(const RecordDecl *RD,
3215 static bool classof(const Stmt *T) {
3216 return T->getStmtClass() >= firstCastExprConstant &&
3217 T->getStmtClass() <= lastCastExprConstant;
3221 child_range children() { return child_range(&Op, &Op+1); }
3222 const_child_range children() const { return const_child_range(&Op, &Op + 1); }
3225 /// ImplicitCastExpr - Allows us to explicitly represent implicit type
3226 /// conversions, which have no direct representation in the original
3227 /// source code. For example: converting T[]->T*, void f()->void
3228 /// (*f)(), float->double, short->int, etc.
3230 /// In C, implicit casts always produce rvalues. However, in C++, an
3231 /// implicit cast whose result is being bound to a reference will be
3232 /// an lvalue or xvalue. For example:
3236 /// class Derived : public Base { };
3237 /// Derived &&ref();
3238 /// void f(Derived d) {
3239 /// Base& b = d; // initializer is an ImplicitCastExpr
3240 /// // to an lvalue of type Base
3241 /// Base&& r = ref(); // initializer is an ImplicitCastExpr
3242 /// // to an xvalue of type Base
3245 class ImplicitCastExpr final
3247 private llvm::TrailingObjects<ImplicitCastExpr, CXXBaseSpecifier *> {
3249 ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
3250 unsigned BasePathLength, ExprValueKind VK)
3251 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) { }
3253 /// Construct an empty implicit cast.
3254 explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize)
3255 : CastExpr(ImplicitCastExprClass, Shell, PathSize) { }
3258 enum OnStack_t { OnStack };
3259 ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
3261 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) {
3264 bool isPartOfExplicitCast() const { return CastExprBits.PartOfExplicitCast; }
3265 void setIsPartOfExplicitCast(bool PartOfExplicitCast) {
3266 CastExprBits.PartOfExplicitCast = PartOfExplicitCast;
3269 static ImplicitCastExpr *Create(const ASTContext &Context, QualType T,
3270 CastKind Kind, Expr *Operand,
3271 const CXXCastPath *BasePath,
3274 static ImplicitCastExpr *CreateEmpty(const ASTContext &Context,
3277 SourceLocation getBeginLoc() const LLVM_READONLY {
3278 return getSubExpr()->getBeginLoc();
3280 SourceLocation getEndLoc() const LLVM_READONLY {
3281 return getSubExpr()->getEndLoc();
3284 static bool classof(const Stmt *T) {
3285 return T->getStmtClass() == ImplicitCastExprClass;
3288 friend TrailingObjects;
3289 friend class CastExpr;
3292 /// ExplicitCastExpr - An explicit cast written in the source
3295 /// This class is effectively an abstract class, because it provides
3296 /// the basic representation of an explicitly-written cast without
3297 /// specifying which kind of cast (C cast, functional cast, static
3298 /// cast, etc.) was written; specific derived classes represent the
3299 /// particular style of cast and its location information.
3301 /// Unlike implicit casts, explicit cast nodes have two different
3302 /// types: the type that was written into the source code, and the
3303 /// actual type of the expression as determined by semantic
3304 /// analysis. These types may differ slightly. For example, in C++ one
3305 /// can cast to a reference type, which indicates that the resulting
3306 /// expression will be an lvalue or xvalue. The reference type, however,
3307 /// will not be used as the type of the expression.
3308 class ExplicitCastExpr : public CastExpr {
3309 /// TInfo - Source type info for the (written) type
3310 /// this expression is casting to.
3311 TypeSourceInfo *TInfo;
3314 ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK,
3315 CastKind kind, Expr *op, unsigned PathSize,
3316 TypeSourceInfo *writtenTy)
3317 : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {}
3319 /// Construct an empty explicit cast.
3320 ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
3321 : CastExpr(SC, Shell, PathSize) { }
3324 /// getTypeInfoAsWritten - Returns the type source info for the type
3325 /// that this expression is casting to.
3326 TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
3327 void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
3329 /// getTypeAsWritten - Returns the type that this expression is
3330 /// casting to, as written in the source code.
3331 QualType getTypeAsWritten() const { return TInfo->getType(); }
3333 static bool classof(const Stmt *T) {
3334 return T->getStmtClass() >= firstExplicitCastExprConstant &&
3335 T->getStmtClass() <= lastExplicitCastExprConstant;
3339 /// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
3340 /// cast in C++ (C++ [expr.cast]), which uses the syntax
3341 /// (Type)expr. For example: @c (int)f.
3342 class CStyleCastExpr final
3343 : public ExplicitCastExpr,
3344 private llvm::TrailingObjects<CStyleCastExpr, CXXBaseSpecifier *> {
3345 SourceLocation LPLoc; // the location of the left paren
3346 SourceLocation RPLoc; // the location of the right paren
3348 CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
3349 unsigned PathSize, TypeSourceInfo *writtenTy,
3350 SourceLocation l, SourceLocation r)
3351 : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
3352 writtenTy), LPLoc(l), RPLoc(r) {}
3354 /// Construct an empty C-style explicit cast.
3355 explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize)
3356 : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { }
3359 static CStyleCastExpr *Create(const ASTContext &Context, QualType T,
3360 ExprValueKind VK, CastKind K,
3361 Expr *Op, const CXXCastPath *BasePath,
3362 TypeSourceInfo *WrittenTy, SourceLocation L,
3365 static CStyleCastExpr *CreateEmpty(const ASTContext &Context,
3368 SourceLocation getLParenLoc() const { return LPLoc; }
3369 void setLParenLoc(SourceLocation L) { LPLoc = L; }
3371 SourceLocation getRParenLoc() const { return RPLoc; }
3372 void setRParenLoc(SourceLocation L) { RPLoc = L; }
3374 SourceLocation getBeginLoc() const LLVM_READONLY { return LPLoc; }
3375 SourceLocation getEndLoc() const LLVM_READONLY {
3376 return getSubExpr()->getEndLoc();
3379 static bool classof(const Stmt *T) {
3380 return T->getStmtClass() == CStyleCastExprClass;
3383 friend TrailingObjects;
3384 friend class CastExpr;
3387 /// A builtin binary operation expression such as "x + y" or "x <= y".
3389 /// This expression node kind describes a builtin binary operation,
3390 /// such as "x + y" for integer values "x" and "y". The operands will
3391 /// already have been converted to appropriate types (e.g., by
3392 /// performing promotions or conversions).
3394 /// In C++, where operators may be overloaded, a different kind of
3395 /// expression node (CXXOperatorCallExpr) is used to express the
3396 /// invocation of an overloaded operator with operator syntax. Within
3397 /// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
3398 /// used to store an expression "x + y" depends on the subexpressions
3399 /// for x and y. If neither x or y is type-dependent, and the "+"
3400 /// operator resolves to a built-in operation, BinaryOperator will be
3401 /// used to express the computation (x and y may still be
3402 /// value-dependent). If either x or y is type-dependent, or if the
3403 /// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
3404 /// be used to express the computation.
3405 class BinaryOperator : public Expr {
3406 enum { LHS, RHS, END_EXPR };
3407 Stmt *SubExprs[END_EXPR];
3410 typedef BinaryOperatorKind Opcode;
3412 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
3413 ExprValueKind VK, ExprObjectKind OK,
3414 SourceLocation opLoc, FPOptions FPFeatures)
3415 : Expr(BinaryOperatorClass, ResTy, VK, OK,
3416 lhs->isTypeDependent() || rhs->isTypeDependent(),
3417 lhs->isValueDependent() || rhs->isValueDependent(),
3418 (lhs->isInstantiationDependent() ||
3419 rhs->isInstantiationDependent()),
3420 (lhs->containsUnexpandedParameterPack() ||
3421 rhs->containsUnexpandedParameterPack())) {
3422 BinaryOperatorBits.Opc = opc;
3423 BinaryOperatorBits.FPFeatures = FPFeatures.getInt();
3424 BinaryOperatorBits.OpLoc = opLoc;
3425 SubExprs[LHS] = lhs;
3426 SubExprs[RHS] = rhs;
3427 assert(!isCompoundAssignmentOp() &&
3428 "Use CompoundAssignOperator for compound assignments");
3431 /// Construct an empty binary operator.
3432 explicit BinaryOperator(EmptyShell Empty) : Expr(BinaryOperatorClass, Empty) {
3433 BinaryOperatorBits.Opc = BO_Comma;
3436 SourceLocation getExprLoc() const { return getOperatorLoc(); }
3437 SourceLocation getOperatorLoc() const { return BinaryOperatorBits.OpLoc; }
3438 void setOperatorLoc(SourceLocation L) { BinaryOperatorBits.OpLoc = L; }
3440 Opcode getOpcode() const {
3441 return static_cast<Opcode>(BinaryOperatorBits.Opc);
3443 void setOpcode(Opcode Opc) { BinaryOperatorBits.Opc = Opc; }
3445 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3446 void setLHS(Expr *E) { SubExprs[LHS] = E; }
3447 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3448 void setRHS(Expr *E) { SubExprs[RHS] = E; }
3450 SourceLocation getBeginLoc() const LLVM_READONLY {
3451 return getLHS()->getBeginLoc();
3453 SourceLocation getEndLoc() const LLVM_READONLY {
3454 return getRHS()->getEndLoc();
3457 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
3458 /// corresponds to, e.g. "<<=".
3459 static StringRef getOpcodeStr(Opcode Op);
3461 StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
3463 /// Retrieve the binary opcode that corresponds to the given
3464 /// overloaded operator.
3465 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
3467 /// Retrieve the overloaded operator kind that corresponds to
3468 /// the given binary opcode.
3469 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
3471 /// predicates to categorize the respective opcodes.
3472 static bool isPtrMemOp(Opcode Opc) {
3473 return Opc == BO_PtrMemD || Opc == BO_PtrMemI;
3475 bool isPtrMemOp() const { return isPtrMemOp(getOpcode()); }
3477 static bool isMultiplicativeOp(Opcode Opc) {
3478 return Opc >= BO_Mul && Opc <= BO_Rem;
3480 bool isMultiplicativeOp() const { return isMultiplicativeOp(getOpcode()); }
3481 static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
3482 bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
3483 static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
3484 bool isShiftOp() const { return isShiftOp(getOpcode()); }
3486 static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
3487 bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
3489 static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
3490 bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
3492 static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
3493 bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
3495 static bool isComparisonOp(Opcode Opc) { return Opc >= BO_Cmp && Opc<=BO_NE; }
3496 bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
3498 static bool isCommaOp(Opcode Opc) { return Opc == BO_Comma; }
3499 bool isCommaOp() const { return isCommaOp(getOpcode()); }
3501 static Opcode negateComparisonOp(Opcode Opc) {
3504 llvm_unreachable("Not a comparison operator.");
3505 case BO_LT: return BO_GE;
3506 case BO_GT: return BO_LE;
3507 case BO_LE: return BO_GT;
3508 case BO_GE: return BO_LT;
3509 case BO_EQ: return BO_NE;
3510 case BO_NE: return BO_EQ;
3514 static Opcode reverseComparisonOp(Opcode Opc) {
3517 llvm_unreachable("Not a comparison operator.");
3518 case BO_LT: return BO_GT;
3519 case BO_GT: return BO_LT;
3520 case BO_LE: return BO_GE;
3521 case BO_GE: return BO_LE;
3528 static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
3529 bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
3531 static bool isAssignmentOp(Opcode Opc) {
3532 return Opc >= BO_Assign && Opc <= BO_OrAssign;
3534 bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); }
3536 static bool isCompoundAssignmentOp(Opcode Opc) {
3537 return Opc > BO_Assign && Opc <= BO_OrAssign;
3539 bool isCompoundAssignmentOp() const {
3540 return isCompoundAssignmentOp(getOpcode());
3542 static Opcode getOpForCompoundAssignment(Opcode Opc) {
3543 assert(isCompoundAssignmentOp(Opc));
3544 if (Opc >= BO_AndAssign)
3545 return Opcode(unsigned(Opc) - BO_AndAssign + BO_And);
3547 return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul);
3550 static bool isShiftAssignOp(Opcode Opc) {
3551 return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
3553 bool isShiftAssignOp() const {
3554 return isShiftAssignOp(getOpcode());
3557 // Return true if a binary operator using the specified opcode and operands
3558 // would match the 'p = (i8*)nullptr + n' idiom for casting a pointer-sized
3559 // integer to a pointer.
3560 static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc,
3561 Expr *LHS, Expr *RHS);
3563 static bool classof(const Stmt *S) {
3564 return S->getStmtClass() >= firstBinaryOperatorConstant &&
3565 S->getStmtClass() <= lastBinaryOperatorConstant;
3569 child_range children() {
3570 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3572 const_child_range children() const {
3573 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
3576 // Set the FP contractability status of this operator. Only meaningful for
3577 // operations on floating point types.
3578 void setFPFeatures(FPOptions F) {
3579 BinaryOperatorBits.FPFeatures = F.getInt();
3582 FPOptions getFPFeatures() const {
3583 return FPOptions(BinaryOperatorBits.FPFeatures);
3586 // Get the FP contractability status of this operator. Only meaningful for
3587 // operations on floating point types.
3588 bool isFPContractableWithinStatement() const {
3589 return getFPFeatures().allowFPContractWithinStatement();
3592 // Get the FENV_ACCESS status of this operator. Only meaningful for
3593 // operations on floating point types.
3594 bool isFEnvAccessOn() const { return getFPFeatures().allowFEnvAccess(); }
3597 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
3598 ExprValueKind VK, ExprObjectKind OK,
3599 SourceLocation opLoc, FPOptions FPFeatures, bool dead2)
3600 : Expr(CompoundAssignOperatorClass, ResTy, VK, OK,
3601 lhs->isTypeDependent() || rhs->isTypeDependent(),
3602 lhs->isValueDependent() || rhs->isValueDependent(),
3603 (lhs->isInstantiationDependent() ||
3604 rhs->isInstantiationDependent()),
3605 (lhs->containsUnexpandedParameterPack() ||
3606 rhs->containsUnexpandedParameterPack())) {
3607 BinaryOperatorBits.Opc = opc;
3608 BinaryOperatorBits.FPFeatures = FPFeatures.getInt();
3609 BinaryOperatorBits.OpLoc = opLoc;
3610 SubExprs[LHS] = lhs;
3611 SubExprs[RHS] = rhs;
3614 BinaryOperator(StmtClass SC, EmptyShell Empty) : Expr(SC, Empty) {
3615 BinaryOperatorBits.Opc = BO_MulAssign;
3619 /// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
3620 /// track of the type the operation is performed in. Due to the semantics of
3621 /// these operators, the operands are promoted, the arithmetic performed, an
3622 /// implicit conversion back to the result type done, then the assignment takes
3623 /// place. This captures the intermediate type which the computation is done
3625 class CompoundAssignOperator : public BinaryOperator {
3626 QualType ComputationLHSType;
3627 QualType ComputationResultType;
3629 CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResType,
3630 ExprValueKind VK, ExprObjectKind OK,
3631 QualType CompLHSType, QualType CompResultType,
3632 SourceLocation OpLoc, FPOptions FPFeatures)
3633 : BinaryOperator(lhs, rhs, opc, ResType, VK, OK, OpLoc, FPFeatures,
3635 ComputationLHSType(CompLHSType),
3636 ComputationResultType(CompResultType) {
3637 assert(isCompoundAssignmentOp() &&
3638 "Only should be used for compound assignments");
3641 /// Build an empty compound assignment operator expression.
3642 explicit CompoundAssignOperator(EmptyShell Empty)
3643 : BinaryOperator(CompoundAssignOperatorClass, Empty) { }
3645 // The two computation types are the type the LHS is converted
3646 // to for the computation and the type of the result; the two are
3647 // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
3648 QualType getComputationLHSType() const { return ComputationLHSType; }
3649 void setComputationLHSType(QualType T) { ComputationLHSType = T; }
3651 QualType getComputationResultType() const { return ComputationResultType; }
3652 void setComputationResultType(QualType T) { ComputationResultType = T; }
3654 static bool classof(const Stmt *S) {
3655 return S->getStmtClass() == CompoundAssignOperatorClass;
3659 /// AbstractConditionalOperator - An abstract base class for
3660 /// ConditionalOperator and BinaryConditionalOperator.
3661 class AbstractConditionalOperator : public Expr {
3662 SourceLocation QuestionLoc, ColonLoc;
3663 friend class ASTStmtReader;
3666 AbstractConditionalOperator(StmtClass SC, QualType T,
3667 ExprValueKind VK, ExprObjectKind OK,
3668 bool TD, bool VD, bool ID,
3669 bool ContainsUnexpandedParameterPack,
3670 SourceLocation qloc,
3671 SourceLocation cloc)
3672 : Expr(SC, T, VK, OK, TD, VD, ID, ContainsUnexpandedParameterPack),
3673 QuestionLoc(qloc), ColonLoc(cloc) {}
3675 AbstractConditionalOperator(StmtClass SC, EmptyShell Empty)
3676 : Expr(SC, Empty) { }
3679 // getCond - Return the expression representing the condition for
3681 Expr *getCond() const;
3683 // getTrueExpr - Return the subexpression representing the value of
3684 // the expression if the condition evaluates to true.
3685 Expr *getTrueExpr() const;
3687 // getFalseExpr - Return the subexpression representing the value of
3688 // the expression if the condition evaluates to false. This is
3689 // the same as getRHS.
3690 Expr *getFalseExpr() const;
3692 SourceLocation getQuestionLoc() const { return QuestionLoc; }
3693 SourceLocation getColonLoc() const { return ColonLoc; }
3695 static bool classof(const Stmt *T) {
3696 return T->getStmtClass() == ConditionalOperatorClass ||
3697 T->getStmtClass() == BinaryConditionalOperatorClass;
3701 /// ConditionalOperator - The ?: ternary operator. The GNU "missing
3702 /// middle" extension is a BinaryConditionalOperator.
3703 class ConditionalOperator : public AbstractConditionalOperator {
3704 enum { COND, LHS, RHS, END_EXPR };
3705 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3707 friend class ASTStmtReader;
3709 ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
3710 SourceLocation CLoc, Expr *rhs,
3711 QualType t, ExprValueKind VK, ExprObjectKind OK)
3712 : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK,
3713 // FIXME: the type of the conditional operator doesn't
3714 // depend on the type of the conditional, but the standard
3715 // seems to imply that it could. File a bug!
3716 (lhs->isTypeDependent() || rhs->isTypeDependent()),
3717 (cond->isValueDependent() || lhs->isValueDependent() ||
3718 rhs->isValueDependent()),
3719 (cond->isInstantiationDependent() ||
3720 lhs->isInstantiationDependent() ||
3721 rhs->isInstantiationDependent()),
3722 (cond->containsUnexpandedParameterPack() ||
3723 lhs->containsUnexpandedParameterPack() ||
3724 rhs->containsUnexpandedParameterPack()),
3726 SubExprs[COND] = cond;
3727 SubExprs[LHS] = lhs;
3728 SubExprs[RHS] = rhs;
3731 /// Build an empty conditional operator.
3732 explicit ConditionalOperator(EmptyShell Empty)
3733 : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
3735 // getCond - Return the expression representing the condition for
3737 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3739 // getTrueExpr - Return the subexpression representing the value of
3740 // the expression if the condition evaluates to true.
3741 Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); }
3743 // getFalseExpr - Return the subexpression representing the value of
3744 // the expression if the condition evaluates to false. This is
3745 // the same as getRHS.
3746 Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
3748 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3749 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3751 SourceLocation getBeginLoc() const LLVM_READONLY {
3752 return getCond()->getBeginLoc();
3754 SourceLocation getEndLoc() const LLVM_READONLY {
3755 return getRHS()->getEndLoc();
3758 static bool classof(const Stmt *T) {
3759 return T->getStmtClass() == ConditionalOperatorClass;
3763 child_range children() {
3764 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3766 const_child_range children() const {
3767 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
3771 /// BinaryConditionalOperator - The GNU extension to the conditional
3772 /// operator which allows the middle operand to be omitted.
3774 /// This is a different expression kind on the assumption that almost
3775 /// every client ends up needing to know that these are different.
3776 class BinaryConditionalOperator : public AbstractConditionalOperator {
3777 enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS };
3779 /// - the common condition/left-hand-side expression, which will be
3780 /// evaluated as the opaque value
3781 /// - the condition, expressed in terms of the opaque value
3782 /// - the left-hand-side, expressed in terms of the opaque value
3783 /// - the right-hand-side
3784 Stmt *SubExprs[NUM_SUBEXPRS];
3785 OpaqueValueExpr *OpaqueValue;
3787 friend class ASTStmtReader;
3789 BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue,
3790 Expr *cond, Expr *lhs, Expr *rhs,
3791 SourceLocation qloc, SourceLocation cloc,
3792 QualType t, ExprValueKind VK, ExprObjectKind OK)
3793 : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK,
3794 (common->isTypeDependent() || rhs->isTypeDependent()),
3795 (common->isValueDependent() || rhs->isValueDependent()),
3796 (common->isInstantiationDependent() ||
3797 rhs->isInstantiationDependent()),
3798 (common->containsUnexpandedParameterPack() ||
3799 rhs->containsUnexpandedParameterPack()),
3801 OpaqueValue(opaqueValue) {
3802 SubExprs[COMMON] = common;
3803 SubExprs[COND] = cond;
3804 SubExprs[LHS] = lhs;
3805 SubExprs[RHS] = rhs;
3806 assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value");
3809 /// Build an empty conditional operator.
3810 explicit BinaryConditionalOperator(EmptyShell Empty)
3811 : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { }
3813 /// getCommon - Return the common expression, written to the
3814 /// left of the condition. The opaque value will be bound to the
3815 /// result of this expression.
3816 Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); }
3818 /// getOpaqueValue - Return the opaque value placeholder.
3819 OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
3821 /// getCond - Return the condition expression; this is defined
3822 /// in terms of the opaque value.
3823 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3825 /// getTrueExpr - Return the subexpression which will be
3826 /// evaluated if the condition evaluates to true; this is defined
3827 /// in terms of the opaque value.
3828 Expr *getTrueExpr() const {
3829 return cast<Expr>(SubExprs[LHS]);
3832 /// getFalseExpr - Return the subexpression which will be
3833 /// evaluated if the condnition evaluates to false; this is
3834 /// defined in terms of the opaque value.
3835 Expr *getFalseExpr() const {
3836 return cast<Expr>(SubExprs[RHS]);
3839 SourceLocation getBeginLoc() const LLVM_READONLY {
3840 return getCommon()->getBeginLoc();
3842 SourceLocation getEndLoc() const LLVM_READONLY {
3843 return getFalseExpr()->getEndLoc();
3846 static bool classof(const Stmt *T) {
3847 return T->getStmtClass() == BinaryConditionalOperatorClass;
3851 child_range children() {
3852 return child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
3854 const_child_range children() const {
3855 return const_child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
3859 inline Expr *AbstractConditionalOperator::getCond() const {
3860 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3861 return co->getCond();
3862 return cast<BinaryConditionalOperator>(this)->getCond();
3865 inline Expr *AbstractConditionalOperator::getTrueExpr() const {
3866 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3867 return co->getTrueExpr();
3868 return cast<BinaryConditionalOperator>(this)->getTrueExpr();
3871 inline Expr *AbstractConditionalOperator::getFalseExpr() const {
3872 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3873 return co->getFalseExpr();
3874 return cast<BinaryConditionalOperator>(this)->getFalseExpr();
3877 /// AddrLabelExpr - The GNU address of label extension, representing &&label.
3878 class AddrLabelExpr : public Expr {
3879 SourceLocation AmpAmpLoc, LabelLoc;
3882 AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L,
3884 : Expr(AddrLabelExprClass, t, VK_RValue, OK_Ordinary, false, false, false,
3886 AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
3888 /// Build an empty address of a label expression.
3889 explicit AddrLabelExpr(EmptyShell Empty)
3890 : Expr(AddrLabelExprClass, Empty) { }
3892 SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
3893 void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
3894 SourceLocation getLabelLoc() const { return LabelLoc; }
3895 void setLabelLoc(SourceLocation L) { LabelLoc = L; }
3897 SourceLocation getBeginLoc() const LLVM_READONLY { return AmpAmpLoc; }
3898 SourceLocation getEndLoc() const LLVM_READONLY { return LabelLoc; }
3900 LabelDecl *getLabel() const { return Label; }
3901 void setLabel(LabelDecl *L) { Label = L; }
3903 static bool classof(const Stmt *T) {
3904 return T->getStmtClass() == AddrLabelExprClass;
3908 child_range children() {
3909 return child_range(child_iterator(), child_iterator());
3911 const_child_range children() const {
3912 return const_child_range(const_child_iterator(), const_child_iterator());
3916 /// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
3917 /// The StmtExpr contains a single CompoundStmt node, which it evaluates and
3918 /// takes the value of the last subexpression.
3920 /// A StmtExpr is always an r-value; values "returned" out of a
3921 /// StmtExpr will be copied.
3922 class StmtExpr : public Expr {
3924 SourceLocation LParenLoc, RParenLoc;
3926 // FIXME: Does type-dependence need to be computed differently?
3927 // FIXME: Do we need to compute instantiation instantiation-dependence for
3928 // statements? (ugh!)
3929 StmtExpr(CompoundStmt *substmt, QualType T,
3930 SourceLocation lp, SourceLocation rp) :
3931 Expr(StmtExprClass, T, VK_RValue, OK_Ordinary,
3932 T->isDependentType(), false, false, false),
3933 SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { }
3935 /// Build an empty statement expression.
3936 explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
3938 CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
3939 const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
3940 void setSubStmt(CompoundStmt *S) { SubStmt = S; }
3942 SourceLocation getBeginLoc() const LLVM_READONLY { return LParenLoc; }
3943 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
3945 SourceLocation getLParenLoc() const { return LParenLoc; }
3946 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3947 SourceLocation getRParenLoc() const { return RParenLoc; }
3948 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3950 static bool classof(const Stmt *T) {
3951 return T->getStmtClass() == StmtExprClass;
3955 child_range children() { return child_range(&SubStmt, &SubStmt+1); }
3956 const_child_range children() const {
3957 return const_child_range(&SubStmt, &SubStmt + 1);
3961 /// ShuffleVectorExpr - clang-specific builtin-in function
3962 /// __builtin_shufflevector.
3963 /// This AST node represents a operator that does a constant
3964 /// shuffle, similar to LLVM's shufflevector instruction. It takes
3965 /// two vectors and a variable number of constant indices,
3966 /// and returns the appropriately shuffled vector.
3967 class ShuffleVectorExpr : public Expr {
3968 SourceLocation BuiltinLoc, RParenLoc;
3970 // SubExprs - the list of values passed to the __builtin_shufflevector
3971 // function. The first two are vectors, and the rest are constant
3972 // indices. The number of values in this list is always
3973 // 2+the number of indices in the vector type.
3978 ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args, QualType Type,
3979 SourceLocation BLoc, SourceLocation RP);
3981 /// Build an empty vector-shuffle expression.
3982 explicit ShuffleVectorExpr(EmptyShell Empty)
3983 : Expr(ShuffleVectorExprClass, Empty), SubExprs(nullptr) { }
3985 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3986 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3988 SourceLocation getRParenLoc() const { return RParenLoc; }
3989 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3991 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
3992 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
3994 static bool classof(const Stmt *T) {
3995 return T->getStmtClass() == ShuffleVectorExprClass;
3998 /// getNumSubExprs - Return the size of the SubExprs array. This includes the
3999 /// constant expression, the actual arguments passed in, and the function
4001 unsigned getNumSubExprs() const { return NumExprs; }
4003 /// Retrieve the array of expressions.
4004 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
4006 /// getExpr - Return the Expr at the specified index.
4007 Expr *getExpr(unsigned Index) {
4008 assert((Index < NumExprs) && "Arg access out of range!");
4009 return cast<Expr>(SubExprs[Index]);
4011 const Expr *getExpr(unsigned Index) const {
4012 assert((Index < NumExprs) && "Arg access out of range!");
4013 return cast<Expr>(SubExprs[Index]);
4016 void setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs);
4018 llvm::APSInt getShuffleMaskIdx(const ASTContext &Ctx, unsigned N) const {
4019 assert((N < NumExprs - 2) && "Shuffle idx out of range!");
4020 return getExpr(N+2)->EvaluateKnownConstInt(Ctx);
4024 child_range children() {
4025 return child_range(&SubExprs[0], &SubExprs[0]+NumExprs);
4027 const_child_range children() const {
4028 return const_child_range(&SubExprs[0], &SubExprs[0] + NumExprs);
4032 /// ConvertVectorExpr - Clang builtin function __builtin_convertvector
4033 /// This AST node provides support for converting a vector type to another
4034 /// vector type of the same arity.
4035 class ConvertVectorExpr : public Expr {
4038 TypeSourceInfo *TInfo;
4039 SourceLocation BuiltinLoc, RParenLoc;
4041 friend class ASTReader;
4042 friend class ASTStmtReader;
4043 explicit ConvertVectorExpr(EmptyShell Empty) : Expr(ConvertVectorExprClass, Empty) {}
4046 ConvertVectorExpr(Expr* SrcExpr, TypeSourceInfo *TI, QualType DstType,
4047 ExprValueKind VK, ExprObjectKind OK,
4048 SourceLocation BuiltinLoc, SourceLocation RParenLoc)
4049 : Expr(ConvertVectorExprClass, DstType, VK, OK,
4050 DstType->isDependentType(),
4051 DstType->isDependentType() || SrcExpr->isValueDependent(),
4052 (DstType->isInstantiationDependentType() ||
4053 SrcExpr->isInstantiationDependent()),
4054 (DstType->containsUnexpandedParameterPack() ||
4055 SrcExpr->containsUnexpandedParameterPack())),
4056 SrcExpr(SrcExpr), TInfo(TI), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
4058 /// getSrcExpr - Return the Expr to be converted.
4059 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
4061 /// getTypeSourceInfo - Return the destination type.
4062 TypeSourceInfo *getTypeSourceInfo() const {
4065 void setTypeSourceInfo(TypeSourceInfo *ti) {
4069 /// getBuiltinLoc - Return the location of the __builtin_convertvector token.
4070 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4072 /// getRParenLoc - Return the location of final right parenthesis.
4073 SourceLocation getRParenLoc() const { return RParenLoc; }
4075 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
4076 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4078 static bool classof(const Stmt *T) {
4079 return T->getStmtClass() == ConvertVectorExprClass;
4083 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
4084 const_child_range children() const {
4085 return const_child_range(&SrcExpr, &SrcExpr + 1);
4089 /// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
4090 /// This AST node is similar to the conditional operator (?:) in C, with
4091 /// the following exceptions:
4092 /// - the test expression must be a integer constant expression.
4093 /// - the expression returned acts like the chosen subexpression in every
4094 /// visible way: the type is the same as that of the chosen subexpression,
4095 /// and all predicates (whether it's an l-value, whether it's an integer
4096 /// constant expression, etc.) return the same result as for the chosen
4098 class ChooseExpr : public Expr {
4099 enum { COND, LHS, RHS, END_EXPR };
4100 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
4101 SourceLocation BuiltinLoc, RParenLoc;
4104 ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs,
4105 QualType t, ExprValueKind VK, ExprObjectKind OK,
4106 SourceLocation RP, bool condIsTrue,
4107 bool TypeDependent, bool ValueDependent)
4108 : Expr(ChooseExprClass, t, VK, OK, TypeDependent, ValueDependent,
4109 (cond->isInstantiationDependent() ||
4110 lhs->isInstantiationDependent() ||
4111 rhs->isInstantiationDependent()),
4112 (cond->containsUnexpandedParameterPack() ||
4113 lhs->containsUnexpandedParameterPack() ||
4114 rhs->containsUnexpandedParameterPack())),
4115 BuiltinLoc(BLoc), RParenLoc(RP), CondIsTrue(condIsTrue) {
4116 SubExprs[COND] = cond;
4117 SubExprs[LHS] = lhs;
4118 SubExprs[RHS] = rhs;
4121 /// Build an empty __builtin_choose_expr.
4122 explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
4124 /// isConditionTrue - Return whether the condition is true (i.e. not
4126 bool isConditionTrue() const {
4127 assert(!isConditionDependent() &&
4128 "Dependent condition isn't true or false");
4131 void setIsConditionTrue(bool isTrue) { CondIsTrue = isTrue; }
4133 bool isConditionDependent() const {
4134 return getCond()->isTypeDependent() || getCond()->isValueDependent();
4137 /// getChosenSubExpr - Return the subexpression chosen according to the
4139 Expr *getChosenSubExpr() const {
4140 return isConditionTrue() ? getLHS() : getRHS();
4143 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
4144 void setCond(Expr *E) { SubExprs[COND] = E; }
4145 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
4146 void setLHS(Expr *E) { SubExprs[LHS] = E; }
4147 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
4148 void setRHS(Expr *E) { SubExprs[RHS] = E; }
4150 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4151 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
4153 SourceLocation getRParenLoc() const { return RParenLoc; }
4154 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4156 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
4157 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4159 static bool classof(const Stmt *T) {
4160 return T->getStmtClass() == ChooseExprClass;
4164 child_range children() {
4165 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
4167 const_child_range children() const {
4168 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
4172 /// GNUNullExpr - Implements the GNU __null extension, which is a name
4173 /// for a null pointer constant that has integral type (e.g., int or
4174 /// long) and is the same size and alignment as a pointer. The __null
4175 /// extension is typically only used by system headers, which define
4176 /// NULL as __null in C++ rather than using 0 (which is an integer
4177 /// that may not match the size of a pointer).
4178 class GNUNullExpr : public Expr {
4179 /// TokenLoc - The location of the __null keyword.
4180 SourceLocation TokenLoc;
4183 GNUNullExpr(QualType Ty, SourceLocation Loc)
4184 : Expr(GNUNullExprClass, Ty, VK_RValue, OK_Ordinary, false, false, false,
4188 /// Build an empty GNU __null expression.
4189 explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
4191 /// getTokenLocation - The location of the __null token.
4192 SourceLocation getTokenLocation() const { return TokenLoc; }
4193 void setTokenLocation(SourceLocation L) { TokenLoc = L; }
4195 SourceLocation getBeginLoc() const LLVM_READONLY { return TokenLoc; }
4196 SourceLocation getEndLoc() const LLVM_READONLY { return TokenLoc; }
4198 static bool classof(const Stmt *T) {
4199 return T->getStmtClass() == GNUNullExprClass;
4203 child_range children() {
4204 return child_range(child_iterator(), child_iterator());
4206 const_child_range children() const {
4207 return const_child_range(const_child_iterator(), const_child_iterator());
4211 /// Represents a call to the builtin function \c __builtin_va_arg.
4212 class VAArgExpr : public Expr {
4214 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfo;
4215 SourceLocation BuiltinLoc, RParenLoc;
4217 VAArgExpr(SourceLocation BLoc, Expr *e, TypeSourceInfo *TInfo,
4218 SourceLocation RPLoc, QualType t, bool IsMS)
4219 : Expr(VAArgExprClass, t, VK_RValue, OK_Ordinary, t->isDependentType(),
4220 false, (TInfo->getType()->isInstantiationDependentType() ||
4221 e->isInstantiationDependent()),
4222 (TInfo->getType()->containsUnexpandedParameterPack() ||
4223 e->containsUnexpandedParameterPack())),
4224 Val(e), TInfo(TInfo, IsMS), BuiltinLoc(BLoc), RParenLoc(RPLoc) {}
4226 /// Create an empty __builtin_va_arg expression.
4227 explicit VAArgExpr(EmptyShell Empty)
4228 : Expr(VAArgExprClass, Empty), Val(nullptr), TInfo(nullptr, false) {}
4230 const Expr *getSubExpr() const { return cast<Expr>(Val); }
4231 Expr *getSubExpr() { return cast<Expr>(Val); }
4232 void setSubExpr(Expr *E) { Val = E; }
4234 /// Returns whether this is really a Win64 ABI va_arg expression.
4235 bool isMicrosoftABI() const { return TInfo.getInt(); }
4236 void setIsMicrosoftABI(bool IsMS) { TInfo.setInt(IsMS); }
4238 TypeSourceInfo *getWrittenTypeInfo() const { return TInfo.getPointer(); }
4239 void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo.setPointer(TI); }
4241 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4242 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
4244 SourceLocation getRParenLoc() const { return RParenLoc; }
4245 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4247 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
4248 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4250 static bool classof(const Stmt *T) {
4251 return T->getStmtClass() == VAArgExprClass;
4255 child_range children() { return child_range(&Val, &Val+1); }
4256 const_child_range children() const {
4257 return const_child_range(&Val, &Val + 1);
4261 /// Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(),
4262 /// __builtin_FUNCTION(), or __builtin_FILE().
4263 class SourceLocExpr final : public Expr {
4264 SourceLocation BuiltinLoc, RParenLoc;
4265 DeclContext *ParentContext;
4268 enum IdentKind { Function, File, Line, Column };
4270 SourceLocExpr(const ASTContext &Ctx, IdentKind Type, SourceLocation BLoc,
4271 SourceLocation RParenLoc, DeclContext *Context);
4273 /// Build an empty call expression.
4274 explicit SourceLocExpr(EmptyShell Empty) : Expr(SourceLocExprClass, Empty) {}
4276 /// Return the result of evaluating this SourceLocExpr in the specified
4277 /// (and possibly null) default argument or initialization context.
4278 APValue EvaluateInContext(const ASTContext &Ctx,
4279 const Expr *DefaultExpr) const;
4281 /// Return a string representing the name of the specific builtin function.
4282 StringRef getBuiltinStr() const;
4284 IdentKind getIdentKind() const {
4285 return static_cast<IdentKind>(SourceLocExprBits.Kind);
4288 bool isStringType() const {
4289 switch (getIdentKind()) {
4297 llvm_unreachable("unknown source location expression kind");
4299 bool isIntType() const LLVM_READONLY { return !isStringType(); }
4301 /// If the SourceLocExpr has been resolved return the subexpression
4302 /// representing the resolved value. Otherwise return null.
4303 const DeclContext *getParentContext() const { return ParentContext; }
4304 DeclContext *getParentContext() { return ParentContext; }
4306 SourceLocation getLocation() const { return BuiltinLoc; }
4307 SourceLocation getBeginLoc() const { return BuiltinLoc; }
4308 SourceLocation getEndLoc() const { return RParenLoc; }
4310 child_range children() {
4311 return child_range(child_iterator(), child_iterator());
4314 const_child_range children() const {
4315 return const_child_range(child_iterator(), child_iterator());
4318 static bool classof(const Stmt *T) {
4319 return T->getStmtClass() == SourceLocExprClass;
4323 friend class ASTStmtReader;
4326 /// Describes an C or C++ initializer list.
4328 /// InitListExpr describes an initializer list, which can be used to
4329 /// initialize objects of different types, including
4330 /// struct/class/union types, arrays, and vectors. For example:
4333 /// struct foo x = { 1, { 2, 3 } };
4336 /// Prior to semantic analysis, an initializer list will represent the
4337 /// initializer list as written by the user, but will have the
4338 /// placeholder type "void". This initializer list is called the
4339 /// syntactic form of the initializer, and may contain C99 designated
4340 /// initializers (represented as DesignatedInitExprs), initializations
4341 /// of subobject members without explicit braces, and so on. Clients
4342 /// interested in the original syntax of the initializer list should
4343 /// use the syntactic form of the initializer list.
4345 /// After semantic analysis, the initializer list will represent the
4346 /// semantic form of the initializer, where the initializations of all
4347 /// subobjects are made explicit with nested InitListExpr nodes and
4348 /// C99 designators have been eliminated by placing the designated
4349 /// initializations into the subobject they initialize. Additionally,
4350 /// any "holes" in the initialization, where no initializer has been
4351 /// specified for a particular subobject, will be replaced with
4352 /// implicitly-generated ImplicitValueInitExpr expressions that
4353 /// value-initialize the subobjects. Note, however, that the
4354 /// initializer lists may still have fewer initializers than there are
4355 /// elements to initialize within the object.
4357 /// After semantic analysis has completed, given an initializer list,
4358 /// method isSemanticForm() returns true if and only if this is the
4359 /// semantic form of the initializer list (note: the same AST node
4360 /// may at the same time be the syntactic form).
4361 /// Given the semantic form of the initializer list, one can retrieve
4362 /// the syntactic form of that initializer list (when different)
4363 /// using method getSyntacticForm(); the method returns null if applied
4364 /// to a initializer list which is already in syntactic form.
4365 /// Similarly, given the syntactic form (i.e., an initializer list such
4366 /// that isSemanticForm() returns false), one can retrieve the semantic
4367 /// form using method getSemanticForm().
4368 /// Since many initializer lists have the same syntactic and semantic forms,
4369 /// getSyntacticForm() may return NULL, indicating that the current
4370 /// semantic initializer list also serves as its syntactic form.
4371 class InitListExpr : public Expr {
4372 // FIXME: Eliminate this vector in favor of ASTContext allocation
4373 typedef ASTVector<Stmt *> InitExprsTy;
4374 InitExprsTy InitExprs;
4375 SourceLocation LBraceLoc, RBraceLoc;
4377 /// The alternative form of the initializer list (if it exists).
4378 /// The int part of the pair stores whether this initializer list is
4379 /// in semantic form. If not null, the pointer points to:
4380 /// - the syntactic form, if this is in semantic form;
4381 /// - the semantic form, if this is in syntactic form.
4382 llvm::PointerIntPair<InitListExpr *, 1, bool> AltForm;
4385 /// If this initializer list initializes an array with more elements than
4386 /// there are initializers in the list, specifies an expression to be used
4387 /// for value initialization of the rest of the elements.
4389 /// If this initializer list initializes a union, specifies which
4390 /// field within the union will be initialized.
4391 llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit;
4394 InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
4395 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc);
4397 /// Build an empty initializer list.
4398 explicit InitListExpr(EmptyShell Empty)
4399 : Expr(InitListExprClass, Empty), AltForm(nullptr, true) { }
4401 unsigned getNumInits() const { return InitExprs.size(); }
4403 /// Retrieve the set of initializers.
4404 Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); }
4406 /// Retrieve the set of initializers.
4407 Expr * const *getInits() const {
4408 return reinterpret_cast<Expr * const *>(InitExprs.data());
4411 ArrayRef<Expr *> inits() {
4412 return llvm::makeArrayRef(getInits(), getNumInits());
4415 ArrayRef<Expr *> inits() const {
4416 return llvm::makeArrayRef(getInits(), getNumInits());
4419 const Expr *getInit(unsigned Init) const {
4420 assert(Init < getNumInits() && "Initializer access out of range!");
4421 return cast_or_null<Expr>(InitExprs[Init]);
4424 Expr *getInit(unsigned Init) {
4425 assert(Init < getNumInits() && "Initializer access out of range!");
4426 return cast_or_null<Expr>(InitExprs[Init]);
4429 void setInit(unsigned Init, Expr *expr) {
4430 assert(Init < getNumInits() && "Initializer access out of range!");
4431 InitExprs[Init] = expr;
4434 ExprBits.TypeDependent |= expr->isTypeDependent();
4435 ExprBits.ValueDependent |= expr->isValueDependent();
4436 ExprBits.InstantiationDependent |= expr->isInstantiationDependent();
4437 ExprBits.ContainsUnexpandedParameterPack |=
4438 expr->containsUnexpandedParameterPack();
4442 /// Reserve space for some number of initializers.
4443 void reserveInits(const ASTContext &C, unsigned NumInits);
4445 /// Specify the number of initializers
4447 /// If there are more than @p NumInits initializers, the remaining
4448 /// initializers will be destroyed. If there are fewer than @p
4449 /// NumInits initializers, NULL expressions will be added for the
4450 /// unknown initializers.
4451 void resizeInits(const ASTContext &Context, unsigned NumInits);
4453 /// Updates the initializer at index @p Init with the new
4454 /// expression @p expr, and returns the old expression at that
4457 /// When @p Init is out of range for this initializer list, the
4458 /// initializer list will be extended with NULL expressions to
4459 /// accommodate the new entry.
4460 Expr *updateInit(const ASTContext &C, unsigned Init, Expr *expr);
4462 /// If this initializer list initializes an array with more elements
4463 /// than there are initializers in the list, specifies an expression to be
4464 /// used for value initialization of the rest of the elements.
4465 Expr *getArrayFiller() {
4466 return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>();
4468 const Expr *getArrayFiller() const {
4469 return const_cast<InitListExpr *>(this)->getArrayFiller();
4471 void setArrayFiller(Expr *filler);
4473 /// Return true if this is an array initializer and its array "filler"
4475 bool hasArrayFiller() const { return getArrayFiller(); }
4477 /// If this initializes a union, specifies which field in the
4478 /// union to initialize.
4480 /// Typically, this field is the first named field within the
4481 /// union. However, a designated initializer can specify the
4482 /// initialization of a different field within the union.
4483 FieldDecl *getInitializedFieldInUnion() {
4484 return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>();
4486 const FieldDecl *getInitializedFieldInUnion() const {
4487 return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion();
4489 void setInitializedFieldInUnion(FieldDecl *FD) {
4490 assert((FD == nullptr
4491 || getInitializedFieldInUnion() == nullptr
4492 || getInitializedFieldInUnion() == FD)
4493 && "Only one field of a union may be initialized at a time!");
4494 ArrayFillerOrUnionFieldInit = FD;
4497 // Explicit InitListExpr's originate from source code (and have valid source
4498 // locations). Implicit InitListExpr's are created by the semantic analyzer.
4499 bool isExplicit() const {
4500 return LBraceLoc.isValid() && RBraceLoc.isValid();
4503 // Is this an initializer for an array of characters, initialized by a string
4504 // literal or an @encode?
4505 bool isStringLiteralInit() const;
4507 /// Is this a transparent initializer list (that is, an InitListExpr that is
4508 /// purely syntactic, and whose semantics are that of the sole contained
4510 bool isTransparent() const;
4512 /// Is this the zero initializer {0} in a language which considers it
4514 bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const;
4516 SourceLocation getLBraceLoc() const { return LBraceLoc; }
4517 void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
4518 SourceLocation getRBraceLoc() const { return RBraceLoc; }
4519 void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
4521 bool isSemanticForm() const { return AltForm.getInt(); }
4522 InitListExpr *getSemanticForm() const {
4523 return isSemanticForm() ? nullptr : AltForm.getPointer();
4525 bool isSyntacticForm() const {
4526 return !AltForm.getInt() || !AltForm.getPointer();
4528 InitListExpr *getSyntacticForm() const {
4529 return isSemanticForm() ? AltForm.getPointer() : nullptr;
4532 void setSyntacticForm(InitListExpr *Init) {
4533 AltForm.setPointer(Init);
4534 AltForm.setInt(true);
4535 Init->AltForm.setPointer(this);
4536 Init->AltForm.setInt(false);
4539 bool hadArrayRangeDesignator() const {
4540 return InitListExprBits.HadArrayRangeDesignator != 0;
4542 void sawArrayRangeDesignator(bool ARD = true) {
4543 InitListExprBits.HadArrayRangeDesignator = ARD;
4546 SourceLocation getBeginLoc() const LLVM_READONLY;
4547 SourceLocation getEndLoc() const LLVM_READONLY;
4549 static bool classof(const Stmt *T) {
4550 return T->getStmtClass() == InitListExprClass;
4554 child_range children() {
4555 const_child_range CCR = const_cast<const InitListExpr *>(this)->children();
4556 return child_range(cast_away_const(CCR.begin()),
4557 cast_away_const(CCR.end()));
4560 const_child_range children() const {
4561 // FIXME: This does not include the array filler expression.
4562 if (InitExprs.empty())
4563 return const_child_range(const_child_iterator(), const_child_iterator());
4564 return const_child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size());
4567 typedef InitExprsTy::iterator iterator;
4568 typedef InitExprsTy::const_iterator const_iterator;
4569 typedef InitExprsTy::reverse_iterator reverse_iterator;
4570 typedef InitExprsTy::const_reverse_iterator const_reverse_iterator;
4572 iterator begin() { return InitExprs.begin(); }
4573 const_iterator begin() const { return InitExprs.begin(); }
4574 iterator end() { return InitExprs.end(); }
4575 const_iterator end() const { return InitExprs.end(); }
4576 reverse_iterator rbegin() { return InitExprs.rbegin(); }
4577 const_reverse_iterator rbegin() const { return InitExprs.rbegin(); }
4578 reverse_iterator rend() { return InitExprs.rend(); }
4579 const_reverse_iterator rend() const { return InitExprs.rend(); }
4581 friend class ASTStmtReader;
4582 friend class ASTStmtWriter;
4585 /// Represents a C99 designated initializer expression.
4587 /// A designated initializer expression (C99 6.7.8) contains one or
4588 /// more designators (which can be field designators, array
4589 /// designators, or GNU array-range designators) followed by an
4590 /// expression that initializes the field or element(s) that the
4591 /// designators refer to. For example, given:
4598 /// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
4601 /// The InitListExpr contains three DesignatedInitExprs, the first of
4602 /// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
4603 /// designators, one array designator for @c [2] followed by one field
4604 /// designator for @c .y. The initialization expression will be 1.0.
4605 class DesignatedInitExpr final
4607 private llvm::TrailingObjects<DesignatedInitExpr, Stmt *> {
4609 /// Forward declaration of the Designator class.
4613 /// The location of the '=' or ':' prior to the actual initializer
4615 SourceLocation EqualOrColonLoc;
4617 /// Whether this designated initializer used the GNU deprecated
4618 /// syntax rather than the C99 '=' syntax.
4619 unsigned GNUSyntax : 1;
4621 /// The number of designators in this initializer expression.
4622 unsigned NumDesignators : 15;
4624 /// The number of subexpressions of this initializer expression,
4625 /// which contains both the initializer and any additional
4626 /// expressions used by array and array-range designators.
4627 unsigned NumSubExprs : 16;
4629 /// The designators in this designated initialization
4631 Designator *Designators;
4633 DesignatedInitExpr(const ASTContext &C, QualType Ty,
4634 llvm::ArrayRef<Designator> Designators,
4635 SourceLocation EqualOrColonLoc, bool GNUSyntax,
4636 ArrayRef<Expr *> IndexExprs, Expr *Init);
4638 explicit DesignatedInitExpr(unsigned NumSubExprs)
4639 : Expr(DesignatedInitExprClass, EmptyShell()),
4640 NumDesignators(0), NumSubExprs(NumSubExprs), Designators(nullptr) { }
4643 /// A field designator, e.g., ".x".
4644 struct FieldDesignator {
4645 /// Refers to the field that is being initialized. The low bit
4646 /// of this field determines whether this is actually a pointer
4647 /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
4648 /// initially constructed, a field designator will store an
4649 /// IdentifierInfo*. After semantic analysis has resolved that
4650 /// name, the field designator will instead store a FieldDecl*.
4651 uintptr_t NameOrField;
4653 /// The location of the '.' in the designated initializer.
4656 /// The location of the field name in the designated initializer.
4660 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
4661 struct ArrayOrRangeDesignator {
4662 /// Location of the first index expression within the designated
4663 /// initializer expression's list of subexpressions.
4665 /// The location of the '[' starting the array range designator.
4666 unsigned LBracketLoc;
4667 /// The location of the ellipsis separating the start and end
4668 /// indices. Only valid for GNU array-range designators.
4669 unsigned EllipsisLoc;
4670 /// The location of the ']' terminating the array range designator.
4671 unsigned RBracketLoc;
4674 /// Represents a single C99 designator.
4676 /// @todo This class is infuriatingly similar to clang::Designator,
4677 /// but minor differences (storing indices vs. storing pointers)
4678 /// keep us from reusing it. Try harder, later, to rectify these
4681 /// The kind of designator this describes.
4685 ArrayRangeDesignator
4689 /// A field designator, e.g., ".x".
4690 struct FieldDesignator Field;
4691 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
4692 struct ArrayOrRangeDesignator ArrayOrRange;
4694 friend class DesignatedInitExpr;
4699 /// Initializes a field designator.
4700 Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
4701 SourceLocation FieldLoc)
4702 : Kind(FieldDesignator) {
4703 Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
4704 Field.DotLoc = DotLoc.getRawEncoding();
4705 Field.FieldLoc = FieldLoc.getRawEncoding();
4708 /// Initializes an array designator.
4709 Designator(unsigned Index, SourceLocation LBracketLoc,
4710 SourceLocation RBracketLoc)
4711 : Kind(ArrayDesignator) {
4712 ArrayOrRange.Index = Index;
4713 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
4714 ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding();
4715 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
4718 /// Initializes a GNU array-range designator.
4719 Designator(unsigned Index, SourceLocation LBracketLoc,
4720 SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
4721 : Kind(ArrayRangeDesignator) {
4722 ArrayOrRange.Index = Index;
4723 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
4724 ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding();
4725 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
4728 bool isFieldDesignator() const { return Kind == FieldDesignator; }
4729 bool isArrayDesignator() const { return Kind == ArrayDesignator; }
4730 bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
4732 IdentifierInfo *getFieldName() const;
4734 FieldDecl *getField() const {
4735 assert(Kind == FieldDesignator && "Only valid on a field designator");
4736 if (Field.NameOrField & 0x01)
4739 return reinterpret_cast<FieldDecl *>(Field.NameOrField);
4742 void setField(FieldDecl *FD) {
4743 assert(Kind == FieldDesignator && "Only valid on a field designator");
4744 Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
4747 SourceLocation getDotLoc() const {
4748 assert(Kind == FieldDesignator && "Only valid on a field designator");
4749 return SourceLocation::getFromRawEncoding(Field.DotLoc);
4752 SourceLocation getFieldLoc() const {
4753 assert(Kind == FieldDesignator && "Only valid on a field designator");
4754 return SourceLocation::getFromRawEncoding(Field.FieldLoc);
4757 SourceLocation getLBracketLoc() const {
4758 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4759 "Only valid on an array or array-range designator");
4760 return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc);
4763 SourceLocation getRBracketLoc() const {
4764 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4765 "Only valid on an array or array-range designator");
4766 return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc);
4769 SourceLocation getEllipsisLoc() const {
4770 assert(Kind == ArrayRangeDesignator &&
4771 "Only valid on an array-range designator");
4772 return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc);
4775 unsigned getFirstExprIndex() const {
4776 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4777 "Only valid on an array or array-range designator");
4778 return ArrayOrRange.Index;
4781 SourceLocation getBeginLoc() const LLVM_READONLY {
4782 if (Kind == FieldDesignator)
4783 return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc();
4785 return getLBracketLoc();
4787 SourceLocation getEndLoc() const LLVM_READONLY {
4788 return Kind == FieldDesignator ? getFieldLoc() : getRBracketLoc();
4790 SourceRange getSourceRange() const LLVM_READONLY {
4791 return SourceRange(getBeginLoc(), getEndLoc());
4795 static DesignatedInitExpr *Create(const ASTContext &C,
4796 llvm::ArrayRef<Designator> Designators,
4797 ArrayRef<Expr*> IndexExprs,
4798 SourceLocation EqualOrColonLoc,
4799 bool GNUSyntax, Expr *Init);
4801 static DesignatedInitExpr *CreateEmpty(const ASTContext &C,
4802 unsigned NumIndexExprs);
4804 /// Returns the number of designators in this initializer.
4805 unsigned size() const { return NumDesignators; }
4807 // Iterator access to the designators.
4808 llvm::MutableArrayRef<Designator> designators() {
4809 return {Designators, NumDesignators};
4812 llvm::ArrayRef<Designator> designators() const {
4813 return {Designators, NumDesignators};
4816 Designator *getDesignator(unsigned Idx) { return &designators()[Idx]; }
4817 const Designator *getDesignator(unsigned Idx) const {
4818 return &designators()[Idx];
4821 void setDesignators(const ASTContext &C, const Designator *Desigs,
4822 unsigned NumDesigs);
4824 Expr *getArrayIndex(const Designator &D) const;
4825 Expr *getArrayRangeStart(const Designator &D) const;
4826 Expr *getArrayRangeEnd(const Designator &D) const;
4828 /// Retrieve the location of the '=' that precedes the
4829 /// initializer value itself, if present.
4830 SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
4831 void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
4833 /// Determines whether this designated initializer used the
4834 /// deprecated GNU syntax for designated initializers.
4835 bool usesGNUSyntax() const { return GNUSyntax; }
4836 void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
4838 /// Retrieve the initializer value.
4839 Expr *getInit() const {
4840 return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
4843 void setInit(Expr *init) {
4844 *child_begin() = init;
4847 /// Retrieve the total number of subexpressions in this
4848 /// designated initializer expression, including the actual
4849 /// initialized value and any expressions that occur within array
4850 /// and array-range designators.
4851 unsigned getNumSubExprs() const { return NumSubExprs; }
4853 Expr *getSubExpr(unsigned Idx) const {
4854 assert(Idx < NumSubExprs && "Subscript out of range");
4855 return cast<Expr>(getTrailingObjects<Stmt *>()[Idx]);
4858 void setSubExpr(unsigned Idx, Expr *E) {
4859 assert(Idx < NumSubExprs && "Subscript out of range");
4860 getTrailingObjects<Stmt *>()[Idx] = E;
4863 /// Replaces the designator at index @p Idx with the series
4864 /// of designators in [First, Last).
4865 void ExpandDesignator(const ASTContext &C, unsigned Idx,
4866 const Designator *First, const Designator *Last);
4868 SourceRange getDesignatorsSourceRange() const;
4870 SourceLocation getBeginLoc() const LLVM_READONLY;
4871 SourceLocation getEndLoc() const LLVM_READONLY;
4873 static bool classof(const Stmt *T) {
4874 return T->getStmtClass() == DesignatedInitExprClass;
4878 child_range children() {
4879 Stmt **begin = getTrailingObjects<Stmt *>();
4880 return child_range(begin, begin + NumSubExprs);
4882 const_child_range children() const {
4883 Stmt * const *begin = getTrailingObjects<Stmt *>();
4884 return const_child_range(begin, begin + NumSubExprs);
4887 friend TrailingObjects;
4890 /// Represents a place-holder for an object not to be initialized by
4893 /// This only makes sense when it appears as part of an updater of a
4894 /// DesignatedInitUpdateExpr (see below). The base expression of a DIUE
4895 /// initializes a big object, and the NoInitExpr's mark the spots within the
4896 /// big object not to be overwritten by the updater.
4898 /// \see DesignatedInitUpdateExpr
4899 class NoInitExpr : public Expr {
4901 explicit NoInitExpr(QualType ty)
4902 : Expr(NoInitExprClass, ty, VK_RValue, OK_Ordinary,
4903 false, false, ty->isInstantiationDependentType(), false) { }
4905 explicit NoInitExpr(EmptyShell Empty)
4906 : Expr(NoInitExprClass, Empty) { }
4908 static bool classof(const Stmt *T) {
4909 return T->getStmtClass() == NoInitExprClass;
4912 SourceLocation getBeginLoc() const LLVM_READONLY { return SourceLocation(); }
4913 SourceLocation getEndLoc() const LLVM_READONLY { return SourceLocation(); }
4916 child_range children() {
4917 return child_range(child_iterator(), child_iterator());
4919 const_child_range children() const {
4920 return const_child_range(const_child_iterator(), const_child_iterator());
4925 // struct Q { int a, b, c; };
4928 // struct A { Q q; } a = { *getQ(), .q.b = 3 };
4931 // We will have an InitListExpr for a, with type A, and then a
4932 // DesignatedInitUpdateExpr for "a.q" with type Q. The "base" for this DIUE
4933 // is the call expression *getQ(); the "updater" for the DIUE is ".q.b = 3"
4935 class DesignatedInitUpdateExpr : public Expr {
4936 // BaseAndUpdaterExprs[0] is the base expression;
4937 // BaseAndUpdaterExprs[1] is an InitListExpr overwriting part of the base.
4938 Stmt *BaseAndUpdaterExprs[2];
4941 DesignatedInitUpdateExpr(const ASTContext &C, SourceLocation lBraceLoc,
4942 Expr *baseExprs, SourceLocation rBraceLoc);
4944 explicit DesignatedInitUpdateExpr(EmptyShell Empty)
4945 : Expr(DesignatedInitUpdateExprClass, Empty) { }
4947 SourceLocation getBeginLoc() const LLVM_READONLY;
4948 SourceLocation getEndLoc() const LLVM_READONLY;
4950 static bool classof(const Stmt *T) {
4951 return T->getStmtClass() == DesignatedInitUpdateExprClass;
4954 Expr *getBase() const { return cast<Expr>(BaseAndUpdaterExprs[0]); }
4955 void setBase(Expr *Base) { BaseAndUpdaterExprs[0] = Base; }
4957 InitListExpr *getUpdater() const {
4958 return cast<InitListExpr>(BaseAndUpdaterExprs[1]);
4960 void setUpdater(Expr *Updater) { BaseAndUpdaterExprs[1] = Updater; }
4963 // children = the base and the updater
4964 child_range children() {
4965 return child_range(&BaseAndUpdaterExprs[0], &BaseAndUpdaterExprs[0] + 2);
4967 const_child_range children() const {
4968 return const_child_range(&BaseAndUpdaterExprs[0],
4969 &BaseAndUpdaterExprs[0] + 2);
4973 /// Represents a loop initializing the elements of an array.
4975 /// The need to initialize the elements of an array occurs in a number of
4978 /// * in the implicit copy/move constructor for a class with an array member
4979 /// * when a lambda-expression captures an array by value
4980 /// * when a decomposition declaration decomposes an array
4982 /// There are two subexpressions: a common expression (the source array)
4983 /// that is evaluated once up-front, and a per-element initializer that
4984 /// runs once for each array element.
4986 /// Within the per-element initializer, the common expression may be referenced
4987 /// via an OpaqueValueExpr, and the current index may be obtained via an
4988 /// ArrayInitIndexExpr.
4989 class ArrayInitLoopExpr : public Expr {
4992 explicit ArrayInitLoopExpr(EmptyShell Empty)
4993 : Expr(ArrayInitLoopExprClass, Empty), SubExprs{} {}
4996 explicit ArrayInitLoopExpr(QualType T, Expr *CommonInit, Expr *ElementInit)
4997 : Expr(ArrayInitLoopExprClass, T, VK_RValue, OK_Ordinary, false,
4998 CommonInit->isValueDependent() || ElementInit->isValueDependent(),
4999 T->isInstantiationDependentType(),
5000 CommonInit->containsUnexpandedParameterPack() ||
5001 ElementInit->containsUnexpandedParameterPack()),
5002 SubExprs{CommonInit, ElementInit} {}
5004 /// Get the common subexpression shared by all initializations (the source
5006 OpaqueValueExpr *getCommonExpr() const {
5007 return cast<OpaqueValueExpr>(SubExprs[0]);
5010 /// Get the initializer to use for each array element.
5011 Expr *getSubExpr() const { return cast<Expr>(SubExprs[1]); }
5013 llvm::APInt getArraySize() const {
5014 return cast<ConstantArrayType>(getType()->castAsArrayTypeUnsafe())
5018 static bool classof(const Stmt *S) {
5019 return S->getStmtClass() == ArrayInitLoopExprClass;
5022 SourceLocation getBeginLoc() const LLVM_READONLY {
5023 return getCommonExpr()->getBeginLoc();
5025 SourceLocation getEndLoc() const LLVM_READONLY {
5026 return getCommonExpr()->getEndLoc();
5029 child_range children() {
5030 return child_range(SubExprs, SubExprs + 2);
5032 const_child_range children() const {
5033 return const_child_range(SubExprs, SubExprs + 2);
5036 friend class ASTReader;
5037 friend class ASTStmtReader;
5038 friend class ASTStmtWriter;
5041 /// Represents the index of the current element of an array being
5042 /// initialized by an ArrayInitLoopExpr. This can only appear within the
5043 /// subexpression of an ArrayInitLoopExpr.
5044 class ArrayInitIndexExpr : public Expr {
5045 explicit ArrayInitIndexExpr(EmptyShell Empty)
5046 : Expr(ArrayInitIndexExprClass, Empty) {}
5049 explicit ArrayInitIndexExpr(QualType T)
5050 : Expr(ArrayInitIndexExprClass, T, VK_RValue, OK_Ordinary,
5051 false, false, false, false) {}
5053 static bool classof(const Stmt *S) {
5054 return S->getStmtClass() == ArrayInitIndexExprClass;
5057 SourceLocation getBeginLoc() const LLVM_READONLY { return SourceLocation(); }
5058 SourceLocation getEndLoc() const LLVM_READONLY { return SourceLocation(); }
5060 child_range children() {
5061 return child_range(child_iterator(), child_iterator());
5063 const_child_range children() const {
5064 return const_child_range(const_child_iterator(), const_child_iterator());
5067 friend class ASTReader;
5068 friend class ASTStmtReader;
5071 /// Represents an implicitly-generated value initialization of
5072 /// an object of a given type.
5074 /// Implicit value initializations occur within semantic initializer
5075 /// list expressions (InitListExpr) as placeholders for subobject
5076 /// initializations not explicitly specified by the user.
5078 /// \see InitListExpr
5079 class ImplicitValueInitExpr : public Expr {
5081 explicit ImplicitValueInitExpr(QualType ty)
5082 : Expr(ImplicitValueInitExprClass, ty, VK_RValue, OK_Ordinary,
5083 false, false, ty->isInstantiationDependentType(), false) { }
5085 /// Construct an empty implicit value initialization.
5086 explicit ImplicitValueInitExpr(EmptyShell Empty)
5087 : Expr(ImplicitValueInitExprClass, Empty) { }
5089 static bool classof(const Stmt *T) {
5090 return T->getStmtClass() == ImplicitValueInitExprClass;
5093 SourceLocation getBeginLoc() const LLVM_READONLY { return SourceLocation(); }
5094 SourceLocation getEndLoc() const LLVM_READONLY { return SourceLocation(); }
5097 child_range children() {
5098 return child_range(child_iterator(), child_iterator());
5100 const_child_range children() const {
5101 return const_child_range(const_child_iterator(), const_child_iterator());
5105 class ParenListExpr final
5107 private llvm::TrailingObjects<ParenListExpr, Stmt *> {
5108 friend class ASTStmtReader;
5109 friend TrailingObjects;
5111 /// The location of the left and right parentheses.
5112 SourceLocation LParenLoc, RParenLoc;
5114 /// Build a paren list.
5115 ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,
5116 SourceLocation RParenLoc);
5118 /// Build an empty paren list.
5119 ParenListExpr(EmptyShell Empty, unsigned NumExprs);
5122 /// Create a paren list.
5123 static ParenListExpr *Create(const ASTContext &Ctx, SourceLocation LParenLoc,
5124 ArrayRef<Expr *> Exprs,
5125 SourceLocation RParenLoc);
5127 /// Create an empty paren list.
5128 static ParenListExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumExprs);
5130 /// Return the number of expressions in this paren list.
5131 unsigned getNumExprs() const { return ParenListExprBits.NumExprs; }
5133 Expr *getExpr(unsigned Init) {
5134 assert(Init < getNumExprs() && "Initializer access out of range!");
5135 return getExprs()[Init];
5138 const Expr *getExpr(unsigned Init) const {
5139 return const_cast<ParenListExpr *>(this)->getExpr(Init);
5143 return reinterpret_cast<Expr **>(getTrailingObjects<Stmt *>());
5146 ArrayRef<Expr *> exprs() {
5147 return llvm::makeArrayRef(getExprs(), getNumExprs());
5150 SourceLocation getLParenLoc() const { return LParenLoc; }
5151 SourceLocation getRParenLoc() const { return RParenLoc; }
5152 SourceLocation getBeginLoc() const { return getLParenLoc(); }
5153 SourceLocation getEndLoc() const { return getRParenLoc(); }
5155 static bool classof(const Stmt *T) {
5156 return T->getStmtClass() == ParenListExprClass;
5160 child_range children() {
5161 return child_range(getTrailingObjects<Stmt *>(),
5162 getTrailingObjects<Stmt *>() + getNumExprs());
5164 const_child_range children() const {
5165 return const_child_range(getTrailingObjects<Stmt *>(),
5166 getTrailingObjects<Stmt *>() + getNumExprs());
5170 /// Represents a C11 generic selection.
5172 /// A generic selection (C11 6.5.1.1) contains an unevaluated controlling
5173 /// expression, followed by one or more generic associations. Each generic
5174 /// association specifies a type name and an expression, or "default" and an
5175 /// expression (in which case it is known as a default generic association).
5176 /// The type and value of the generic selection are identical to those of its
5177 /// result expression, which is defined as the expression in the generic
5178 /// association with a type name that is compatible with the type of the
5179 /// controlling expression, or the expression in the default generic association
5180 /// if no types are compatible. For example:
5183 /// _Generic(X, double: 1, float: 2, default: 3)
5186 /// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f
5187 /// or 3 if "hello".
5189 /// As an extension, generic selections are allowed in C++, where the following
5190 /// additional semantics apply:
5192 /// Any generic selection whose controlling expression is type-dependent or
5193 /// which names a dependent type in its association list is result-dependent,
5194 /// which means that the choice of result expression is dependent.
5195 /// Result-dependent generic associations are both type- and value-dependent.
5196 class GenericSelectionExpr final
5198 private llvm::TrailingObjects<GenericSelectionExpr, Stmt *,
5200 friend class ASTStmtReader;
5201 friend class ASTStmtWriter;
5202 friend TrailingObjects;
5204 /// The number of association expressions and the index of the result
5205 /// expression in the case where the generic selection expression is not
5206 /// result-dependent. The result index is equal to ResultDependentIndex
5207 /// if and only if the generic selection expression is result-dependent.
5208 unsigned NumAssocs, ResultIndex;
5210 ResultDependentIndex = std::numeric_limits<unsigned>::max(),
5211 ControllingIndex = 0,
5212 AssocExprStartIndex = 1
5215 /// The location of the "default" and of the right parenthesis.
5216 SourceLocation DefaultLoc, RParenLoc;
5218 // GenericSelectionExpr is followed by several trailing objects.
5219 // They are (in order):
5221 // * A single Stmt * for the controlling expression.
5222 // * An array of getNumAssocs() Stmt * for the association expressions.
5223 // * An array of getNumAssocs() TypeSourceInfo *, one for each of the
5224 // association expressions.
5225 unsigned numTrailingObjects(OverloadToken<Stmt *>) const {
5226 // Add one to account for the controlling expression; the remainder
5227 // are the associated expressions.
5228 return 1 + getNumAssocs();
5231 unsigned numTrailingObjects(OverloadToken<TypeSourceInfo *>) const {
5232 return getNumAssocs();
5235 template <bool Const> class AssociationIteratorTy;
5236 /// Bundle together an association expression and its TypeSourceInfo.
5237 /// The Const template parameter is for the const and non-const versions
5238 /// of AssociationTy.
5239 template <bool Const> class AssociationTy {
5240 friend class GenericSelectionExpr;
5241 template <bool OtherConst> friend class AssociationIteratorTy;
5243 typename std::conditional<Const, const Expr *, Expr *>::type;
5244 using TSIPtrTy = typename std::conditional<Const, const TypeSourceInfo *,
5245 TypeSourceInfo *>::type;
5249 AssociationTy(ExprPtrTy E, TSIPtrTy TSI, bool Selected)
5250 : E(E), TSI(TSI), Selected(Selected) {}
5253 ExprPtrTy getAssociationExpr() const { return E; }
5254 TSIPtrTy getTypeSourceInfo() const { return TSI; }
5255 QualType getType() const { return TSI ? TSI->getType() : QualType(); }
5256 bool isSelected() const { return Selected; }
5257 AssociationTy *operator->() { return this; }
5258 const AssociationTy *operator->() const { return this; }
5259 }; // class AssociationTy
5261 /// Iterator over const and non-const Association objects. The Association
5262 /// objects are created on the fly when the iterator is dereferenced.
5263 /// This abstract over how exactly the association expressions and the
5264 /// corresponding TypeSourceInfo * are stored.
5265 template <bool Const>
5266 class AssociationIteratorTy
5267 : public llvm::iterator_facade_base<
5268 AssociationIteratorTy<Const>, std::input_iterator_tag,
5269 AssociationTy<Const>, std::ptrdiff_t, AssociationTy<Const>,
5270 AssociationTy<Const>> {
5271 friend class GenericSelectionExpr;
5272 // FIXME: This iterator could conceptually be a random access iterator, and
5273 // it would be nice if we could strengthen the iterator category someday.
5274 // However this iterator does not satisfy two requirements of forward
5276 // a) reference = T& or reference = const T&
5277 // b) If It1 and It2 are both dereferenceable, then It1 == It2 if and only
5278 // if *It1 and *It2 are bound to the same objects.
5279 // An alternative design approach was discussed during review;
5280 // store an Association object inside the iterator, and return a reference
5281 // to it when dereferenced. This idea was discarded beacuse of nasty
5283 // AssociationIterator It = ...;
5284 // const Association &Assoc = *It++; // Oops, Assoc is dangling.
5285 using BaseTy = typename AssociationIteratorTy::iterator_facade_base;
5286 using StmtPtrPtrTy =
5287 typename std::conditional<Const, const Stmt *const *, Stmt **>::type;
5289 typename std::conditional<Const, const TypeSourceInfo *const *,
5290 TypeSourceInfo **>::type;
5291 StmtPtrPtrTy E; // = nullptr; FIXME: Once support for gcc 4.8 is dropped.
5292 TSIPtrPtrTy TSI; // Kept in sync with E.
5293 unsigned Offset = 0, SelectedOffset = 0;
5294 AssociationIteratorTy(StmtPtrPtrTy E, TSIPtrPtrTy TSI, unsigned Offset,
5295 unsigned SelectedOffset)
5296 : E(E), TSI(TSI), Offset(Offset), SelectedOffset(SelectedOffset) {}
5299 AssociationIteratorTy() : E(nullptr), TSI(nullptr) {}
5300 typename BaseTy::reference operator*() const {
5301 return AssociationTy<Const>(cast<Expr>(*E), *TSI,
5302 Offset == SelectedOffset);
5304 typename BaseTy::pointer operator->() const { return **this; }
5305 using BaseTy::operator++;
5306 AssociationIteratorTy &operator++() {
5312 bool operator==(AssociationIteratorTy Other) const { return E == Other.E; }
5313 }; // class AssociationIterator
5315 /// Build a non-result-dependent generic selection expression.
5316 GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc,
5317 Expr *ControllingExpr,
5318 ArrayRef<TypeSourceInfo *> AssocTypes,
5319 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
5320 SourceLocation RParenLoc,
5321 bool ContainsUnexpandedParameterPack,
5322 unsigned ResultIndex);
5324 /// Build a result-dependent generic selection expression.
5325 GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc,
5326 Expr *ControllingExpr,
5327 ArrayRef<TypeSourceInfo *> AssocTypes,
5328 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
5329 SourceLocation RParenLoc,
5330 bool ContainsUnexpandedParameterPack);
5332 /// Build an empty generic selection expression for deserialization.
5333 explicit GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs);
5336 /// Create a non-result-dependent generic selection expression.
5337 static GenericSelectionExpr *
5338 Create(const ASTContext &Context, SourceLocation GenericLoc,
5339 Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> AssocTypes,
5340 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
5341 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack,
5342 unsigned ResultIndex);
5344 /// Create a result-dependent generic selection expression.
5345 static GenericSelectionExpr *
5346 Create(const ASTContext &Context, SourceLocation GenericLoc,
5347 Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> AssocTypes,
5348 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
5349 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack);
5351 /// Create an empty generic selection expression for deserialization.
5352 static GenericSelectionExpr *CreateEmpty(const ASTContext &Context,
5353 unsigned NumAssocs);
5355 using Association = AssociationTy<false>;
5356 using ConstAssociation = AssociationTy<true>;
5357 using AssociationIterator = AssociationIteratorTy<false>;
5358 using ConstAssociationIterator = AssociationIteratorTy<true>;
5359 using association_range = llvm::iterator_range<AssociationIterator>;
5360 using const_association_range =
5361 llvm::iterator_range<ConstAssociationIterator>;
5363 /// The number of association expressions.
5364 unsigned getNumAssocs() const { return NumAssocs; }
5366 /// The zero-based index of the result expression's generic association in
5367 /// the generic selection's association list. Defined only if the
5368 /// generic selection is not result-dependent.
5369 unsigned getResultIndex() const {
5370 assert(!isResultDependent() &&
5371 "Generic selection is result-dependent but getResultIndex called!");
5375 /// Whether this generic selection is result-dependent.
5376 bool isResultDependent() const { return ResultIndex == ResultDependentIndex; }
5378 /// Return the controlling expression of this generic selection expression.
5379 Expr *getControllingExpr() {
5380 return cast<Expr>(getTrailingObjects<Stmt *>()[ControllingIndex]);
5382 const Expr *getControllingExpr() const {
5383 return cast<Expr>(getTrailingObjects<Stmt *>()[ControllingIndex]);
5386 /// Return the result expression of this controlling expression. Defined if
5387 /// and only if the generic selection expression is not result-dependent.
5388 Expr *getResultExpr() {
5390 getTrailingObjects<Stmt *>()[AssocExprStartIndex + getResultIndex()]);
5392 const Expr *getResultExpr() const {
5394 getTrailingObjects<Stmt *>()[AssocExprStartIndex + getResultIndex()]);
5397 ArrayRef<Expr *> getAssocExprs() const {
5398 return {reinterpret_cast<Expr *const *>(getTrailingObjects<Stmt *>() +
5399 AssocExprStartIndex),
5402 ArrayRef<TypeSourceInfo *> getAssocTypeSourceInfos() const {
5403 return {getTrailingObjects<TypeSourceInfo *>(), NumAssocs};
5406 /// Return the Ith association expression with its TypeSourceInfo,
5407 /// bundled together in GenericSelectionExpr::(Const)Association.
5408 Association getAssociation(unsigned I) {
5409 assert(I < getNumAssocs() &&
5410 "Out-of-range index in GenericSelectionExpr::getAssociation!");
5412 cast<Expr>(getTrailingObjects<Stmt *>()[AssocExprStartIndex + I]),
5413 getTrailingObjects<TypeSourceInfo *>()[I],
5414 !isResultDependent() && (getResultIndex() == I));
5416 ConstAssociation getAssociation(unsigned I) const {
5417 assert(I < getNumAssocs() &&
5418 "Out-of-range index in GenericSelectionExpr::getAssociation!");
5419 return ConstAssociation(
5420 cast<Expr>(getTrailingObjects<Stmt *>()[AssocExprStartIndex + I]),
5421 getTrailingObjects<TypeSourceInfo *>()[I],
5422 !isResultDependent() && (getResultIndex() == I));
5425 association_range associations() {
5426 AssociationIterator Begin(getTrailingObjects<Stmt *>() +
5427 AssocExprStartIndex,
5428 getTrailingObjects<TypeSourceInfo *>(),
5429 /*Offset=*/0, ResultIndex);
5430 AssociationIterator End(Begin.E + NumAssocs, Begin.TSI + NumAssocs,
5431 /*Offset=*/NumAssocs, ResultIndex);
5432 return llvm::make_range(Begin, End);
5435 const_association_range associations() const {
5436 ConstAssociationIterator Begin(getTrailingObjects<Stmt *>() +
5437 AssocExprStartIndex,
5438 getTrailingObjects<TypeSourceInfo *>(),
5439 /*Offset=*/0, ResultIndex);
5440 ConstAssociationIterator End(Begin.E + NumAssocs, Begin.TSI + NumAssocs,
5441 /*Offset=*/NumAssocs, ResultIndex);
5442 return llvm::make_range(Begin, End);
5445 SourceLocation getGenericLoc() const {
5446 return GenericSelectionExprBits.GenericLoc;
5448 SourceLocation getDefaultLoc() const { return DefaultLoc; }
5449 SourceLocation getRParenLoc() const { return RParenLoc; }
5450 SourceLocation getBeginLoc() const { return getGenericLoc(); }
5451 SourceLocation getEndLoc() const { return getRParenLoc(); }
5453 static bool classof(const Stmt *T) {
5454 return T->getStmtClass() == GenericSelectionExprClass;
5457 child_range children() {
5458 return child_range(getTrailingObjects<Stmt *>(),
5459 getTrailingObjects<Stmt *>() +
5460 numTrailingObjects(OverloadToken<Stmt *>()));
5462 const_child_range children() const {
5463 return const_child_range(getTrailingObjects<Stmt *>(),
5464 getTrailingObjects<Stmt *>() +
5465 numTrailingObjects(OverloadToken<Stmt *>()));
5469 //===----------------------------------------------------------------------===//
5471 //===----------------------------------------------------------------------===//
5473 /// ExtVectorElementExpr - This represents access to specific elements of a
5474 /// vector, and may occur on the left hand side or right hand side. For example
5475 /// the following is legal: "V.xy = V.zw" if V is a 4 element extended vector.
5477 /// Note that the base may have either vector or pointer to vector type, just
5478 /// like a struct field reference.
5480 class ExtVectorElementExpr : public Expr {
5482 IdentifierInfo *Accessor;
5483 SourceLocation AccessorLoc;
5485 ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base,
5486 IdentifierInfo &accessor, SourceLocation loc)
5487 : Expr(ExtVectorElementExprClass, ty, VK,
5488 (VK == VK_RValue ? OK_Ordinary : OK_VectorComponent),
5489 base->isTypeDependent(), base->isValueDependent(),
5490 base->isInstantiationDependent(),
5491 base->containsUnexpandedParameterPack()),
5492 Base(base), Accessor(&accessor), AccessorLoc(loc) {}
5494 /// Build an empty vector element expression.
5495 explicit ExtVectorElementExpr(EmptyShell Empty)
5496 : Expr(ExtVectorElementExprClass, Empty) { }
5498 const Expr *getBase() const { return cast<Expr>(Base); }
5499 Expr *getBase() { return cast<Expr>(Base); }
5500 void setBase(Expr *E) { Base = E; }
5502 IdentifierInfo &getAccessor() const { return *Accessor; }
5503 void setAccessor(IdentifierInfo *II) { Accessor = II; }
5505 SourceLocation getAccessorLoc() const { return AccessorLoc; }
5506 void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
5508 /// getNumElements - Get the number of components being selected.
5509 unsigned getNumElements() const;
5511 /// containsDuplicateElements - Return true if any element access is
5513 bool containsDuplicateElements() const;
5515 /// getEncodedElementAccess - Encode the elements accessed into an llvm
5516 /// aggregate Constant of ConstantInt(s).
5517 void getEncodedElementAccess(SmallVectorImpl<uint32_t> &Elts) const;
5519 SourceLocation getBeginLoc() const LLVM_READONLY {
5520 return getBase()->getBeginLoc();
5522 SourceLocation getEndLoc() const LLVM_READONLY { return AccessorLoc; }
5524 /// isArrow - Return true if the base expression is a pointer to vector,
5525 /// return false if the base expression is a vector.
5526 bool isArrow() const;
5528 static bool classof(const Stmt *T) {
5529 return T->getStmtClass() == ExtVectorElementExprClass;
5533 child_range children() { return child_range(&Base, &Base+1); }
5534 const_child_range children() const {
5535 return const_child_range(&Base, &Base + 1);
5539 /// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
5540 /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
5541 class BlockExpr : public Expr {
5543 BlockDecl *TheBlock;
5545 BlockExpr(BlockDecl *BD, QualType ty)
5546 : Expr(BlockExprClass, ty, VK_RValue, OK_Ordinary,
5547 ty->isDependentType(), ty->isDependentType(),
5548 ty->isInstantiationDependentType() || BD->isDependentContext(),
5552 /// Build an empty block expression.
5553 explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
5555 const BlockDecl *getBlockDecl() const { return TheBlock; }
5556 BlockDecl *getBlockDecl() { return TheBlock; }
5557 void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
5559 // Convenience functions for probing the underlying BlockDecl.
5560 SourceLocation getCaretLocation() const;
5561 const Stmt *getBody() const;
5564 SourceLocation getBeginLoc() const LLVM_READONLY {
5565 return getCaretLocation();
5567 SourceLocation getEndLoc() const LLVM_READONLY {
5568 return getBody()->getEndLoc();
5571 /// getFunctionType - Return the underlying function type for this block.
5572 const FunctionProtoType *getFunctionType() const;
5574 static bool classof(const Stmt *T) {
5575 return T->getStmtClass() == BlockExprClass;
5579 child_range children() {
5580 return child_range(child_iterator(), child_iterator());
5582 const_child_range children() const {
5583 return const_child_range(const_child_iterator(), const_child_iterator());
5587 /// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2]
5588 /// This AST node provides support for reinterpreting a type to another
5589 /// type of the same size.
5590 class AsTypeExpr : public Expr {
5593 SourceLocation BuiltinLoc, RParenLoc;
5595 friend class ASTReader;
5596 friend class ASTStmtReader;
5597 explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {}
5600 AsTypeExpr(Expr* SrcExpr, QualType DstType,
5601 ExprValueKind VK, ExprObjectKind OK,
5602 SourceLocation BuiltinLoc, SourceLocation RParenLoc)
5603 : Expr(AsTypeExprClass, DstType, VK, OK,
5604 DstType->isDependentType(),
5605 DstType->isDependentType() || SrcExpr->isValueDependent(),
5606 (DstType->isInstantiationDependentType() ||
5607 SrcExpr->isInstantiationDependent()),
5608 (DstType->containsUnexpandedParameterPack() ||
5609 SrcExpr->containsUnexpandedParameterPack())),
5610 SrcExpr(SrcExpr), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
5612 /// getSrcExpr - Return the Expr to be converted.
5613 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
5615 /// getBuiltinLoc - Return the location of the __builtin_astype token.
5616 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
5618 /// getRParenLoc - Return the location of final right parenthesis.
5619 SourceLocation getRParenLoc() const { return RParenLoc; }
5621 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
5622 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
5624 static bool classof(const Stmt *T) {
5625 return T->getStmtClass() == AsTypeExprClass;
5629 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
5630 const_child_range children() const {
5631 return const_child_range(&SrcExpr, &SrcExpr + 1);
5635 /// PseudoObjectExpr - An expression which accesses a pseudo-object
5636 /// l-value. A pseudo-object is an abstract object, accesses to which
5637 /// are translated to calls. The pseudo-object expression has a
5638 /// syntactic form, which shows how the expression was actually
5639 /// written in the source code, and a semantic form, which is a series
5640 /// of expressions to be executed in order which detail how the
5641 /// operation is actually evaluated. Optionally, one of the semantic
5642 /// forms may also provide a result value for the expression.
5644 /// If any of the semantic-form expressions is an OpaqueValueExpr,
5645 /// that OVE is required to have a source expression, and it is bound
5646 /// to the result of that source expression. Such OVEs may appear
5647 /// only in subsequent semantic-form expressions and as
5648 /// sub-expressions of the syntactic form.
5650 /// PseudoObjectExpr should be used only when an operation can be
5651 /// usefully described in terms of fairly simple rewrite rules on
5652 /// objects and functions that are meant to be used by end-developers.
5653 /// For example, under the Itanium ABI, dynamic casts are implemented
5654 /// as a call to a runtime function called __dynamic_cast; using this
5655 /// class to describe that would be inappropriate because that call is
5656 /// not really part of the user-visible semantics, and instead the
5657 /// cast is properly reflected in the AST and IR-generation has been
5658 /// taught to generate the call as necessary. In contrast, an
5659 /// Objective-C property access is semantically defined to be
5660 /// equivalent to a particular message send, and this is very much
5661 /// part of the user model. The name of this class encourages this
5662 /// modelling design.
5663 class PseudoObjectExpr final
5665 private llvm::TrailingObjects<PseudoObjectExpr, Expr *> {
5666 // PseudoObjectExprBits.NumSubExprs - The number of sub-expressions.
5667 // Always at least two, because the first sub-expression is the
5670 // PseudoObjectExprBits.ResultIndex - The index of the
5671 // sub-expression holding the result. 0 means the result is void,
5672 // which is unambiguous because it's the index of the syntactic
5673 // form. Note that this is therefore 1 higher than the value passed
5674 // in to Create, which is an index within the semantic forms.
5675 // Note also that ASTStmtWriter assumes this encoding.
5677 Expr **getSubExprsBuffer() { return getTrailingObjects<Expr *>(); }
5678 const Expr * const *getSubExprsBuffer() const {
5679 return getTrailingObjects<Expr *>();
5682 PseudoObjectExpr(QualType type, ExprValueKind VK,
5683 Expr *syntactic, ArrayRef<Expr*> semantic,
5684 unsigned resultIndex);
5686 PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs);
5688 unsigned getNumSubExprs() const {
5689 return PseudoObjectExprBits.NumSubExprs;
5693 /// NoResult - A value for the result index indicating that there is
5694 /// no semantic result.
5695 enum : unsigned { NoResult = ~0U };
5697 static PseudoObjectExpr *Create(const ASTContext &Context, Expr *syntactic,
5698 ArrayRef<Expr*> semantic,
5699 unsigned resultIndex);
5701 static PseudoObjectExpr *Create(const ASTContext &Context, EmptyShell shell,
5702 unsigned numSemanticExprs);
5704 /// Return the syntactic form of this expression, i.e. the
5705 /// expression it actually looks like. Likely to be expressed in
5706 /// terms of OpaqueValueExprs bound in the semantic form.
5707 Expr *getSyntacticForm() { return getSubExprsBuffer()[0]; }
5708 const Expr *getSyntacticForm() const { return getSubExprsBuffer()[0]; }
5710 /// Return the index of the result-bearing expression into the semantics
5711 /// expressions, or PseudoObjectExpr::NoResult if there is none.
5712 unsigned getResultExprIndex() const {
5713 if (PseudoObjectExprBits.ResultIndex == 0) return NoResult;
5714 return PseudoObjectExprBits.ResultIndex - 1;
5717 /// Return the result-bearing expression, or null if there is none.
5718 Expr *getResultExpr() {
5719 if (PseudoObjectExprBits.ResultIndex == 0)
5721 return getSubExprsBuffer()[PseudoObjectExprBits.ResultIndex];
5723 const Expr *getResultExpr() const {
5724 return const_cast<PseudoObjectExpr*>(this)->getResultExpr();
5727 unsigned getNumSemanticExprs() const { return getNumSubExprs() - 1; }
5729 typedef Expr * const *semantics_iterator;
5730 typedef const Expr * const *const_semantics_iterator;
5731 semantics_iterator semantics_begin() {
5732 return getSubExprsBuffer() + 1;
5734 const_semantics_iterator semantics_begin() const {
5735 return getSubExprsBuffer() + 1;
5737 semantics_iterator semantics_end() {
5738 return getSubExprsBuffer() + getNumSubExprs();
5740 const_semantics_iterator semantics_end() const {
5741 return getSubExprsBuffer() + getNumSubExprs();
5744 llvm::iterator_range<semantics_iterator> semantics() {
5745 return llvm::make_range(semantics_begin(), semantics_end());
5747 llvm::iterator_range<const_semantics_iterator> semantics() const {
5748 return llvm::make_range(semantics_begin(), semantics_end());
5751 Expr *getSemanticExpr(unsigned index) {
5752 assert(index + 1 < getNumSubExprs());
5753 return getSubExprsBuffer()[index + 1];
5755 const Expr *getSemanticExpr(unsigned index) const {
5756 return const_cast<PseudoObjectExpr*>(this)->getSemanticExpr(index);
5759 SourceLocation getExprLoc() const LLVM_READONLY {
5760 return getSyntacticForm()->getExprLoc();
5763 SourceLocation getBeginLoc() const LLVM_READONLY {
5764 return getSyntacticForm()->getBeginLoc();
5766 SourceLocation getEndLoc() const LLVM_READONLY {
5767 return getSyntacticForm()->getEndLoc();
5770 child_range children() {
5771 const_child_range CCR =
5772 const_cast<const PseudoObjectExpr *>(this)->children();
5773 return child_range(cast_away_const(CCR.begin()),
5774 cast_away_const(CCR.end()));
5776 const_child_range children() const {
5777 Stmt *const *cs = const_cast<Stmt *const *>(
5778 reinterpret_cast<const Stmt *const *>(getSubExprsBuffer()));
5779 return const_child_range(cs, cs + getNumSubExprs());
5782 static bool classof(const Stmt *T) {
5783 return T->getStmtClass() == PseudoObjectExprClass;
5786 friend TrailingObjects;
5787 friend class ASTStmtReader;
5790 /// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*,
5791 /// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the
5792 /// similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>,
5793 /// and corresponding __opencl_atomic_* for OpenCL 2.0.
5794 /// All of these instructions take one primary pointer, at least one memory
5795 /// order. The instructions for which getScopeModel returns non-null value
5796 /// take one synch scope.
5797 class AtomicExpr : public Expr {
5800 #define BUILTIN(ID, TYPE, ATTRS)
5801 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) AO ## ID,
5802 #include "clang/Basic/Builtins.def"
5803 // Avoid trailing comma
5808 /// Location of sub-expressions.
5809 /// The location of Scope sub-expression is NumSubExprs - 1, which is
5810 /// not fixed, therefore is not defined in enum.
5811 enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, WEAK, END_EXPR };
5812 Stmt *SubExprs[END_EXPR + 1];
5813 unsigned NumSubExprs;
5814 SourceLocation BuiltinLoc, RParenLoc;
5817 friend class ASTStmtReader;
5819 AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args, QualType t,
5820 AtomicOp op, SourceLocation RP);
5822 /// Determine the number of arguments the specified atomic builtin
5824 static unsigned getNumSubExprs(AtomicOp Op);
5826 /// Build an empty AtomicExpr.
5827 explicit AtomicExpr(EmptyShell Empty) : Expr(AtomicExprClass, Empty) { }
5829 Expr *getPtr() const {
5830 return cast<Expr>(SubExprs[PTR]);
5832 Expr *getOrder() const {
5833 return cast<Expr>(SubExprs[ORDER]);
5835 Expr *getScope() const {
5836 assert(getScopeModel() && "No scope");
5837 return cast<Expr>(SubExprs[NumSubExprs - 1]);
5839 Expr *getVal1() const {
5840 if (Op == AO__c11_atomic_init || Op == AO__opencl_atomic_init)
5841 return cast<Expr>(SubExprs[ORDER]);
5842 assert(NumSubExprs > VAL1);
5843 return cast<Expr>(SubExprs[VAL1]);
5845 Expr *getOrderFail() const {
5846 assert(NumSubExprs > ORDER_FAIL);
5847 return cast<Expr>(SubExprs[ORDER_FAIL]);
5849 Expr *getVal2() const {
5850 if (Op == AO__atomic_exchange)
5851 return cast<Expr>(SubExprs[ORDER_FAIL]);
5852 assert(NumSubExprs > VAL2);
5853 return cast<Expr>(SubExprs[VAL2]);
5855 Expr *getWeak() const {
5856 assert(NumSubExprs > WEAK);
5857 return cast<Expr>(SubExprs[WEAK]);
5859 QualType getValueType() const;
5861 AtomicOp getOp() const { return Op; }
5862 unsigned getNumSubExprs() const { return NumSubExprs; }
5864 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
5865 const Expr * const *getSubExprs() const {
5866 return reinterpret_cast<Expr * const *>(SubExprs);
5869 bool isVolatile() const {
5870 return getPtr()->getType()->getPointeeType().isVolatileQualified();
5873 bool isCmpXChg() const {
5874 return getOp() == AO__c11_atomic_compare_exchange_strong ||
5875 getOp() == AO__c11_atomic_compare_exchange_weak ||
5876 getOp() == AO__opencl_atomic_compare_exchange_strong ||
5877 getOp() == AO__opencl_atomic_compare_exchange_weak ||
5878 getOp() == AO__atomic_compare_exchange ||
5879 getOp() == AO__atomic_compare_exchange_n;
5882 bool isOpenCL() const {
5883 return getOp() >= AO__opencl_atomic_init &&
5884 getOp() <= AO__opencl_atomic_fetch_max;
5887 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
5888 SourceLocation getRParenLoc() const { return RParenLoc; }
5890 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
5891 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
5893 static bool classof(const Stmt *T) {
5894 return T->getStmtClass() == AtomicExprClass;
5898 child_range children() {
5899 return child_range(SubExprs, SubExprs+NumSubExprs);
5901 const_child_range children() const {
5902 return const_child_range(SubExprs, SubExprs + NumSubExprs);
5905 /// Get atomic scope model for the atomic op code.
5906 /// \return empty atomic scope model if the atomic op code does not have
5908 static std::unique_ptr<AtomicScopeModel> getScopeModel(AtomicOp Op) {
5910 (Op >= AO__opencl_atomic_load && Op <= AO__opencl_atomic_fetch_max)
5911 ? AtomicScopeModelKind::OpenCL
5912 : AtomicScopeModelKind::None;
5913 return AtomicScopeModel::create(Kind);
5916 /// Get atomic scope model.
5917 /// \return empty atomic scope model if this atomic expression does not have
5919 std::unique_ptr<AtomicScopeModel> getScopeModel() const {
5920 return getScopeModel(getOp());
5924 /// TypoExpr - Internal placeholder for expressions where typo correction
5925 /// still needs to be performed and/or an error diagnostic emitted.
5926 class TypoExpr : public Expr {
5928 TypoExpr(QualType T)
5929 : Expr(TypoExprClass, T, VK_LValue, OK_Ordinary,
5930 /*isTypeDependent*/ true,
5931 /*isValueDependent*/ true,
5932 /*isInstantiationDependent*/ true,
5933 /*containsUnexpandedParameterPack*/ false) {
5934 assert(T->isDependentType() && "TypoExpr given a non-dependent type");
5937 child_range children() {
5938 return child_range(child_iterator(), child_iterator());
5940 const_child_range children() const {
5941 return const_child_range(const_child_iterator(), const_child_iterator());
5944 SourceLocation getBeginLoc() const LLVM_READONLY { return SourceLocation(); }
5945 SourceLocation getEndLoc() const LLVM_READONLY { return SourceLocation(); }
5947 static bool classof(const Stmt *T) {
5948 return T->getStmtClass() == TypoExprClass;
5952 } // end namespace clang
5954 #endif // LLVM_CLANG_AST_EXPR_H