1 //===--- Expr.h - Classes for representing expressions ----------*- C++ -*-===// 2 // 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 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the Expr interface and subclasses. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #ifndef LLVM_CLANG_AST_EXPR_H 14 #define LLVM_CLANG_AST_EXPR_H 15 16 #include "clang/AST/APValue.h" 17 #include "clang/AST/ASTVector.h" 18 #include "clang/AST/ComputeDependence.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclAccessPair.h" 21 #include "clang/AST/DependenceFlags.h" 22 #include "clang/AST/OperationKinds.h" 23 #include "clang/AST/Stmt.h" 24 #include "clang/AST/TemplateBase.h" 25 #include "clang/AST/Type.h" 26 #include "clang/Basic/CharInfo.h" 27 #include "clang/Basic/LangOptions.h" 28 #include "clang/Basic/SyncScope.h" 29 #include "clang/Basic/TypeTraits.h" 30 #include "llvm/ADT/APFloat.h" 31 #include "llvm/ADT/APSInt.h" 32 #include "llvm/ADT/SmallVector.h" 33 #include "llvm/ADT/StringRef.h" 34 #include "llvm/ADT/iterator.h" 35 #include "llvm/ADT/iterator_range.h" 36 #include "llvm/Support/AtomicOrdering.h" 37 #include "llvm/Support/Compiler.h" 38 #include "llvm/Support/TrailingObjects.h" 39 #include <optional> 40 41 namespace clang { 42 class APValue; 43 class ASTContext; 44 class BlockDecl; 45 class CXXBaseSpecifier; 46 class CXXMemberCallExpr; 47 class CXXOperatorCallExpr; 48 class CastExpr; 49 class Decl; 50 class IdentifierInfo; 51 class MaterializeTemporaryExpr; 52 class NamedDecl; 53 class ObjCPropertyRefExpr; 54 class OpaqueValueExpr; 55 class ParmVarDecl; 56 class StringLiteral; 57 class TargetInfo; 58 class ValueDecl; 59 60 /// A simple array of base specifiers. 61 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath; 62 63 /// An adjustment to be made to the temporary created when emitting a 64 /// reference binding, which accesses a particular subobject of that temporary. 65 struct SubobjectAdjustment { 66 enum { 67 DerivedToBaseAdjustment, 68 FieldAdjustment, 69 MemberPointerAdjustment 70 } Kind; 71 72 struct DTB { 73 const CastExpr *BasePath; 74 const CXXRecordDecl *DerivedClass; 75 }; 76 77 struct P { 78 const MemberPointerType *MPT; 79 Expr *RHS; 80 }; 81 82 union { 83 struct DTB DerivedToBase; 84 FieldDecl *Field; 85 struct P Ptr; 86 }; 87 88 SubobjectAdjustment(const CastExpr *BasePath, 89 const CXXRecordDecl *DerivedClass) 90 : Kind(DerivedToBaseAdjustment) { 91 DerivedToBase.BasePath = BasePath; 92 DerivedToBase.DerivedClass = DerivedClass; 93 } 94 95 SubobjectAdjustment(FieldDecl *Field) 96 : Kind(FieldAdjustment) { 97 this->Field = Field; 98 } 99 100 SubobjectAdjustment(const MemberPointerType *MPT, Expr *RHS) 101 : Kind(MemberPointerAdjustment) { 102 this->Ptr.MPT = MPT; 103 this->Ptr.RHS = RHS; 104 } 105 }; 106 107 /// This represents one expression. Note that Expr's are subclasses of Stmt. 108 /// This allows an expression to be transparently used any place a Stmt is 109 /// required. 110 class Expr : public ValueStmt { 111 QualType TR; 112 113 public: 114 Expr() = delete; 115 Expr(const Expr&) = delete; 116 Expr(Expr &&) = delete; 117 Expr &operator=(const Expr&) = delete; 118 Expr &operator=(Expr&&) = delete; 119 120 protected: 121 Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK) 122 : ValueStmt(SC) { 123 ExprBits.Dependent = 0; 124 ExprBits.ValueKind = VK; 125 ExprBits.ObjectKind = OK; 126 assert(ExprBits.ObjectKind == OK && "truncated kind"); 127 setType(T); 128 } 129 130 /// Construct an empty expression. 131 explicit Expr(StmtClass SC, EmptyShell) : ValueStmt(SC) { } 132 133 /// Each concrete expr subclass is expected to compute its dependence and call 134 /// this in the constructor. 135 void setDependence(ExprDependence Deps) { 136 ExprBits.Dependent = static_cast<unsigned>(Deps); 137 } 138 friend class ASTImporter; // Sets dependence directly. 139 friend class ASTStmtReader; // Sets dependence directly. 140 141 public: 142 QualType getType() const { return TR; } 143 void setType(QualType t) { 144 // In C++, the type of an expression is always adjusted so that it 145 // will not have reference type (C++ [expr]p6). Use 146 // QualType::getNonReferenceType() to retrieve the non-reference 147 // type. Additionally, inspect Expr::isLvalue to determine whether 148 // an expression that is adjusted in this manner should be 149 // considered an lvalue. 150 assert((t.isNull() || !t->isReferenceType()) && 151 "Expressions can't have reference type"); 152 153 TR = t; 154 } 155 156 ExprDependence getDependence() const { 157 return static_cast<ExprDependence>(ExprBits.Dependent); 158 } 159 160 /// Determines whether the value of this expression depends on 161 /// - a template parameter (C++ [temp.dep.constexpr]) 162 /// - or an error, whose resolution is unknown 163 /// 164 /// For example, the array bound of "Chars" in the following example is 165 /// value-dependent. 166 /// @code 167 /// template<int Size, char (&Chars)[Size]> struct meta_string; 168 /// @endcode 169 bool isValueDependent() const { 170 return static_cast<bool>(getDependence() & ExprDependence::Value); 171 } 172 173 /// Determines whether the type of this expression depends on 174 /// - a template parameter (C++ [temp.dep.expr], which means that its type 175 /// could change from one template instantiation to the next) 176 /// - or an error 177 /// 178 /// For example, the expressions "x" and "x + y" are type-dependent in 179 /// the following code, but "y" is not type-dependent: 180 /// @code 181 /// template<typename T> 182 /// void add(T x, int y) { 183 /// x + y; 184 /// } 185 /// @endcode 186 bool isTypeDependent() const { 187 return static_cast<bool>(getDependence() & ExprDependence::Type); 188 } 189 190 /// Whether this expression is instantiation-dependent, meaning that 191 /// it depends in some way on 192 /// - a template parameter (even if neither its type nor (constant) value 193 /// can change due to the template instantiation) 194 /// - or an error 195 /// 196 /// In the following example, the expression \c sizeof(sizeof(T() + T())) is 197 /// instantiation-dependent (since it involves a template parameter \c T), but 198 /// is neither type- nor value-dependent, since the type of the inner 199 /// \c sizeof is known (\c std::size_t) and therefore the size of the outer 200 /// \c sizeof is known. 201 /// 202 /// \code 203 /// template<typename T> 204 /// void f(T x, T y) { 205 /// sizeof(sizeof(T() + T()); 206 /// } 207 /// \endcode 208 /// 209 /// \code 210 /// void func(int) { 211 /// func(); // the expression is instantiation-dependent, because it depends 212 /// // on an error. 213 /// } 214 /// \endcode 215 bool isInstantiationDependent() const { 216 return static_cast<bool>(getDependence() & ExprDependence::Instantiation); 217 } 218 219 /// Whether this expression contains an unexpanded parameter 220 /// pack (for C++11 variadic templates). 221 /// 222 /// Given the following function template: 223 /// 224 /// \code 225 /// template<typename F, typename ...Types> 226 /// void forward(const F &f, Types &&...args) { 227 /// f(static_cast<Types&&>(args)...); 228 /// } 229 /// \endcode 230 /// 231 /// The expressions \c args and \c static_cast<Types&&>(args) both 232 /// contain parameter packs. 233 bool containsUnexpandedParameterPack() const { 234 return static_cast<bool>(getDependence() & ExprDependence::UnexpandedPack); 235 } 236 237 /// Whether this expression contains subexpressions which had errors, e.g. a 238 /// TypoExpr. 239 bool containsErrors() const { 240 return static_cast<bool>(getDependence() & ExprDependence::Error); 241 } 242 243 /// getExprLoc - Return the preferred location for the arrow when diagnosing 244 /// a problem with a generic expression. 245 SourceLocation getExprLoc() const LLVM_READONLY; 246 247 /// Determine whether an lvalue-to-rvalue conversion should implicitly be 248 /// applied to this expression if it appears as a discarded-value expression 249 /// in C++11 onwards. This applies to certain forms of volatile glvalues. 250 bool isReadIfDiscardedInCPlusPlus11() const; 251 252 /// isUnusedResultAWarning - Return true if this immediate expression should 253 /// be warned about if the result is unused. If so, fill in expr, location, 254 /// and ranges with expr to warn on and source locations/ranges appropriate 255 /// for a warning. 256 bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc, 257 SourceRange &R1, SourceRange &R2, 258 ASTContext &Ctx) const; 259 260 /// isLValue - True if this expression is an "l-value" according to 261 /// the rules of the current language. C and C++ give somewhat 262 /// different rules for this concept, but in general, the result of 263 /// an l-value expression identifies a specific object whereas the 264 /// result of an r-value expression is a value detached from any 265 /// specific storage. 266 /// 267 /// C++11 divides the concept of "r-value" into pure r-values 268 /// ("pr-values") and so-called expiring values ("x-values"), which 269 /// identify specific objects that can be safely cannibalized for 270 /// their resources. 271 bool isLValue() const { return getValueKind() == VK_LValue; } 272 bool isPRValue() const { return getValueKind() == VK_PRValue; } 273 bool isXValue() const { return getValueKind() == VK_XValue; } 274 bool isGLValue() const { return getValueKind() != VK_PRValue; } 275 276 enum LValueClassification { 277 LV_Valid, 278 LV_NotObjectType, 279 LV_IncompleteVoidType, 280 LV_DuplicateVectorComponents, 281 LV_InvalidExpression, 282 LV_InvalidMessageExpression, 283 LV_MemberFunction, 284 LV_SubObjCPropertySetting, 285 LV_ClassTemporary, 286 LV_ArrayTemporary 287 }; 288 /// Reasons why an expression might not be an l-value. 289 LValueClassification ClassifyLValue(ASTContext &Ctx) const; 290 291 enum isModifiableLvalueResult { 292 MLV_Valid, 293 MLV_NotObjectType, 294 MLV_IncompleteVoidType, 295 MLV_DuplicateVectorComponents, 296 MLV_InvalidExpression, 297 MLV_LValueCast, // Specialized form of MLV_InvalidExpression. 298 MLV_IncompleteType, 299 MLV_ConstQualified, 300 MLV_ConstQualifiedField, 301 MLV_ConstAddrSpace, 302 MLV_ArrayType, 303 MLV_NoSetterProperty, 304 MLV_MemberFunction, 305 MLV_SubObjCPropertySetting, 306 MLV_InvalidMessageExpression, 307 MLV_ClassTemporary, 308 MLV_ArrayTemporary 309 }; 310 /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type, 311 /// does not have an incomplete type, does not have a const-qualified type, 312 /// and if it is a structure or union, does not have any member (including, 313 /// recursively, any member or element of all contained aggregates or unions) 314 /// with a const-qualified type. 315 /// 316 /// \param Loc [in,out] - A source location which *may* be filled 317 /// in with the location of the expression making this a 318 /// non-modifiable lvalue, if specified. 319 isModifiableLvalueResult 320 isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc = nullptr) const; 321 322 /// The return type of classify(). Represents the C++11 expression 323 /// taxonomy. 324 class Classification { 325 public: 326 /// The various classification results. Most of these mean prvalue. 327 enum Kinds { 328 CL_LValue, 329 CL_XValue, 330 CL_Function, // Functions cannot be lvalues in C. 331 CL_Void, // Void cannot be an lvalue in C. 332 CL_AddressableVoid, // Void expression whose address can be taken in C. 333 CL_DuplicateVectorComponents, // A vector shuffle with dupes. 334 CL_MemberFunction, // An expression referring to a member function 335 CL_SubObjCPropertySetting, 336 CL_ClassTemporary, // A temporary of class type, or subobject thereof. 337 CL_ArrayTemporary, // A temporary of array type. 338 CL_ObjCMessageRValue, // ObjC message is an rvalue 339 CL_PRValue // A prvalue for any other reason, of any other type 340 }; 341 /// The results of modification testing. 342 enum ModifiableType { 343 CM_Untested, // testModifiable was false. 344 CM_Modifiable, 345 CM_RValue, // Not modifiable because it's an rvalue 346 CM_Function, // Not modifiable because it's a function; C++ only 347 CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext 348 CM_NoSetterProperty,// Implicit assignment to ObjC property without setter 349 CM_ConstQualified, 350 CM_ConstQualifiedField, 351 CM_ConstAddrSpace, 352 CM_ArrayType, 353 CM_IncompleteType 354 }; 355 356 private: 357 friend class Expr; 358 359 unsigned short Kind; 360 unsigned short Modifiable; 361 362 explicit Classification(Kinds k, ModifiableType m) 363 : Kind(k), Modifiable(m) 364 {} 365 366 public: 367 Classification() {} 368 369 Kinds getKind() const { return static_cast<Kinds>(Kind); } 370 ModifiableType getModifiable() const { 371 assert(Modifiable != CM_Untested && "Did not test for modifiability."); 372 return static_cast<ModifiableType>(Modifiable); 373 } 374 bool isLValue() const { return Kind == CL_LValue; } 375 bool isXValue() const { return Kind == CL_XValue; } 376 bool isGLValue() const { return Kind <= CL_XValue; } 377 bool isPRValue() const { return Kind >= CL_Function; } 378 bool isRValue() const { return Kind >= CL_XValue; } 379 bool isModifiable() const { return getModifiable() == CM_Modifiable; } 380 381 /// Create a simple, modifiably lvalue 382 static Classification makeSimpleLValue() { 383 return Classification(CL_LValue, CM_Modifiable); 384 } 385 386 }; 387 /// Classify - Classify this expression according to the C++11 388 /// expression taxonomy. 389 /// 390 /// C++11 defines ([basic.lval]) a new taxonomy of expressions to replace the 391 /// old lvalue vs rvalue. This function determines the type of expression this 392 /// is. There are three expression types: 393 /// - lvalues are classical lvalues as in C++03. 394 /// - prvalues are equivalent to rvalues in C++03. 395 /// - xvalues are expressions yielding unnamed rvalue references, e.g. a 396 /// function returning an rvalue reference. 397 /// lvalues and xvalues are collectively referred to as glvalues, while 398 /// prvalues and xvalues together form rvalues. 399 Classification Classify(ASTContext &Ctx) const { 400 return ClassifyImpl(Ctx, nullptr); 401 } 402 403 /// ClassifyModifiable - Classify this expression according to the 404 /// C++11 expression taxonomy, and see if it is valid on the left side 405 /// of an assignment. 406 /// 407 /// This function extends classify in that it also tests whether the 408 /// expression is modifiable (C99 6.3.2.1p1). 409 /// \param Loc A source location that might be filled with a relevant location 410 /// if the expression is not modifiable. 411 Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{ 412 return ClassifyImpl(Ctx, &Loc); 413 } 414 415 /// Returns the set of floating point options that apply to this expression. 416 /// Only meaningful for operations on floating point values. 417 FPOptions getFPFeaturesInEffect(const LangOptions &LO) const; 418 419 /// getValueKindForType - Given a formal return or parameter type, 420 /// give its value kind. 421 static ExprValueKind getValueKindForType(QualType T) { 422 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 423 return (isa<LValueReferenceType>(RT) 424 ? VK_LValue 425 : (RT->getPointeeType()->isFunctionType() 426 ? VK_LValue : VK_XValue)); 427 return VK_PRValue; 428 } 429 430 /// getValueKind - The value kind that this expression produces. 431 ExprValueKind getValueKind() const { 432 return static_cast<ExprValueKind>(ExprBits.ValueKind); 433 } 434 435 /// getObjectKind - The object kind that this expression produces. 436 /// Object kinds are meaningful only for expressions that yield an 437 /// l-value or x-value. 438 ExprObjectKind getObjectKind() const { 439 return static_cast<ExprObjectKind>(ExprBits.ObjectKind); 440 } 441 442 bool isOrdinaryOrBitFieldObject() const { 443 ExprObjectKind OK = getObjectKind(); 444 return (OK == OK_Ordinary || OK == OK_BitField); 445 } 446 447 /// setValueKind - Set the value kind produced by this expression. 448 void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; } 449 450 /// setObjectKind - Set the object kind produced by this expression. 451 void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; } 452 453 private: 454 Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const; 455 456 public: 457 458 /// Returns true if this expression is a gl-value that 459 /// potentially refers to a bit-field. 460 /// 461 /// In C++, whether a gl-value refers to a bitfield is essentially 462 /// an aspect of the value-kind type system. 463 bool refersToBitField() const { return getObjectKind() == OK_BitField; } 464 465 /// If this expression refers to a bit-field, retrieve the 466 /// declaration of that bit-field. 467 /// 468 /// Note that this returns a non-null pointer in subtly different 469 /// places than refersToBitField returns true. In particular, this can 470 /// return a non-null pointer even for r-values loaded from 471 /// bit-fields, but it will return null for a conditional bit-field. 472 FieldDecl *getSourceBitField(); 473 474 const FieldDecl *getSourceBitField() const { 475 return const_cast<Expr*>(this)->getSourceBitField(); 476 } 477 478 Decl *getReferencedDeclOfCallee(); 479 const Decl *getReferencedDeclOfCallee() const { 480 return const_cast<Expr*>(this)->getReferencedDeclOfCallee(); 481 } 482 483 /// If this expression is an l-value for an Objective C 484 /// property, find the underlying property reference expression. 485 const ObjCPropertyRefExpr *getObjCProperty() const; 486 487 /// Check if this expression is the ObjC 'self' implicit parameter. 488 bool isObjCSelfExpr() const; 489 490 /// Returns whether this expression refers to a vector element. 491 bool refersToVectorElement() const; 492 493 /// Returns whether this expression refers to a matrix element. 494 bool refersToMatrixElement() const { 495 return getObjectKind() == OK_MatrixComponent; 496 } 497 498 /// Returns whether this expression refers to a global register 499 /// variable. 500 bool refersToGlobalRegisterVar() const; 501 502 /// Returns whether this expression has a placeholder type. 503 bool hasPlaceholderType() const { 504 return getType()->isPlaceholderType(); 505 } 506 507 /// Returns whether this expression has a specific placeholder type. 508 bool hasPlaceholderType(BuiltinType::Kind K) const { 509 assert(BuiltinType::isPlaceholderTypeKind(K)); 510 if (const BuiltinType *BT = dyn_cast<BuiltinType>(getType())) 511 return BT->getKind() == K; 512 return false; 513 } 514 515 /// isKnownToHaveBooleanValue - Return true if this is an integer expression 516 /// that is known to return 0 or 1. This happens for _Bool/bool expressions 517 /// but also int expressions which are produced by things like comparisons in 518 /// C. 519 /// 520 /// \param Semantic If true, only return true for expressions that are known 521 /// to be semantically boolean, which might not be true even for expressions 522 /// that are known to evaluate to 0/1. For instance, reading an unsigned 523 /// bit-field with width '1' will evaluate to 0/1, but doesn't necessarily 524 /// semantically correspond to a bool. 525 bool isKnownToHaveBooleanValue(bool Semantic = true) const; 526 527 /// Check whether this array fits the idiom of a flexible array member, 528 /// depending on the value of -fstrict-flex-array. 529 /// When IgnoreTemplateOrMacroSubstitution is set, it doesn't consider sizes 530 /// resulting from the substitution of a macro or a template as special sizes. 531 bool isFlexibleArrayMemberLike( 532 ASTContext &Context, 533 LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel, 534 bool IgnoreTemplateOrMacroSubstitution = false) const; 535 536 /// isIntegerConstantExpr - Return the value if this expression is a valid 537 /// integer constant expression. If not a valid i-c-e, return std::nullopt 538 /// and fill in Loc (if specified) with the location of the invalid 539 /// expression. 540 /// 541 /// Note: This does not perform the implicit conversions required by C++11 542 /// [expr.const]p5. 543 std::optional<llvm::APSInt> 544 getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc = nullptr, 545 bool isEvaluated = true) const; 546 bool isIntegerConstantExpr(const ASTContext &Ctx, 547 SourceLocation *Loc = nullptr) const; 548 549 /// isCXX98IntegralConstantExpr - Return true if this expression is an 550 /// integral constant expression in C++98. Can only be used in C++. 551 bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const; 552 553 /// isCXX11ConstantExpr - Return true if this expression is a constant 554 /// expression in C++11. Can only be used in C++. 555 /// 556 /// Note: This does not perform the implicit conversions required by C++11 557 /// [expr.const]p5. 558 bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result = nullptr, 559 SourceLocation *Loc = nullptr) const; 560 561 /// isPotentialConstantExpr - Return true if this function's definition 562 /// might be usable in a constant expression in C++11, if it were marked 563 /// constexpr. Return false if the function can never produce a constant 564 /// expression, along with diagnostics describing why not. 565 static bool isPotentialConstantExpr(const FunctionDecl *FD, 566 SmallVectorImpl< 567 PartialDiagnosticAt> &Diags); 568 569 /// isPotentialConstantExprUnevaluted - Return true if this expression might 570 /// be usable in a constant expression in C++11 in an unevaluated context, if 571 /// it were in function FD marked constexpr. Return false if the function can 572 /// never produce a constant expression, along with diagnostics describing 573 /// why not. 574 static bool isPotentialConstantExprUnevaluated(Expr *E, 575 const FunctionDecl *FD, 576 SmallVectorImpl< 577 PartialDiagnosticAt> &Diags); 578 579 /// isConstantInitializer - Returns true if this expression can be emitted to 580 /// IR as a constant, and thus can be used as a constant initializer in C. 581 /// If this expression is not constant and Culprit is non-null, 582 /// it is used to store the address of first non constant expr. 583 bool isConstantInitializer(ASTContext &Ctx, bool ForRef, 584 const Expr **Culprit = nullptr) const; 585 586 /// If this expression is an unambiguous reference to a single declaration, 587 /// in the style of __builtin_function_start, return that declaration. Note 588 /// that this may return a non-static member function or field in C++ if this 589 /// expression is a member pointer constant. 590 const ValueDecl *getAsBuiltinConstantDeclRef(const ASTContext &Context) const; 591 592 /// EvalStatus is a struct with detailed info about an evaluation in progress. 593 struct EvalStatus { 594 /// Whether the evaluated expression has side effects. 595 /// For example, (f() && 0) can be folded, but it still has side effects. 596 bool HasSideEffects = false; 597 598 /// Whether the evaluation hit undefined behavior. 599 /// For example, 1.0 / 0.0 can be folded to Inf, but has undefined behavior. 600 /// Likewise, INT_MAX + 1 can be folded to INT_MIN, but has UB. 601 bool HasUndefinedBehavior = false; 602 603 /// Diag - If this is non-null, it will be filled in with a stack of notes 604 /// indicating why evaluation failed (or why it failed to produce a constant 605 /// expression). 606 /// If the expression is unfoldable, the notes will indicate why it's not 607 /// foldable. If the expression is foldable, but not a constant expression, 608 /// the notes will describes why it isn't a constant expression. If the 609 /// expression *is* a constant expression, no notes will be produced. 610 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr; 611 612 EvalStatus() = default; 613 614 // hasSideEffects - Return true if the evaluated expression has 615 // side effects. 616 bool hasSideEffects() const { 617 return HasSideEffects; 618 } 619 }; 620 621 /// EvalResult is a struct with detailed info about an evaluated expression. 622 struct EvalResult : EvalStatus { 623 /// Val - This is the value the expression can be folded to. 624 APValue Val; 625 626 // isGlobalLValue - Return true if the evaluated lvalue expression 627 // is global. 628 bool isGlobalLValue() const; 629 }; 630 631 /// EvaluateAsRValue - Return true if this is a constant which we can fold to 632 /// an rvalue using any crazy technique (that has nothing to do with language 633 /// standards) that we want to, even if the expression has side-effects. If 634 /// this function returns true, it returns the folded constant in Result. If 635 /// the expression is a glvalue, an lvalue-to-rvalue conversion will be 636 /// applied. 637 bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 638 bool InConstantContext = false) const; 639 640 /// EvaluateAsBooleanCondition - Return true if this is a constant 641 /// which we can fold and convert to a boolean condition using 642 /// any crazy technique that we want to, even if the expression has 643 /// side-effects. 644 bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, 645 bool InConstantContext = false) const; 646 647 enum SideEffectsKind { 648 SE_NoSideEffects, ///< Strictly evaluate the expression. 649 SE_AllowUndefinedBehavior, ///< Allow UB that we can give a value, but not 650 ///< arbitrary unmodeled side effects. 651 SE_AllowSideEffects ///< Allow any unmodeled side effect. 652 }; 653 654 /// EvaluateAsInt - Return true if this is a constant which we can fold and 655 /// convert to an integer, using any crazy technique that we want to. 656 bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 657 SideEffectsKind AllowSideEffects = SE_NoSideEffects, 658 bool InConstantContext = false) const; 659 660 /// EvaluateAsFloat - Return true if this is a constant which we can fold and 661 /// convert to a floating point value, using any crazy technique that we 662 /// want to. 663 bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx, 664 SideEffectsKind AllowSideEffects = SE_NoSideEffects, 665 bool InConstantContext = false) const; 666 667 /// EvaluateAsFixedPoint - Return true if this is a constant which we can fold 668 /// and convert to a fixed point value. 669 bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, 670 SideEffectsKind AllowSideEffects = SE_NoSideEffects, 671 bool InConstantContext = false) const; 672 673 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 674 /// constant folded without side-effects, but discard the result. 675 bool isEvaluatable(const ASTContext &Ctx, 676 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const; 677 678 /// HasSideEffects - This routine returns true for all those expressions 679 /// which have any effect other than producing a value. Example is a function 680 /// call, volatile variable read, or throwing an exception. If 681 /// IncludePossibleEffects is false, this call treats certain expressions with 682 /// potential side effects (such as function call-like expressions, 683 /// instantiation-dependent expressions, or invocations from a macro) as not 684 /// having side effects. 685 bool HasSideEffects(const ASTContext &Ctx, 686 bool IncludePossibleEffects = true) const; 687 688 /// Determine whether this expression involves a call to any function 689 /// that is not trivial. 690 bool hasNonTrivialCall(const ASTContext &Ctx) const; 691 692 /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded 693 /// integer. This must be called on an expression that constant folds to an 694 /// integer. 695 llvm::APSInt EvaluateKnownConstInt( 696 const ASTContext &Ctx, 697 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const; 698 699 llvm::APSInt EvaluateKnownConstIntCheckOverflow( 700 const ASTContext &Ctx, 701 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const; 702 703 void EvaluateForOverflow(const ASTContext &Ctx) const; 704 705 /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an 706 /// lvalue with link time known address, with no side-effects. 707 bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, 708 bool InConstantContext = false) const; 709 710 /// EvaluateAsInitializer - Evaluate an expression as if it were the 711 /// initializer of the given declaration. Returns true if the initializer 712 /// can be folded to a constant, and produces any relevant notes. In C++11, 713 /// notes will be produced if the expression is not a constant expression. 714 bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx, 715 const VarDecl *VD, 716 SmallVectorImpl<PartialDiagnosticAt> &Notes, 717 bool IsConstantInitializer) const; 718 719 /// EvaluateWithSubstitution - Evaluate an expression as if from the context 720 /// of a call to the given function with the given arguments, inside an 721 /// unevaluated context. Returns true if the expression could be folded to a 722 /// constant. 723 bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 724 const FunctionDecl *Callee, 725 ArrayRef<const Expr*> Args, 726 const Expr *This = nullptr) const; 727 728 enum class ConstantExprKind { 729 /// An integer constant expression (an array bound, enumerator, case value, 730 /// bit-field width, or similar) or similar. 731 Normal, 732 /// A non-class template argument. Such a value is only used for mangling, 733 /// not for code generation, so can refer to dllimported functions. 734 NonClassTemplateArgument, 735 /// A class template argument. Such a value is used for code generation. 736 ClassTemplateArgument, 737 /// An immediate invocation. The destruction of the end result of this 738 /// evaluation is not part of the evaluation, but all other temporaries 739 /// are destroyed. 740 ImmediateInvocation, 741 }; 742 743 /// Evaluate an expression that is required to be a constant expression. Does 744 /// not check the syntactic constraints for C and C++98 constant expressions. 745 bool EvaluateAsConstantExpr( 746 EvalResult &Result, const ASTContext &Ctx, 747 ConstantExprKind Kind = ConstantExprKind::Normal) const; 748 749 /// If the current Expr is a pointer, this will try to statically 750 /// determine the number of bytes available where the pointer is pointing. 751 /// Returns true if all of the above holds and we were able to figure out the 752 /// size, false otherwise. 753 /// 754 /// \param Type - How to evaluate the size of the Expr, as defined by the 755 /// "type" parameter of __builtin_object_size 756 bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 757 unsigned Type) const; 758 759 /// If the current Expr is a pointer, this will try to statically 760 /// determine the strlen of the string pointed to. 761 /// Returns true if all of the above holds and we were able to figure out the 762 /// strlen, false otherwise. 763 bool tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const; 764 765 bool EvaluateCharRangeAsString(std::string &Result, 766 const Expr *SizeExpression, 767 const Expr *PtrExpression, ASTContext &Ctx, 768 EvalResult &Status) const; 769 770 /// Enumeration used to describe the kind of Null pointer constant 771 /// returned from \c isNullPointerConstant(). 772 enum NullPointerConstantKind { 773 /// Expression is not a Null pointer constant. 774 NPCK_NotNull = 0, 775 776 /// Expression is a Null pointer constant built from a zero integer 777 /// expression that is not a simple, possibly parenthesized, zero literal. 778 /// C++ Core Issue 903 will classify these expressions as "not pointers" 779 /// once it is adopted. 780 /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 781 NPCK_ZeroExpression, 782 783 /// Expression is a Null pointer constant built from a literal zero. 784 NPCK_ZeroLiteral, 785 786 /// Expression is a C++11 nullptr. 787 NPCK_CXX11_nullptr, 788 789 /// Expression is a GNU-style __null constant. 790 NPCK_GNUNull 791 }; 792 793 /// Enumeration used to describe how \c isNullPointerConstant() 794 /// should cope with value-dependent expressions. 795 enum NullPointerConstantValueDependence { 796 /// Specifies that the expression should never be value-dependent. 797 NPC_NeverValueDependent = 0, 798 799 /// Specifies that a value-dependent expression of integral or 800 /// dependent type should be considered a null pointer constant. 801 NPC_ValueDependentIsNull, 802 803 /// Specifies that a value-dependent expression should be considered 804 /// to never be a null pointer constant. 805 NPC_ValueDependentIsNotNull 806 }; 807 808 /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to 809 /// a Null pointer constant. The return value can further distinguish the 810 /// kind of NULL pointer constant that was detected. 811 NullPointerConstantKind isNullPointerConstant( 812 ASTContext &Ctx, 813 NullPointerConstantValueDependence NPC) const; 814 815 /// isOBJCGCCandidate - Return true if this expression may be used in a read/ 816 /// write barrier. 817 bool isOBJCGCCandidate(ASTContext &Ctx) const; 818 819 /// Returns true if this expression is a bound member function. 820 bool isBoundMemberFunction(ASTContext &Ctx) const; 821 822 /// Given an expression of bound-member type, find the type 823 /// of the member. Returns null if this is an *overloaded* bound 824 /// member expression. 825 static QualType findBoundMemberType(const Expr *expr); 826 827 /// Skip past any invisible AST nodes which might surround this 828 /// statement, such as ExprWithCleanups or ImplicitCastExpr nodes, 829 /// but also injected CXXMemberExpr and CXXConstructExpr which represent 830 /// implicit conversions. 831 Expr *IgnoreUnlessSpelledInSource(); 832 const Expr *IgnoreUnlessSpelledInSource() const { 833 return const_cast<Expr *>(this)->IgnoreUnlessSpelledInSource(); 834 } 835 836 /// Skip past any implicit casts which might surround this expression until 837 /// reaching a fixed point. Skips: 838 /// * ImplicitCastExpr 839 /// * FullExpr 840 Expr *IgnoreImpCasts() LLVM_READONLY; 841 const Expr *IgnoreImpCasts() const { 842 return const_cast<Expr *>(this)->IgnoreImpCasts(); 843 } 844 845 /// Skip past any casts which might surround this expression until reaching 846 /// a fixed point. Skips: 847 /// * CastExpr 848 /// * FullExpr 849 /// * MaterializeTemporaryExpr 850 /// * SubstNonTypeTemplateParmExpr 851 Expr *IgnoreCasts() LLVM_READONLY; 852 const Expr *IgnoreCasts() const { 853 return const_cast<Expr *>(this)->IgnoreCasts(); 854 } 855 856 /// Skip past any implicit AST nodes which might surround this expression 857 /// until reaching a fixed point. Skips: 858 /// * What IgnoreImpCasts() skips 859 /// * MaterializeTemporaryExpr 860 /// * CXXBindTemporaryExpr 861 Expr *IgnoreImplicit() LLVM_READONLY; 862 const Expr *IgnoreImplicit() const { 863 return const_cast<Expr *>(this)->IgnoreImplicit(); 864 } 865 866 /// Skip past any implicit AST nodes which might surround this expression 867 /// until reaching a fixed point. Same as IgnoreImplicit, except that it 868 /// also skips over implicit calls to constructors and conversion functions. 869 /// 870 /// FIXME: Should IgnoreImplicit do this? 871 Expr *IgnoreImplicitAsWritten() LLVM_READONLY; 872 const Expr *IgnoreImplicitAsWritten() const { 873 return const_cast<Expr *>(this)->IgnoreImplicitAsWritten(); 874 } 875 876 /// Skip past any parentheses which might surround this expression until 877 /// reaching a fixed point. Skips: 878 /// * ParenExpr 879 /// * UnaryOperator if `UO_Extension` 880 /// * GenericSelectionExpr if `!isResultDependent()` 881 /// * ChooseExpr if `!isConditionDependent()` 882 /// * ConstantExpr 883 Expr *IgnoreParens() LLVM_READONLY; 884 const Expr *IgnoreParens() const { 885 return const_cast<Expr *>(this)->IgnoreParens(); 886 } 887 888 /// Skip past any parentheses and implicit casts which might surround this 889 /// expression until reaching a fixed point. 890 /// FIXME: IgnoreParenImpCasts really ought to be equivalent to 891 /// IgnoreParens() + IgnoreImpCasts() until reaching a fixed point. However 892 /// this is currently not the case. Instead IgnoreParenImpCasts() skips: 893 /// * What IgnoreParens() skips 894 /// * What IgnoreImpCasts() skips 895 /// * MaterializeTemporaryExpr 896 /// * SubstNonTypeTemplateParmExpr 897 Expr *IgnoreParenImpCasts() LLVM_READONLY; 898 const Expr *IgnoreParenImpCasts() const { 899 return const_cast<Expr *>(this)->IgnoreParenImpCasts(); 900 } 901 902 /// Skip past any parentheses and casts which might surround this expression 903 /// until reaching a fixed point. Skips: 904 /// * What IgnoreParens() skips 905 /// * What IgnoreCasts() skips 906 Expr *IgnoreParenCasts() LLVM_READONLY; 907 const Expr *IgnoreParenCasts() const { 908 return const_cast<Expr *>(this)->IgnoreParenCasts(); 909 } 910 911 /// Skip conversion operators. If this Expr is a call to a conversion 912 /// operator, return the argument. 913 Expr *IgnoreConversionOperatorSingleStep() LLVM_READONLY; 914 const Expr *IgnoreConversionOperatorSingleStep() const { 915 return const_cast<Expr *>(this)->IgnoreConversionOperatorSingleStep(); 916 } 917 918 /// Skip past any parentheses and lvalue casts which might surround this 919 /// expression until reaching a fixed point. Skips: 920 /// * What IgnoreParens() skips 921 /// * What IgnoreCasts() skips, except that only lvalue-to-rvalue 922 /// casts are skipped 923 /// FIXME: This is intended purely as a temporary workaround for code 924 /// that hasn't yet been rewritten to do the right thing about those 925 /// casts, and may disappear along with the last internal use. 926 Expr *IgnoreParenLValueCasts() LLVM_READONLY; 927 const Expr *IgnoreParenLValueCasts() const { 928 return const_cast<Expr *>(this)->IgnoreParenLValueCasts(); 929 } 930 931 /// Skip past any parentheses and casts which do not change the value 932 /// (including ptr->int casts of the same size) until reaching a fixed point. 933 /// Skips: 934 /// * What IgnoreParens() skips 935 /// * CastExpr which do not change the value 936 /// * SubstNonTypeTemplateParmExpr 937 Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY; 938 const Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) const { 939 return const_cast<Expr *>(this)->IgnoreParenNoopCasts(Ctx); 940 } 941 942 /// Skip past any parentheses and derived-to-base casts until reaching a 943 /// fixed point. Skips: 944 /// * What IgnoreParens() skips 945 /// * CastExpr which represent a derived-to-base cast (CK_DerivedToBase, 946 /// CK_UncheckedDerivedToBase and CK_NoOp) 947 Expr *IgnoreParenBaseCasts() LLVM_READONLY; 948 const Expr *IgnoreParenBaseCasts() const { 949 return const_cast<Expr *>(this)->IgnoreParenBaseCasts(); 950 } 951 952 /// Determine whether this expression is a default function argument. 953 /// 954 /// Default arguments are implicitly generated in the abstract syntax tree 955 /// by semantic analysis for function calls, object constructions, etc. in 956 /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes; 957 /// this routine also looks through any implicit casts to determine whether 958 /// the expression is a default argument. 959 bool isDefaultArgument() const; 960 961 /// Determine whether the result of this expression is a 962 /// temporary object of the given class type. 963 bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const; 964 965 /// Whether this expression is an implicit reference to 'this' in C++. 966 bool isImplicitCXXThis() const; 967 968 static bool hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs); 969 970 /// For an expression of class type or pointer to class type, 971 /// return the most derived class decl the expression is known to refer to. 972 /// 973 /// If this expression is a cast, this method looks through it to find the 974 /// most derived decl that can be inferred from the expression. 975 /// This is valid because derived-to-base conversions have undefined 976 /// behavior if the object isn't dynamically of the derived type. 977 const CXXRecordDecl *getBestDynamicClassType() const; 978 979 /// Get the inner expression that determines the best dynamic class. 980 /// If this is a prvalue, we guarantee that it is of the most-derived type 981 /// for the object itself. 982 const Expr *getBestDynamicClassTypeExpr() const; 983 984 /// Walk outwards from an expression we want to bind a reference to and 985 /// find the expression whose lifetime needs to be extended. Record 986 /// the LHSs of comma expressions and adjustments needed along the path. 987 const Expr *skipRValueSubobjectAdjustments( 988 SmallVectorImpl<const Expr *> &CommaLHS, 989 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const; 990 const Expr *skipRValueSubobjectAdjustments() const { 991 SmallVector<const Expr *, 8> CommaLHSs; 992 SmallVector<SubobjectAdjustment, 8> Adjustments; 993 return skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 994 } 995 996 /// Checks that the two Expr's will refer to the same value as a comparison 997 /// operand. The caller must ensure that the values referenced by the Expr's 998 /// are not modified between E1 and E2 or the result my be invalid. 999 static bool isSameComparisonOperand(const Expr* E1, const Expr* E2); 1000 1001 static bool classof(const Stmt *T) { 1002 return T->getStmtClass() >= firstExprConstant && 1003 T->getStmtClass() <= lastExprConstant; 1004 } 1005 }; 1006 // PointerLikeTypeTraits is specialized so it can be used with a forward-decl of 1007 // Expr. Verify that we got it right. 1008 static_assert(llvm::PointerLikeTypeTraits<Expr *>::NumLowBitsAvailable <= 1009 llvm::detail::ConstantLog2<alignof(Expr)>::value, 1010 "PointerLikeTypeTraits<Expr*> assumes too much alignment."); 1011 1012 using ConstantExprKind = Expr::ConstantExprKind; 1013 1014 //===----------------------------------------------------------------------===// 1015 // Wrapper Expressions. 1016 //===----------------------------------------------------------------------===// 1017 1018 /// FullExpr - Represents a "full-expression" node. 1019 class FullExpr : public Expr { 1020 protected: 1021 Stmt *SubExpr; 1022 1023 FullExpr(StmtClass SC, Expr *subexpr) 1024 : Expr(SC, subexpr->getType(), subexpr->getValueKind(), 1025 subexpr->getObjectKind()), 1026 SubExpr(subexpr) { 1027 setDependence(computeDependence(this)); 1028 } 1029 FullExpr(StmtClass SC, EmptyShell Empty) 1030 : Expr(SC, Empty) {} 1031 public: 1032 const Expr *getSubExpr() const { return cast<Expr>(SubExpr); } 1033 Expr *getSubExpr() { return cast<Expr>(SubExpr); } 1034 1035 /// As with any mutator of the AST, be very careful when modifying an 1036 /// existing AST to preserve its invariants. 1037 void setSubExpr(Expr *E) { SubExpr = E; } 1038 1039 static bool classof(const Stmt *T) { 1040 return T->getStmtClass() >= firstFullExprConstant && 1041 T->getStmtClass() <= lastFullExprConstant; 1042 } 1043 }; 1044 1045 /// ConstantExpr - An expression that occurs in a constant context and 1046 /// optionally the result of evaluating the expression. 1047 class ConstantExpr final 1048 : public FullExpr, 1049 private llvm::TrailingObjects<ConstantExpr, APValue, uint64_t> { 1050 static_assert(std::is_same<uint64_t, llvm::APInt::WordType>::value, 1051 "ConstantExpr assumes that llvm::APInt::WordType is uint64_t " 1052 "for tail-allocated storage"); 1053 friend TrailingObjects; 1054 friend class ASTStmtReader; 1055 friend class ASTStmtWriter; 1056 1057 public: 1058 /// Describes the kind of result that can be tail-allocated. 1059 enum ResultStorageKind { RSK_None, RSK_Int64, RSK_APValue }; 1060 1061 private: 1062 size_t numTrailingObjects(OverloadToken<APValue>) const { 1063 return ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue; 1064 } 1065 size_t numTrailingObjects(OverloadToken<uint64_t>) const { 1066 return ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64; 1067 } 1068 1069 uint64_t &Int64Result() { 1070 assert(ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64 && 1071 "invalid accessor"); 1072 return *getTrailingObjects<uint64_t>(); 1073 } 1074 const uint64_t &Int64Result() const { 1075 return const_cast<ConstantExpr *>(this)->Int64Result(); 1076 } 1077 APValue &APValueResult() { 1078 assert(ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue && 1079 "invalid accessor"); 1080 return *getTrailingObjects<APValue>(); 1081 } 1082 APValue &APValueResult() const { 1083 return const_cast<ConstantExpr *>(this)->APValueResult(); 1084 } 1085 1086 ConstantExpr(Expr *SubExpr, ResultStorageKind StorageKind, 1087 bool IsImmediateInvocation); 1088 ConstantExpr(EmptyShell Empty, ResultStorageKind StorageKind); 1089 1090 public: 1091 static ConstantExpr *Create(const ASTContext &Context, Expr *E, 1092 const APValue &Result); 1093 static ConstantExpr *Create(const ASTContext &Context, Expr *E, 1094 ResultStorageKind Storage = RSK_None, 1095 bool IsImmediateInvocation = false); 1096 static ConstantExpr *CreateEmpty(const ASTContext &Context, 1097 ResultStorageKind StorageKind); 1098 1099 static ResultStorageKind getStorageKind(const APValue &Value); 1100 static ResultStorageKind getStorageKind(const Type *T, 1101 const ASTContext &Context); 1102 1103 SourceLocation getBeginLoc() const LLVM_READONLY { 1104 return SubExpr->getBeginLoc(); 1105 } 1106 SourceLocation getEndLoc() const LLVM_READONLY { 1107 return SubExpr->getEndLoc(); 1108 } 1109 1110 static bool classof(const Stmt *T) { 1111 return T->getStmtClass() == ConstantExprClass; 1112 } 1113 1114 void SetResult(APValue Value, const ASTContext &Context) { 1115 MoveIntoResult(Value, Context); 1116 } 1117 void MoveIntoResult(APValue &Value, const ASTContext &Context); 1118 1119 APValue::ValueKind getResultAPValueKind() const { 1120 return static_cast<APValue::ValueKind>(ConstantExprBits.APValueKind); 1121 } 1122 ResultStorageKind getResultStorageKind() const { 1123 return static_cast<ResultStorageKind>(ConstantExprBits.ResultKind); 1124 } 1125 bool isImmediateInvocation() const { 1126 return ConstantExprBits.IsImmediateInvocation; 1127 } 1128 bool hasAPValueResult() const { 1129 return ConstantExprBits.APValueKind != APValue::None; 1130 } 1131 APValue getAPValueResult() const; 1132 APValue &getResultAsAPValue() const { return APValueResult(); } 1133 llvm::APSInt getResultAsAPSInt() const; 1134 // Iterators 1135 child_range children() { return child_range(&SubExpr, &SubExpr+1); } 1136 const_child_range children() const { 1137 return const_child_range(&SubExpr, &SubExpr + 1); 1138 } 1139 }; 1140 1141 //===----------------------------------------------------------------------===// 1142 // Primary Expressions. 1143 //===----------------------------------------------------------------------===// 1144 1145 /// OpaqueValueExpr - An expression referring to an opaque object of a 1146 /// fixed type and value class. These don't correspond to concrete 1147 /// syntax; instead they're used to express operations (usually copy 1148 /// operations) on values whose source is generally obvious from 1149 /// context. 1150 class OpaqueValueExpr : public Expr { 1151 friend class ASTStmtReader; 1152 Expr *SourceExpr; 1153 1154 public: 1155 OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK, 1156 ExprObjectKind OK = OK_Ordinary, Expr *SourceExpr = nullptr) 1157 : Expr(OpaqueValueExprClass, T, VK, OK), SourceExpr(SourceExpr) { 1158 setIsUnique(false); 1159 OpaqueValueExprBits.Loc = Loc; 1160 setDependence(computeDependence(this)); 1161 } 1162 1163 /// Given an expression which invokes a copy constructor --- i.e. a 1164 /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups --- 1165 /// find the OpaqueValueExpr that's the source of the construction. 1166 static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr); 1167 1168 explicit OpaqueValueExpr(EmptyShell Empty) 1169 : Expr(OpaqueValueExprClass, Empty) {} 1170 1171 /// Retrieve the location of this expression. 1172 SourceLocation getLocation() const { return OpaqueValueExprBits.Loc; } 1173 1174 SourceLocation getBeginLoc() const LLVM_READONLY { 1175 return SourceExpr ? SourceExpr->getBeginLoc() : getLocation(); 1176 } 1177 SourceLocation getEndLoc() const LLVM_READONLY { 1178 return SourceExpr ? SourceExpr->getEndLoc() : getLocation(); 1179 } 1180 SourceLocation getExprLoc() const LLVM_READONLY { 1181 return SourceExpr ? SourceExpr->getExprLoc() : getLocation(); 1182 } 1183 1184 child_range children() { 1185 return child_range(child_iterator(), child_iterator()); 1186 } 1187 1188 const_child_range children() const { 1189 return const_child_range(const_child_iterator(), const_child_iterator()); 1190 } 1191 1192 /// The source expression of an opaque value expression is the 1193 /// expression which originally generated the value. This is 1194 /// provided as a convenience for analyses that don't wish to 1195 /// precisely model the execution behavior of the program. 1196 /// 1197 /// The source expression is typically set when building the 1198 /// expression which binds the opaque value expression in the first 1199 /// place. 1200 Expr *getSourceExpr() const { return SourceExpr; } 1201 1202 void setIsUnique(bool V) { 1203 assert((!V || SourceExpr) && 1204 "unique OVEs are expected to have source expressions"); 1205 OpaqueValueExprBits.IsUnique = V; 1206 } 1207 1208 bool isUnique() const { return OpaqueValueExprBits.IsUnique; } 1209 1210 static bool classof(const Stmt *T) { 1211 return T->getStmtClass() == OpaqueValueExprClass; 1212 } 1213 }; 1214 1215 /// A reference to a declared variable, function, enum, etc. 1216 /// [C99 6.5.1p2] 1217 /// 1218 /// This encodes all the information about how a declaration is referenced 1219 /// within an expression. 1220 /// 1221 /// There are several optional constructs attached to DeclRefExprs only when 1222 /// they apply in order to conserve memory. These are laid out past the end of 1223 /// the object, and flags in the DeclRefExprBitfield track whether they exist: 1224 /// 1225 /// DeclRefExprBits.HasQualifier: 1226 /// Specifies when this declaration reference expression has a C++ 1227 /// nested-name-specifier. 1228 /// DeclRefExprBits.HasFoundDecl: 1229 /// Specifies when this declaration reference expression has a record of 1230 /// a NamedDecl (different from the referenced ValueDecl) which was found 1231 /// during name lookup and/or overload resolution. 1232 /// DeclRefExprBits.HasTemplateKWAndArgsInfo: 1233 /// Specifies when this declaration reference expression has an explicit 1234 /// C++ template keyword and/or template argument list. 1235 /// DeclRefExprBits.RefersToEnclosingVariableOrCapture 1236 /// Specifies when this declaration reference expression (validly) 1237 /// refers to an enclosed local or a captured variable. 1238 class DeclRefExpr final 1239 : public Expr, 1240 private llvm::TrailingObjects<DeclRefExpr, NestedNameSpecifierLoc, 1241 NamedDecl *, ASTTemplateKWAndArgsInfo, 1242 TemplateArgumentLoc> { 1243 friend class ASTStmtReader; 1244 friend class ASTStmtWriter; 1245 friend TrailingObjects; 1246 1247 /// The declaration that we are referencing. 1248 ValueDecl *D; 1249 1250 /// Provides source/type location info for the declaration name 1251 /// embedded in D. 1252 DeclarationNameLoc DNLoc; 1253 1254 size_t numTrailingObjects(OverloadToken<NestedNameSpecifierLoc>) const { 1255 return hasQualifier(); 1256 } 1257 1258 size_t numTrailingObjects(OverloadToken<NamedDecl *>) const { 1259 return hasFoundDecl(); 1260 } 1261 1262 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const { 1263 return hasTemplateKWAndArgsInfo(); 1264 } 1265 1266 /// Test whether there is a distinct FoundDecl attached to the end of 1267 /// this DRE. 1268 bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; } 1269 1270 DeclRefExpr(const ASTContext &Ctx, NestedNameSpecifierLoc QualifierLoc, 1271 SourceLocation TemplateKWLoc, ValueDecl *D, 1272 bool RefersToEnlosingVariableOrCapture, 1273 const DeclarationNameInfo &NameInfo, NamedDecl *FoundD, 1274 const TemplateArgumentListInfo *TemplateArgs, QualType T, 1275 ExprValueKind VK, NonOdrUseReason NOUR); 1276 1277 /// Construct an empty declaration reference expression. 1278 explicit DeclRefExpr(EmptyShell Empty) : Expr(DeclRefExprClass, Empty) {} 1279 1280 public: 1281 DeclRefExpr(const ASTContext &Ctx, ValueDecl *D, 1282 bool RefersToEnclosingVariableOrCapture, QualType T, 1283 ExprValueKind VK, SourceLocation L, 1284 const DeclarationNameLoc &LocInfo = DeclarationNameLoc(), 1285 NonOdrUseReason NOUR = NOUR_None); 1286 1287 static DeclRefExpr * 1288 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, 1289 SourceLocation TemplateKWLoc, ValueDecl *D, 1290 bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, 1291 QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr, 1292 const TemplateArgumentListInfo *TemplateArgs = nullptr, 1293 NonOdrUseReason NOUR = NOUR_None); 1294 1295 static DeclRefExpr * 1296 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, 1297 SourceLocation TemplateKWLoc, ValueDecl *D, 1298 bool RefersToEnclosingVariableOrCapture, 1299 const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK, 1300 NamedDecl *FoundD = nullptr, 1301 const TemplateArgumentListInfo *TemplateArgs = nullptr, 1302 NonOdrUseReason NOUR = NOUR_None); 1303 1304 /// Construct an empty declaration reference expression. 1305 static DeclRefExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier, 1306 bool HasFoundDecl, 1307 bool HasTemplateKWAndArgsInfo, 1308 unsigned NumTemplateArgs); 1309 1310 ValueDecl *getDecl() { return D; } 1311 const ValueDecl *getDecl() const { return D; } 1312 void setDecl(ValueDecl *NewD); 1313 1314 DeclarationNameInfo getNameInfo() const { 1315 return DeclarationNameInfo(getDecl()->getDeclName(), getLocation(), DNLoc); 1316 } 1317 1318 SourceLocation getLocation() const { return DeclRefExprBits.Loc; } 1319 void setLocation(SourceLocation L) { DeclRefExprBits.Loc = L; } 1320 SourceLocation getBeginLoc() const LLVM_READONLY; 1321 SourceLocation getEndLoc() const LLVM_READONLY; 1322 1323 /// Determine whether this declaration reference was preceded by a 1324 /// C++ nested-name-specifier, e.g., \c N::foo. 1325 bool hasQualifier() const { return DeclRefExprBits.HasQualifier; } 1326 1327 /// If the name was qualified, retrieves the nested-name-specifier 1328 /// that precedes the name, with source-location information. 1329 NestedNameSpecifierLoc getQualifierLoc() const { 1330 if (!hasQualifier()) 1331 return NestedNameSpecifierLoc(); 1332 return *getTrailingObjects<NestedNameSpecifierLoc>(); 1333 } 1334 1335 /// If the name was qualified, retrieves the nested-name-specifier 1336 /// that precedes the name. Otherwise, returns NULL. 1337 NestedNameSpecifier *getQualifier() const { 1338 return getQualifierLoc().getNestedNameSpecifier(); 1339 } 1340 1341 /// Get the NamedDecl through which this reference occurred. 1342 /// 1343 /// This Decl may be different from the ValueDecl actually referred to in the 1344 /// presence of using declarations, etc. It always returns non-NULL, and may 1345 /// simple return the ValueDecl when appropriate. 1346 1347 NamedDecl *getFoundDecl() { 1348 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D; 1349 } 1350 1351 /// Get the NamedDecl through which this reference occurred. 1352 /// See non-const variant. 1353 const NamedDecl *getFoundDecl() const { 1354 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D; 1355 } 1356 1357 bool hasTemplateKWAndArgsInfo() const { 1358 return DeclRefExprBits.HasTemplateKWAndArgsInfo; 1359 } 1360 1361 /// Retrieve the location of the template keyword preceding 1362 /// this name, if any. 1363 SourceLocation getTemplateKeywordLoc() const { 1364 if (!hasTemplateKWAndArgsInfo()) 1365 return SourceLocation(); 1366 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc; 1367 } 1368 1369 /// Retrieve the location of the left angle bracket starting the 1370 /// explicit template argument list following the name, if any. 1371 SourceLocation getLAngleLoc() const { 1372 if (!hasTemplateKWAndArgsInfo()) 1373 return SourceLocation(); 1374 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc; 1375 } 1376 1377 /// Retrieve the location of the right angle bracket ending the 1378 /// explicit template argument list following the name, if any. 1379 SourceLocation getRAngleLoc() const { 1380 if (!hasTemplateKWAndArgsInfo()) 1381 return SourceLocation(); 1382 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc; 1383 } 1384 1385 /// Determines whether the name in this declaration reference 1386 /// was preceded by the template keyword. 1387 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); } 1388 1389 /// Determines whether this declaration reference was followed by an 1390 /// explicit template argument list. 1391 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); } 1392 1393 /// Copies the template arguments (if present) into the given 1394 /// structure. 1395 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const { 1396 if (hasExplicitTemplateArgs()) 1397 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto( 1398 getTrailingObjects<TemplateArgumentLoc>(), List); 1399 } 1400 1401 /// Retrieve the template arguments provided as part of this 1402 /// template-id. 1403 const TemplateArgumentLoc *getTemplateArgs() const { 1404 if (!hasExplicitTemplateArgs()) 1405 return nullptr; 1406 return getTrailingObjects<TemplateArgumentLoc>(); 1407 } 1408 1409 /// Retrieve the number of template arguments provided as part of this 1410 /// template-id. 1411 unsigned getNumTemplateArgs() const { 1412 if (!hasExplicitTemplateArgs()) 1413 return 0; 1414 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs; 1415 } 1416 1417 ArrayRef<TemplateArgumentLoc> template_arguments() const { 1418 return {getTemplateArgs(), getNumTemplateArgs()}; 1419 } 1420 1421 /// Returns true if this expression refers to a function that 1422 /// was resolved from an overloaded set having size greater than 1. 1423 bool hadMultipleCandidates() const { 1424 return DeclRefExprBits.HadMultipleCandidates; 1425 } 1426 /// Sets the flag telling whether this expression refers to 1427 /// a function that was resolved from an overloaded set having size 1428 /// greater than 1. 1429 void setHadMultipleCandidates(bool V = true) { 1430 DeclRefExprBits.HadMultipleCandidates = V; 1431 } 1432 1433 /// Is this expression a non-odr-use reference, and if so, why? 1434 NonOdrUseReason isNonOdrUse() const { 1435 return static_cast<NonOdrUseReason>(DeclRefExprBits.NonOdrUseReason); 1436 } 1437 1438 /// Does this DeclRefExpr refer to an enclosing local or a captured 1439 /// variable? 1440 bool refersToEnclosingVariableOrCapture() const { 1441 return DeclRefExprBits.RefersToEnclosingVariableOrCapture; 1442 } 1443 1444 bool isImmediateEscalating() const { 1445 return DeclRefExprBits.IsImmediateEscalating; 1446 } 1447 1448 void setIsImmediateEscalating(bool Set) { 1449 DeclRefExprBits.IsImmediateEscalating = Set; 1450 } 1451 1452 static bool classof(const Stmt *T) { 1453 return T->getStmtClass() == DeclRefExprClass; 1454 } 1455 1456 // Iterators 1457 child_range children() { 1458 return child_range(child_iterator(), child_iterator()); 1459 } 1460 1461 const_child_range children() const { 1462 return const_child_range(const_child_iterator(), const_child_iterator()); 1463 } 1464 }; 1465 1466 /// Used by IntegerLiteral/FloatingLiteral to store the numeric without 1467 /// leaking memory. 1468 /// 1469 /// For large floats/integers, APFloat/APInt will allocate memory from the heap 1470 /// to represent these numbers. Unfortunately, when we use a BumpPtrAllocator 1471 /// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with 1472 /// the APFloat/APInt values will never get freed. APNumericStorage uses 1473 /// ASTContext's allocator for memory allocation. 1474 class APNumericStorage { 1475 union { 1476 uint64_t VAL; ///< Used to store the <= 64 bits integer value. 1477 uint64_t *pVal; ///< Used to store the >64 bits integer value. 1478 }; 1479 unsigned BitWidth; 1480 1481 bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; } 1482 1483 APNumericStorage(const APNumericStorage &) = delete; 1484 void operator=(const APNumericStorage &) = delete; 1485 1486 protected: 1487 APNumericStorage() : VAL(0), BitWidth(0) { } 1488 1489 llvm::APInt getIntValue() const { 1490 unsigned NumWords = llvm::APInt::getNumWords(BitWidth); 1491 if (NumWords > 1) 1492 return llvm::APInt(BitWidth, NumWords, pVal); 1493 else 1494 return llvm::APInt(BitWidth, VAL); 1495 } 1496 void setIntValue(const ASTContext &C, const llvm::APInt &Val); 1497 }; 1498 1499 class APIntStorage : private APNumericStorage { 1500 public: 1501 llvm::APInt getValue() const { return getIntValue(); } 1502 void setValue(const ASTContext &C, const llvm::APInt &Val) { 1503 setIntValue(C, Val); 1504 } 1505 }; 1506 1507 class APFloatStorage : private APNumericStorage { 1508 public: 1509 llvm::APFloat getValue(const llvm::fltSemantics &Semantics) const { 1510 return llvm::APFloat(Semantics, getIntValue()); 1511 } 1512 void setValue(const ASTContext &C, const llvm::APFloat &Val) { 1513 setIntValue(C, Val.bitcastToAPInt()); 1514 } 1515 }; 1516 1517 class IntegerLiteral : public Expr, public APIntStorage { 1518 SourceLocation Loc; 1519 1520 /// Construct an empty integer literal. 1521 explicit IntegerLiteral(EmptyShell Empty) 1522 : Expr(IntegerLiteralClass, Empty) { } 1523 1524 public: 1525 // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy, 1526 // or UnsignedLongLongTy 1527 IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type, 1528 SourceLocation l); 1529 1530 /// Returns a new integer literal with value 'V' and type 'type'. 1531 /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy, 1532 /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V 1533 /// \param V - the value that the returned integer literal contains. 1534 static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V, 1535 QualType type, SourceLocation l); 1536 /// Returns a new empty integer literal. 1537 static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty); 1538 1539 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; } 1540 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; } 1541 1542 /// Retrieve the location of the literal. 1543 SourceLocation getLocation() const { return Loc; } 1544 1545 void setLocation(SourceLocation Location) { Loc = Location; } 1546 1547 static bool classof(const Stmt *T) { 1548 return T->getStmtClass() == IntegerLiteralClass; 1549 } 1550 1551 // Iterators 1552 child_range children() { 1553 return child_range(child_iterator(), child_iterator()); 1554 } 1555 const_child_range children() const { 1556 return const_child_range(const_child_iterator(), const_child_iterator()); 1557 } 1558 }; 1559 1560 class FixedPointLiteral : public Expr, public APIntStorage { 1561 SourceLocation Loc; 1562 unsigned Scale; 1563 1564 /// \brief Construct an empty fixed-point literal. 1565 explicit FixedPointLiteral(EmptyShell Empty) 1566 : Expr(FixedPointLiteralClass, Empty) {} 1567 1568 public: 1569 FixedPointLiteral(const ASTContext &C, const llvm::APInt &V, QualType type, 1570 SourceLocation l, unsigned Scale); 1571 1572 // Store the int as is without any bit shifting. 1573 static FixedPointLiteral *CreateFromRawInt(const ASTContext &C, 1574 const llvm::APInt &V, 1575 QualType type, SourceLocation l, 1576 unsigned Scale); 1577 1578 /// Returns an empty fixed-point literal. 1579 static FixedPointLiteral *Create(const ASTContext &C, EmptyShell Empty); 1580 1581 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; } 1582 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; } 1583 1584 /// \brief Retrieve the location of the literal. 1585 SourceLocation getLocation() const { return Loc; } 1586 1587 void setLocation(SourceLocation Location) { Loc = Location; } 1588 1589 unsigned getScale() const { return Scale; } 1590 void setScale(unsigned S) { Scale = S; } 1591 1592 static bool classof(const Stmt *T) { 1593 return T->getStmtClass() == FixedPointLiteralClass; 1594 } 1595 1596 std::string getValueAsString(unsigned Radix) const; 1597 1598 // Iterators 1599 child_range children() { 1600 return child_range(child_iterator(), child_iterator()); 1601 } 1602 const_child_range children() const { 1603 return const_child_range(const_child_iterator(), const_child_iterator()); 1604 } 1605 }; 1606 1607 class CharacterLiteral : public Expr { 1608 public: 1609 enum CharacterKind { 1610 Ascii, 1611 Wide, 1612 UTF8, 1613 UTF16, 1614 UTF32 1615 }; 1616 1617 private: 1618 unsigned Value; 1619 SourceLocation Loc; 1620 public: 1621 // type should be IntTy 1622 CharacterLiteral(unsigned value, CharacterKind kind, QualType type, 1623 SourceLocation l) 1624 : Expr(CharacterLiteralClass, type, VK_PRValue, OK_Ordinary), 1625 Value(value), Loc(l) { 1626 CharacterLiteralBits.Kind = kind; 1627 setDependence(ExprDependence::None); 1628 } 1629 1630 /// Construct an empty character literal. 1631 CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { } 1632 1633 SourceLocation getLocation() const { return Loc; } 1634 CharacterKind getKind() const { 1635 return static_cast<CharacterKind>(CharacterLiteralBits.Kind); 1636 } 1637 1638 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; } 1639 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; } 1640 1641 unsigned getValue() const { return Value; } 1642 1643 void setLocation(SourceLocation Location) { Loc = Location; } 1644 void setKind(CharacterKind kind) { CharacterLiteralBits.Kind = kind; } 1645 void setValue(unsigned Val) { Value = Val; } 1646 1647 static bool classof(const Stmt *T) { 1648 return T->getStmtClass() == CharacterLiteralClass; 1649 } 1650 1651 static void print(unsigned val, CharacterKind Kind, raw_ostream &OS); 1652 1653 // Iterators 1654 child_range children() { 1655 return child_range(child_iterator(), child_iterator()); 1656 } 1657 const_child_range children() const { 1658 return const_child_range(const_child_iterator(), const_child_iterator()); 1659 } 1660 }; 1661 1662 class FloatingLiteral : public Expr, private APFloatStorage { 1663 SourceLocation Loc; 1664 1665 FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact, 1666 QualType Type, SourceLocation L); 1667 1668 /// Construct an empty floating-point literal. 1669 explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty); 1670 1671 public: 1672 static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V, 1673 bool isexact, QualType Type, SourceLocation L); 1674 static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty); 1675 1676 llvm::APFloat getValue() const { 1677 return APFloatStorage::getValue(getSemantics()); 1678 } 1679 void setValue(const ASTContext &C, const llvm::APFloat &Val) { 1680 assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics"); 1681 APFloatStorage::setValue(C, Val); 1682 } 1683 1684 /// Get a raw enumeration value representing the floating-point semantics of 1685 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation. 1686 llvm::APFloatBase::Semantics getRawSemantics() const { 1687 return static_cast<llvm::APFloatBase::Semantics>( 1688 FloatingLiteralBits.Semantics); 1689 } 1690 1691 /// Set the raw enumeration value representing the floating-point semantics of 1692 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation. 1693 void setRawSemantics(llvm::APFloatBase::Semantics Sem) { 1694 FloatingLiteralBits.Semantics = Sem; 1695 } 1696 1697 /// Return the APFloat semantics this literal uses. 1698 const llvm::fltSemantics &getSemantics() const { 1699 return llvm::APFloatBase::EnumToSemantics( 1700 static_cast<llvm::APFloatBase::Semantics>( 1701 FloatingLiteralBits.Semantics)); 1702 } 1703 1704 /// Set the APFloat semantics this literal uses. 1705 void setSemantics(const llvm::fltSemantics &Sem) { 1706 FloatingLiteralBits.Semantics = llvm::APFloatBase::SemanticsToEnum(Sem); 1707 } 1708 1709 bool isExact() const { return FloatingLiteralBits.IsExact; } 1710 void setExact(bool E) { FloatingLiteralBits.IsExact = E; } 1711 1712 /// getValueAsApproximateDouble - This returns the value as an inaccurate 1713 /// double. Note that this may cause loss of precision, but is useful for 1714 /// debugging dumps, etc. 1715 double getValueAsApproximateDouble() const; 1716 1717 SourceLocation getLocation() const { return Loc; } 1718 void setLocation(SourceLocation L) { Loc = L; } 1719 1720 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; } 1721 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; } 1722 1723 static bool classof(const Stmt *T) { 1724 return T->getStmtClass() == FloatingLiteralClass; 1725 } 1726 1727 // Iterators 1728 child_range children() { 1729 return child_range(child_iterator(), child_iterator()); 1730 } 1731 const_child_range children() const { 1732 return const_child_range(const_child_iterator(), const_child_iterator()); 1733 } 1734 }; 1735 1736 /// ImaginaryLiteral - We support imaginary integer and floating point literals, 1737 /// like "1.0i". We represent these as a wrapper around FloatingLiteral and 1738 /// IntegerLiteral classes. Instances of this class always have a Complex type 1739 /// whose element type matches the subexpression. 1740 /// 1741 class ImaginaryLiteral : public Expr { 1742 Stmt *Val; 1743 public: 1744 ImaginaryLiteral(Expr *val, QualType Ty) 1745 : Expr(ImaginaryLiteralClass, Ty, VK_PRValue, OK_Ordinary), Val(val) { 1746 setDependence(ExprDependence::None); 1747 } 1748 1749 /// Build an empty imaginary literal. 1750 explicit ImaginaryLiteral(EmptyShell Empty) 1751 : Expr(ImaginaryLiteralClass, Empty) { } 1752 1753 const Expr *getSubExpr() const { return cast<Expr>(Val); } 1754 Expr *getSubExpr() { return cast<Expr>(Val); } 1755 void setSubExpr(Expr *E) { Val = E; } 1756 1757 SourceLocation getBeginLoc() const LLVM_READONLY { 1758 return Val->getBeginLoc(); 1759 } 1760 SourceLocation getEndLoc() const LLVM_READONLY { return Val->getEndLoc(); } 1761 1762 static bool classof(const Stmt *T) { 1763 return T->getStmtClass() == ImaginaryLiteralClass; 1764 } 1765 1766 // Iterators 1767 child_range children() { return child_range(&Val, &Val+1); } 1768 const_child_range children() const { 1769 return const_child_range(&Val, &Val + 1); 1770 } 1771 }; 1772 1773 /// StringLiteral - This represents a string literal expression, e.g. "foo" 1774 /// or L"bar" (wide strings). The actual string data can be obtained with 1775 /// getBytes() and is NOT null-terminated. The length of the string data is 1776 /// determined by calling getByteLength(). 1777 /// 1778 /// The C type for a string is always a ConstantArrayType. In C++, the char 1779 /// type is const qualified, in C it is not. 1780 /// 1781 /// Note that strings in C can be formed by concatenation of multiple string 1782 /// literal pptokens in translation phase #6. This keeps track of the locations 1783 /// of each of these pieces. 1784 /// 1785 /// Strings in C can also be truncated and extended by assigning into arrays, 1786 /// e.g. with constructs like: 1787 /// char X[2] = "foobar"; 1788 /// In this case, getByteLength() will return 6, but the string literal will 1789 /// have type "char[2]". 1790 class StringLiteral final 1791 : public Expr, 1792 private llvm::TrailingObjects<StringLiteral, unsigned, SourceLocation, 1793 char> { 1794 friend class ASTStmtReader; 1795 friend TrailingObjects; 1796 1797 /// StringLiteral is followed by several trailing objects. They are in order: 1798 /// 1799 /// * A single unsigned storing the length in characters of this string. The 1800 /// length in bytes is this length times the width of a single character. 1801 /// Always present and stored as a trailing objects because storing it in 1802 /// StringLiteral would increase the size of StringLiteral by sizeof(void *) 1803 /// due to alignment requirements. If you add some data to StringLiteral, 1804 /// consider moving it inside StringLiteral. 1805 /// 1806 /// * An array of getNumConcatenated() SourceLocation, one for each of the 1807 /// token this string is made of. 1808 /// 1809 /// * An array of getByteLength() char used to store the string data. 1810 1811 public: 1812 enum StringKind { Ordinary, Wide, UTF8, UTF16, UTF32, Unevaluated }; 1813 1814 private: 1815 unsigned numTrailingObjects(OverloadToken<unsigned>) const { return 1; } 1816 unsigned numTrailingObjects(OverloadToken<SourceLocation>) const { 1817 return getNumConcatenated(); 1818 } 1819 1820 unsigned numTrailingObjects(OverloadToken<char>) const { 1821 return getByteLength(); 1822 } 1823 1824 char *getStrDataAsChar() { return getTrailingObjects<char>(); } 1825 const char *getStrDataAsChar() const { return getTrailingObjects<char>(); } 1826 1827 const uint16_t *getStrDataAsUInt16() const { 1828 return reinterpret_cast<const uint16_t *>(getTrailingObjects<char>()); 1829 } 1830 1831 const uint32_t *getStrDataAsUInt32() const { 1832 return reinterpret_cast<const uint32_t *>(getTrailingObjects<char>()); 1833 } 1834 1835 /// Build a string literal. 1836 StringLiteral(const ASTContext &Ctx, StringRef Str, StringKind Kind, 1837 bool Pascal, QualType Ty, const SourceLocation *Loc, 1838 unsigned NumConcatenated); 1839 1840 /// Build an empty string literal. 1841 StringLiteral(EmptyShell Empty, unsigned NumConcatenated, unsigned Length, 1842 unsigned CharByteWidth); 1843 1844 /// Map a target and string kind to the appropriate character width. 1845 static unsigned mapCharByteWidth(TargetInfo const &Target, StringKind SK); 1846 1847 /// Set one of the string literal token. 1848 void setStrTokenLoc(unsigned TokNum, SourceLocation L) { 1849 assert(TokNum < getNumConcatenated() && "Invalid tok number"); 1850 getTrailingObjects<SourceLocation>()[TokNum] = L; 1851 } 1852 1853 public: 1854 /// This is the "fully general" constructor that allows representation of 1855 /// strings formed from multiple concatenated tokens. 1856 static StringLiteral *Create(const ASTContext &Ctx, StringRef Str, 1857 StringKind Kind, bool Pascal, QualType Ty, 1858 const SourceLocation *Loc, 1859 unsigned NumConcatenated); 1860 1861 /// Simple constructor for string literals made from one token. 1862 static StringLiteral *Create(const ASTContext &Ctx, StringRef Str, 1863 StringKind Kind, bool Pascal, QualType Ty, 1864 SourceLocation Loc) { 1865 return Create(Ctx, Str, Kind, Pascal, Ty, &Loc, 1); 1866 } 1867 1868 /// Construct an empty string literal. 1869 static StringLiteral *CreateEmpty(const ASTContext &Ctx, 1870 unsigned NumConcatenated, unsigned Length, 1871 unsigned CharByteWidth); 1872 1873 StringRef getString() const { 1874 assert((isUnevaluated() || getCharByteWidth() == 1) && 1875 "This function is used in places that assume strings use char"); 1876 return StringRef(getStrDataAsChar(), getByteLength()); 1877 } 1878 1879 /// Allow access to clients that need the byte representation, such as 1880 /// ASTWriterStmt::VisitStringLiteral(). 1881 StringRef getBytes() const { 1882 // FIXME: StringRef may not be the right type to use as a result for this. 1883 return StringRef(getStrDataAsChar(), getByteLength()); 1884 } 1885 1886 void outputString(raw_ostream &OS) const; 1887 1888 uint32_t getCodeUnit(size_t i) const { 1889 assert(i < getLength() && "out of bounds access"); 1890 switch (getCharByteWidth()) { 1891 case 1: 1892 return static_cast<unsigned char>(getStrDataAsChar()[i]); 1893 case 2: 1894 return getStrDataAsUInt16()[i]; 1895 case 4: 1896 return getStrDataAsUInt32()[i]; 1897 } 1898 llvm_unreachable("Unsupported character width!"); 1899 } 1900 1901 unsigned getByteLength() const { return getCharByteWidth() * getLength(); } 1902 unsigned getLength() const { return *getTrailingObjects<unsigned>(); } 1903 unsigned getCharByteWidth() const { return StringLiteralBits.CharByteWidth; } 1904 1905 StringKind getKind() const { 1906 return static_cast<StringKind>(StringLiteralBits.Kind); 1907 } 1908 1909 bool isOrdinary() const { return getKind() == Ordinary; } 1910 bool isWide() const { return getKind() == Wide; } 1911 bool isUTF8() const { return getKind() == UTF8; } 1912 bool isUTF16() const { return getKind() == UTF16; } 1913 bool isUTF32() const { return getKind() == UTF32; } 1914 bool isUnevaluated() const { return getKind() == Unevaluated; } 1915 bool isPascal() const { return StringLiteralBits.IsPascal; } 1916 1917 bool containsNonAscii() const { 1918 for (auto c : getString()) 1919 if (!isASCII(c)) 1920 return true; 1921 return false; 1922 } 1923 1924 bool containsNonAsciiOrNull() const { 1925 for (auto c : getString()) 1926 if (!isASCII(c) || !c) 1927 return true; 1928 return false; 1929 } 1930 1931 /// getNumConcatenated - Get the number of string literal tokens that were 1932 /// concatenated in translation phase #6 to form this string literal. 1933 unsigned getNumConcatenated() const { 1934 return StringLiteralBits.NumConcatenated; 1935 } 1936 1937 /// Get one of the string literal token. 1938 SourceLocation getStrTokenLoc(unsigned TokNum) const { 1939 assert(TokNum < getNumConcatenated() && "Invalid tok number"); 1940 return getTrailingObjects<SourceLocation>()[TokNum]; 1941 } 1942 1943 /// getLocationOfByte - Return a source location that points to the specified 1944 /// byte of this string literal. 1945 /// 1946 /// Strings are amazingly complex. They can be formed from multiple tokens 1947 /// and can have escape sequences in them in addition to the usual trigraph 1948 /// and escaped newline business. This routine handles this complexity. 1949 /// 1950 SourceLocation 1951 getLocationOfByte(unsigned ByteNo, const SourceManager &SM, 1952 const LangOptions &Features, const TargetInfo &Target, 1953 unsigned *StartToken = nullptr, 1954 unsigned *StartTokenByteOffset = nullptr) const; 1955 1956 typedef const SourceLocation *tokloc_iterator; 1957 1958 tokloc_iterator tokloc_begin() const { 1959 return getTrailingObjects<SourceLocation>(); 1960 } 1961 1962 tokloc_iterator tokloc_end() const { 1963 return getTrailingObjects<SourceLocation>() + getNumConcatenated(); 1964 } 1965 1966 SourceLocation getBeginLoc() const LLVM_READONLY { return *tokloc_begin(); } 1967 SourceLocation getEndLoc() const LLVM_READONLY { return *(tokloc_end() - 1); } 1968 1969 static bool classof(const Stmt *T) { 1970 return T->getStmtClass() == StringLiteralClass; 1971 } 1972 1973 // Iterators 1974 child_range children() { 1975 return child_range(child_iterator(), child_iterator()); 1976 } 1977 const_child_range children() const { 1978 return const_child_range(const_child_iterator(), const_child_iterator()); 1979 } 1980 }; 1981 1982 /// [C99 6.4.2.2] - A predefined identifier such as __func__. 1983 class PredefinedExpr final 1984 : public Expr, 1985 private llvm::TrailingObjects<PredefinedExpr, Stmt *> { 1986 friend class ASTStmtReader; 1987 friend TrailingObjects; 1988 1989 // PredefinedExpr is optionally followed by a single trailing 1990 // "Stmt *" for the predefined identifier. It is present if and only if 1991 // hasFunctionName() is true and is always a "StringLiteral *". 1992 1993 public: 1994 enum IdentKind { 1995 Func, 1996 Function, 1997 LFunction, // Same as Function, but as wide string. 1998 FuncDName, 1999 FuncSig, 2000 LFuncSig, // Same as FuncSig, but as wide string 2001 PrettyFunction, 2002 /// The same as PrettyFunction, except that the 2003 /// 'virtual' keyword is omitted for virtual member functions. 2004 PrettyFunctionNoVirtual 2005 }; 2006 2007 private: 2008 PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK, 2009 bool IsTransparent, StringLiteral *SL); 2010 2011 explicit PredefinedExpr(EmptyShell Empty, bool HasFunctionName); 2012 2013 /// True if this PredefinedExpr has storage for a function name. 2014 bool hasFunctionName() const { return PredefinedExprBits.HasFunctionName; } 2015 2016 void setFunctionName(StringLiteral *SL) { 2017 assert(hasFunctionName() && 2018 "This PredefinedExpr has no storage for a function name!"); 2019 *getTrailingObjects<Stmt *>() = SL; 2020 } 2021 2022 public: 2023 /// Create a PredefinedExpr. 2024 /// 2025 /// If IsTransparent, the PredefinedExpr is transparently handled as a 2026 /// StringLiteral. 2027 static PredefinedExpr *Create(const ASTContext &Ctx, SourceLocation L, 2028 QualType FNTy, IdentKind IK, bool IsTransparent, 2029 StringLiteral *SL); 2030 2031 /// Create an empty PredefinedExpr. 2032 static PredefinedExpr *CreateEmpty(const ASTContext &Ctx, 2033 bool HasFunctionName); 2034 2035 IdentKind getIdentKind() const { 2036 return static_cast<IdentKind>(PredefinedExprBits.Kind); 2037 } 2038 2039 bool isTransparent() const { return PredefinedExprBits.IsTransparent; } 2040 2041 SourceLocation getLocation() const { return PredefinedExprBits.Loc; } 2042 void setLocation(SourceLocation L) { PredefinedExprBits.Loc = L; } 2043 2044 StringLiteral *getFunctionName() { 2045 return hasFunctionName() 2046 ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>()) 2047 : nullptr; 2048 } 2049 2050 const StringLiteral *getFunctionName() const { 2051 return hasFunctionName() 2052 ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>()) 2053 : nullptr; 2054 } 2055 2056 static StringRef getIdentKindName(IdentKind IK); 2057 StringRef getIdentKindName() const { 2058 return getIdentKindName(getIdentKind()); 2059 } 2060 2061 static std::string ComputeName(IdentKind IK, const Decl *CurrentDecl); 2062 2063 SourceLocation getBeginLoc() const { return getLocation(); } 2064 SourceLocation getEndLoc() const { return getLocation(); } 2065 2066 static bool classof(const Stmt *T) { 2067 return T->getStmtClass() == PredefinedExprClass; 2068 } 2069 2070 // Iterators 2071 child_range children() { 2072 return child_range(getTrailingObjects<Stmt *>(), 2073 getTrailingObjects<Stmt *>() + hasFunctionName()); 2074 } 2075 2076 const_child_range children() const { 2077 return const_child_range(getTrailingObjects<Stmt *>(), 2078 getTrailingObjects<Stmt *>() + hasFunctionName()); 2079 } 2080 }; 2081 2082 // This represents a use of the __builtin_sycl_unique_stable_name, which takes a 2083 // type-id, and at CodeGen time emits a unique string representation of the 2084 // type in a way that permits us to properly encode information about the SYCL 2085 // kernels. 2086 class SYCLUniqueStableNameExpr final : public Expr { 2087 friend class ASTStmtReader; 2088 SourceLocation OpLoc, LParen, RParen; 2089 TypeSourceInfo *TypeInfo; 2090 2091 SYCLUniqueStableNameExpr(EmptyShell Empty, QualType ResultTy); 2092 SYCLUniqueStableNameExpr(SourceLocation OpLoc, SourceLocation LParen, 2093 SourceLocation RParen, QualType ResultTy, 2094 TypeSourceInfo *TSI); 2095 2096 void setTypeSourceInfo(TypeSourceInfo *Ty) { TypeInfo = Ty; } 2097 2098 void setLocation(SourceLocation L) { OpLoc = L; } 2099 void setLParenLocation(SourceLocation L) { LParen = L; } 2100 void setRParenLocation(SourceLocation L) { RParen = L; } 2101 2102 public: 2103 TypeSourceInfo *getTypeSourceInfo() { return TypeInfo; } 2104 2105 const TypeSourceInfo *getTypeSourceInfo() const { return TypeInfo; } 2106 2107 static SYCLUniqueStableNameExpr * 2108 Create(const ASTContext &Ctx, SourceLocation OpLoc, SourceLocation LParen, 2109 SourceLocation RParen, TypeSourceInfo *TSI); 2110 2111 static SYCLUniqueStableNameExpr *CreateEmpty(const ASTContext &Ctx); 2112 2113 SourceLocation getBeginLoc() const { return getLocation(); } 2114 SourceLocation getEndLoc() const { return RParen; } 2115 SourceLocation getLocation() const { return OpLoc; } 2116 SourceLocation getLParenLocation() const { return LParen; } 2117 SourceLocation getRParenLocation() const { return RParen; } 2118 2119 static bool classof(const Stmt *T) { 2120 return T->getStmtClass() == SYCLUniqueStableNameExprClass; 2121 } 2122 2123 // Iterators 2124 child_range children() { 2125 return child_range(child_iterator(), child_iterator()); 2126 } 2127 2128 const_child_range children() const { 2129 return const_child_range(const_child_iterator(), const_child_iterator()); 2130 } 2131 2132 // Convenience function to generate the name of the currently stored type. 2133 std::string ComputeName(ASTContext &Context) const; 2134 2135 // Get the generated name of the type. Note that this only works after all 2136 // kernels have been instantiated. 2137 static std::string ComputeName(ASTContext &Context, QualType Ty); 2138 }; 2139 2140 /// ParenExpr - This represents a parethesized expression, e.g. "(1)". This 2141 /// AST node is only formed if full location information is requested. 2142 class ParenExpr : public Expr { 2143 SourceLocation L, R; 2144 Stmt *Val; 2145 public: 2146 ParenExpr(SourceLocation l, SourceLocation r, Expr *val) 2147 : Expr(ParenExprClass, val->getType(), val->getValueKind(), 2148 val->getObjectKind()), 2149 L(l), R(r), Val(val) { 2150 setDependence(computeDependence(this)); 2151 } 2152 2153 /// Construct an empty parenthesized expression. 2154 explicit ParenExpr(EmptyShell Empty) 2155 : Expr(ParenExprClass, Empty) { } 2156 2157 const Expr *getSubExpr() const { return cast<Expr>(Val); } 2158 Expr *getSubExpr() { return cast<Expr>(Val); } 2159 void setSubExpr(Expr *E) { Val = E; } 2160 2161 SourceLocation getBeginLoc() const LLVM_READONLY { return L; } 2162 SourceLocation getEndLoc() const LLVM_READONLY { return R; } 2163 2164 /// Get the location of the left parentheses '('. 2165 SourceLocation getLParen() const { return L; } 2166 void setLParen(SourceLocation Loc) { L = Loc; } 2167 2168 /// Get the location of the right parentheses ')'. 2169 SourceLocation getRParen() const { return R; } 2170 void setRParen(SourceLocation Loc) { R = Loc; } 2171 2172 static bool classof(const Stmt *T) { 2173 return T->getStmtClass() == ParenExprClass; 2174 } 2175 2176 // Iterators 2177 child_range children() { return child_range(&Val, &Val+1); } 2178 const_child_range children() const { 2179 return const_child_range(&Val, &Val + 1); 2180 } 2181 }; 2182 2183 /// UnaryOperator - This represents the unary-expression's (except sizeof and 2184 /// alignof), the postinc/postdec operators from postfix-expression, and various 2185 /// extensions. 2186 /// 2187 /// Notes on various nodes: 2188 /// 2189 /// Real/Imag - These return the real/imag part of a complex operand. If 2190 /// applied to a non-complex value, the former returns its operand and the 2191 /// later returns zero in the type of the operand. 2192 /// 2193 class UnaryOperator final 2194 : public Expr, 2195 private llvm::TrailingObjects<UnaryOperator, FPOptionsOverride> { 2196 Stmt *Val; 2197 2198 size_t numTrailingObjects(OverloadToken<FPOptionsOverride>) const { 2199 return UnaryOperatorBits.HasFPFeatures ? 1 : 0; 2200 } 2201 2202 FPOptionsOverride &getTrailingFPFeatures() { 2203 assert(UnaryOperatorBits.HasFPFeatures); 2204 return *getTrailingObjects<FPOptionsOverride>(); 2205 } 2206 2207 const FPOptionsOverride &getTrailingFPFeatures() const { 2208 assert(UnaryOperatorBits.HasFPFeatures); 2209 return *getTrailingObjects<FPOptionsOverride>(); 2210 } 2211 2212 public: 2213 typedef UnaryOperatorKind Opcode; 2214 2215 protected: 2216 UnaryOperator(const ASTContext &Ctx, Expr *input, Opcode opc, QualType type, 2217 ExprValueKind VK, ExprObjectKind OK, SourceLocation l, 2218 bool CanOverflow, FPOptionsOverride FPFeatures); 2219 2220 /// Build an empty unary operator. 2221 explicit UnaryOperator(bool HasFPFeatures, EmptyShell Empty) 2222 : Expr(UnaryOperatorClass, Empty) { 2223 UnaryOperatorBits.Opc = UO_AddrOf; 2224 UnaryOperatorBits.HasFPFeatures = HasFPFeatures; 2225 } 2226 2227 public: 2228 static UnaryOperator *CreateEmpty(const ASTContext &C, bool hasFPFeatures); 2229 2230 static UnaryOperator *Create(const ASTContext &C, Expr *input, Opcode opc, 2231 QualType type, ExprValueKind VK, 2232 ExprObjectKind OK, SourceLocation l, 2233 bool CanOverflow, FPOptionsOverride FPFeatures); 2234 2235 Opcode getOpcode() const { 2236 return static_cast<Opcode>(UnaryOperatorBits.Opc); 2237 } 2238 void setOpcode(Opcode Opc) { UnaryOperatorBits.Opc = Opc; } 2239 2240 Expr *getSubExpr() const { return cast<Expr>(Val); } 2241 void setSubExpr(Expr *E) { Val = E; } 2242 2243 /// getOperatorLoc - Return the location of the operator. 2244 SourceLocation getOperatorLoc() const { return UnaryOperatorBits.Loc; } 2245 void setOperatorLoc(SourceLocation L) { UnaryOperatorBits.Loc = L; } 2246 2247 /// Returns true if the unary operator can cause an overflow. For instance, 2248 /// signed int i = INT_MAX; i++; 2249 /// signed char c = CHAR_MAX; c++; 2250 /// Due to integer promotions, c++ is promoted to an int before the postfix 2251 /// increment, and the result is an int that cannot overflow. However, i++ 2252 /// can overflow. 2253 bool canOverflow() const { return UnaryOperatorBits.CanOverflow; } 2254 void setCanOverflow(bool C) { UnaryOperatorBits.CanOverflow = C; } 2255 2256 /// Get the FP contractability status of this operator. Only meaningful for 2257 /// operations on floating point types. 2258 bool isFPContractableWithinStatement(const LangOptions &LO) const { 2259 return getFPFeaturesInEffect(LO).allowFPContractWithinStatement(); 2260 } 2261 2262 /// Get the FENV_ACCESS status of this operator. Only meaningful for 2263 /// operations on floating point types. 2264 bool isFEnvAccessOn(const LangOptions &LO) const { 2265 return getFPFeaturesInEffect(LO).getAllowFEnvAccess(); 2266 } 2267 2268 /// isPostfix - Return true if this is a postfix operation, like x++. 2269 static bool isPostfix(Opcode Op) { 2270 return Op == UO_PostInc || Op == UO_PostDec; 2271 } 2272 2273 /// isPrefix - Return true if this is a prefix operation, like --x. 2274 static bool isPrefix(Opcode Op) { 2275 return Op == UO_PreInc || Op == UO_PreDec; 2276 } 2277 2278 bool isPrefix() const { return isPrefix(getOpcode()); } 2279 bool isPostfix() const { return isPostfix(getOpcode()); } 2280 2281 static bool isIncrementOp(Opcode Op) { 2282 return Op == UO_PreInc || Op == UO_PostInc; 2283 } 2284 bool isIncrementOp() const { 2285 return isIncrementOp(getOpcode()); 2286 } 2287 2288 static bool isDecrementOp(Opcode Op) { 2289 return Op == UO_PreDec || Op == UO_PostDec; 2290 } 2291 bool isDecrementOp() const { 2292 return isDecrementOp(getOpcode()); 2293 } 2294 2295 static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; } 2296 bool isIncrementDecrementOp() const { 2297 return isIncrementDecrementOp(getOpcode()); 2298 } 2299 2300 static bool isArithmeticOp(Opcode Op) { 2301 return Op >= UO_Plus && Op <= UO_LNot; 2302 } 2303 bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); } 2304 2305 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it 2306 /// corresponds to, e.g. "sizeof" or "[pre]++" 2307 static StringRef getOpcodeStr(Opcode Op); 2308 2309 /// Retrieve the unary opcode that corresponds to the given 2310 /// overloaded operator. 2311 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix); 2312 2313 /// Retrieve the overloaded operator kind that corresponds to 2314 /// the given unary opcode. 2315 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc); 2316 2317 SourceLocation getBeginLoc() const LLVM_READONLY { 2318 return isPostfix() ? Val->getBeginLoc() : getOperatorLoc(); 2319 } 2320 SourceLocation getEndLoc() const LLVM_READONLY { 2321 return isPostfix() ? getOperatorLoc() : Val->getEndLoc(); 2322 } 2323 SourceLocation getExprLoc() const { return getOperatorLoc(); } 2324 2325 static bool classof(const Stmt *T) { 2326 return T->getStmtClass() == UnaryOperatorClass; 2327 } 2328 2329 // Iterators 2330 child_range children() { return child_range(&Val, &Val+1); } 2331 const_child_range children() const { 2332 return const_child_range(&Val, &Val + 1); 2333 } 2334 2335 /// Is FPFeatures in Trailing Storage? 2336 bool hasStoredFPFeatures() const { return UnaryOperatorBits.HasFPFeatures; } 2337 2338 /// Get FPFeatures from trailing storage. 2339 FPOptionsOverride getStoredFPFeatures() const { 2340 return getTrailingFPFeatures(); 2341 } 2342 2343 protected: 2344 /// Set FPFeatures in trailing storage, used only by Serialization 2345 void setStoredFPFeatures(FPOptionsOverride F) { getTrailingFPFeatures() = F; } 2346 2347 public: 2348 /// Get the FP features status of this operator. Only meaningful for 2349 /// operations on floating point types. 2350 FPOptions getFPFeaturesInEffect(const LangOptions &LO) const { 2351 if (UnaryOperatorBits.HasFPFeatures) 2352 return getStoredFPFeatures().applyOverrides(LO); 2353 return FPOptions::defaultWithoutTrailingStorage(LO); 2354 } 2355 FPOptionsOverride getFPOptionsOverride() const { 2356 if (UnaryOperatorBits.HasFPFeatures) 2357 return getStoredFPFeatures(); 2358 return FPOptionsOverride(); 2359 } 2360 2361 friend TrailingObjects; 2362 friend class ASTReader; 2363 friend class ASTStmtReader; 2364 friend class ASTStmtWriter; 2365 }; 2366 2367 /// Helper class for OffsetOfExpr. 2368 2369 // __builtin_offsetof(type, identifier(.identifier|[expr])*) 2370 class OffsetOfNode { 2371 public: 2372 /// The kind of offsetof node we have. 2373 enum Kind { 2374 /// An index into an array. 2375 Array = 0x00, 2376 /// A field. 2377 Field = 0x01, 2378 /// A field in a dependent type, known only by its name. 2379 Identifier = 0x02, 2380 /// An implicit indirection through a C++ base class, when the 2381 /// field found is in a base class. 2382 Base = 0x03 2383 }; 2384 2385 private: 2386 enum { MaskBits = 2, Mask = 0x03 }; 2387 2388 /// The source range that covers this part of the designator. 2389 SourceRange Range; 2390 2391 /// The data describing the designator, which comes in three 2392 /// different forms, depending on the lower two bits. 2393 /// - An unsigned index into the array of Expr*'s stored after this node 2394 /// in memory, for [constant-expression] designators. 2395 /// - A FieldDecl*, for references to a known field. 2396 /// - An IdentifierInfo*, for references to a field with a given name 2397 /// when the class type is dependent. 2398 /// - A CXXBaseSpecifier*, for references that look at a field in a 2399 /// base class. 2400 uintptr_t Data; 2401 2402 public: 2403 /// Create an offsetof node that refers to an array element. 2404 OffsetOfNode(SourceLocation LBracketLoc, unsigned Index, 2405 SourceLocation RBracketLoc) 2406 : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) {} 2407 2408 /// Create an offsetof node that refers to a field. 2409 OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field, SourceLocation NameLoc) 2410 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc), 2411 Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) {} 2412 2413 /// Create an offsetof node that refers to an identifier. 2414 OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name, 2415 SourceLocation NameLoc) 2416 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc), 2417 Data(reinterpret_cast<uintptr_t>(Name) | Identifier) {} 2418 2419 /// Create an offsetof node that refers into a C++ base class. 2420 explicit OffsetOfNode(const CXXBaseSpecifier *Base) 2421 : Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {} 2422 2423 /// Determine what kind of offsetof node this is. 2424 Kind getKind() const { return static_cast<Kind>(Data & Mask); } 2425 2426 /// For an array element node, returns the index into the array 2427 /// of expressions. 2428 unsigned getArrayExprIndex() const { 2429 assert(getKind() == Array); 2430 return Data >> 2; 2431 } 2432 2433 /// For a field offsetof node, returns the field. 2434 FieldDecl *getField() const { 2435 assert(getKind() == Field); 2436 return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask); 2437 } 2438 2439 /// For a field or identifier offsetof node, returns the name of 2440 /// the field. 2441 IdentifierInfo *getFieldName() const; 2442 2443 /// For a base class node, returns the base specifier. 2444 CXXBaseSpecifier *getBase() const { 2445 assert(getKind() == Base); 2446 return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask); 2447 } 2448 2449 /// Retrieve the source range that covers this offsetof node. 2450 /// 2451 /// For an array element node, the source range contains the locations of 2452 /// the square brackets. For a field or identifier node, the source range 2453 /// contains the location of the period (if there is one) and the 2454 /// identifier. 2455 SourceRange getSourceRange() const LLVM_READONLY { return Range; } 2456 SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); } 2457 SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); } 2458 }; 2459 2460 /// OffsetOfExpr - [C99 7.17] - This represents an expression of the form 2461 /// offsetof(record-type, member-designator). For example, given: 2462 /// @code 2463 /// struct S { 2464 /// float f; 2465 /// double d; 2466 /// }; 2467 /// struct T { 2468 /// int i; 2469 /// struct S s[10]; 2470 /// }; 2471 /// @endcode 2472 /// we can represent and evaluate the expression @c offsetof(struct T, s[2].d). 2473 2474 class OffsetOfExpr final 2475 : public Expr, 2476 private llvm::TrailingObjects<OffsetOfExpr, OffsetOfNode, Expr *> { 2477 SourceLocation OperatorLoc, RParenLoc; 2478 // Base type; 2479 TypeSourceInfo *TSInfo; 2480 // Number of sub-components (i.e. instances of OffsetOfNode). 2481 unsigned NumComps; 2482 // Number of sub-expressions (i.e. array subscript expressions). 2483 unsigned NumExprs; 2484 2485 size_t numTrailingObjects(OverloadToken<OffsetOfNode>) const { 2486 return NumComps; 2487 } 2488 2489 OffsetOfExpr(const ASTContext &C, QualType type, 2490 SourceLocation OperatorLoc, TypeSourceInfo *tsi, 2491 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs, 2492 SourceLocation RParenLoc); 2493 2494 explicit OffsetOfExpr(unsigned numComps, unsigned numExprs) 2495 : Expr(OffsetOfExprClass, EmptyShell()), 2496 TSInfo(nullptr), NumComps(numComps), NumExprs(numExprs) {} 2497 2498 public: 2499 2500 static OffsetOfExpr *Create(const ASTContext &C, QualType type, 2501 SourceLocation OperatorLoc, TypeSourceInfo *tsi, 2502 ArrayRef<OffsetOfNode> comps, 2503 ArrayRef<Expr*> exprs, SourceLocation RParenLoc); 2504 2505 static OffsetOfExpr *CreateEmpty(const ASTContext &C, 2506 unsigned NumComps, unsigned NumExprs); 2507 2508 /// getOperatorLoc - Return the location of the operator. 2509 SourceLocation getOperatorLoc() const { return OperatorLoc; } 2510 void setOperatorLoc(SourceLocation L) { OperatorLoc = L; } 2511 2512 /// Return the location of the right parentheses. 2513 SourceLocation getRParenLoc() const { return RParenLoc; } 2514 void setRParenLoc(SourceLocation R) { RParenLoc = R; } 2515 2516 TypeSourceInfo *getTypeSourceInfo() const { 2517 return TSInfo; 2518 } 2519 void setTypeSourceInfo(TypeSourceInfo *tsi) { 2520 TSInfo = tsi; 2521 } 2522 2523 const OffsetOfNode &getComponent(unsigned Idx) const { 2524 assert(Idx < NumComps && "Subscript out of range"); 2525 return getTrailingObjects<OffsetOfNode>()[Idx]; 2526 } 2527 2528 void setComponent(unsigned Idx, OffsetOfNode ON) { 2529 assert(Idx < NumComps && "Subscript out of range"); 2530 getTrailingObjects<OffsetOfNode>()[Idx] = ON; 2531 } 2532 2533 unsigned getNumComponents() const { 2534 return NumComps; 2535 } 2536 2537 Expr* getIndexExpr(unsigned Idx) { 2538 assert(Idx < NumExprs && "Subscript out of range"); 2539 return getTrailingObjects<Expr *>()[Idx]; 2540 } 2541 2542 const Expr *getIndexExpr(unsigned Idx) const { 2543 assert(Idx < NumExprs && "Subscript out of range"); 2544 return getTrailingObjects<Expr *>()[Idx]; 2545 } 2546 2547 void setIndexExpr(unsigned Idx, Expr* E) { 2548 assert(Idx < NumComps && "Subscript out of range"); 2549 getTrailingObjects<Expr *>()[Idx] = E; 2550 } 2551 2552 unsigned getNumExpressions() const { 2553 return NumExprs; 2554 } 2555 2556 SourceLocation getBeginLoc() const LLVM_READONLY { return OperatorLoc; } 2557 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; } 2558 2559 static bool classof(const Stmt *T) { 2560 return T->getStmtClass() == OffsetOfExprClass; 2561 } 2562 2563 // Iterators 2564 child_range children() { 2565 Stmt **begin = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>()); 2566 return child_range(begin, begin + NumExprs); 2567 } 2568 const_child_range children() const { 2569 Stmt *const *begin = 2570 reinterpret_cast<Stmt *const *>(getTrailingObjects<Expr *>()); 2571 return const_child_range(begin, begin + NumExprs); 2572 } 2573 friend TrailingObjects; 2574 }; 2575 2576 /// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) 2577 /// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and 2578 /// vec_step (OpenCL 1.1 6.11.12). 2579 class UnaryExprOrTypeTraitExpr : public Expr { 2580 union { 2581 TypeSourceInfo *Ty; 2582 Stmt *Ex; 2583 } Argument; 2584 SourceLocation OpLoc, RParenLoc; 2585 2586 public: 2587 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo, 2588 QualType resultType, SourceLocation op, 2589 SourceLocation rp) 2590 : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_PRValue, 2591 OK_Ordinary), 2592 OpLoc(op), RParenLoc(rp) { 2593 assert(ExprKind <= UETT_Last && "invalid enum value!"); 2594 UnaryExprOrTypeTraitExprBits.Kind = ExprKind; 2595 assert(static_cast<unsigned>(ExprKind) == 2596 UnaryExprOrTypeTraitExprBits.Kind && 2597 "UnaryExprOrTypeTraitExprBits.Kind overflow!"); 2598 UnaryExprOrTypeTraitExprBits.IsType = true; 2599 Argument.Ty = TInfo; 2600 setDependence(computeDependence(this)); 2601 } 2602 2603 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E, 2604 QualType resultType, SourceLocation op, 2605 SourceLocation rp); 2606 2607 /// Construct an empty sizeof/alignof expression. 2608 explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty) 2609 : Expr(UnaryExprOrTypeTraitExprClass, Empty) { } 2610 2611 UnaryExprOrTypeTrait getKind() const { 2612 return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind); 2613 } 2614 void setKind(UnaryExprOrTypeTrait K) { 2615 assert(K <= UETT_Last && "invalid enum value!"); 2616 UnaryExprOrTypeTraitExprBits.Kind = K; 2617 assert(static_cast<unsigned>(K) == UnaryExprOrTypeTraitExprBits.Kind && 2618 "UnaryExprOrTypeTraitExprBits.Kind overflow!"); 2619 } 2620 2621 bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; } 2622 QualType getArgumentType() const { 2623 return getArgumentTypeInfo()->getType(); 2624 } 2625 TypeSourceInfo *getArgumentTypeInfo() const { 2626 assert(isArgumentType() && "calling getArgumentType() when arg is expr"); 2627 return Argument.Ty; 2628 } 2629 Expr *getArgumentExpr() { 2630 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type"); 2631 return static_cast<Expr*>(Argument.Ex); 2632 } 2633 const Expr *getArgumentExpr() const { 2634 return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr(); 2635 } 2636 2637 void setArgument(Expr *E) { 2638 Argument.Ex = E; 2639 UnaryExprOrTypeTraitExprBits.IsType = false; 2640 } 2641 void setArgument(TypeSourceInfo *TInfo) { 2642 Argument.Ty = TInfo; 2643 UnaryExprOrTypeTraitExprBits.IsType = true; 2644 } 2645 2646 /// Gets the argument type, or the type of the argument expression, whichever 2647 /// is appropriate. 2648 QualType getTypeOfArgument() const { 2649 return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType(); 2650 } 2651 2652 SourceLocation getOperatorLoc() const { return OpLoc; } 2653 void setOperatorLoc(SourceLocation L) { OpLoc = L; } 2654 2655 SourceLocation getRParenLoc() const { return RParenLoc; } 2656 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 2657 2658 SourceLocation getBeginLoc() const LLVM_READONLY { return OpLoc; } 2659 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; } 2660 2661 static bool classof(const Stmt *T) { 2662 return T->getStmtClass() == UnaryExprOrTypeTraitExprClass; 2663 } 2664 2665 // Iterators 2666 child_range children(); 2667 const_child_range children() const; 2668 }; 2669 2670 //===----------------------------------------------------------------------===// 2671 // Postfix Operators. 2672 //===----------------------------------------------------------------------===// 2673 2674 /// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting. 2675 class ArraySubscriptExpr : public Expr { 2676 enum { LHS, RHS, END_EXPR }; 2677 Stmt *SubExprs[END_EXPR]; 2678 2679 bool lhsIsBase() const { return getRHS()->getType()->isIntegerType(); } 2680 2681 public: 2682 ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t, ExprValueKind VK, 2683 ExprObjectKind OK, SourceLocation rbracketloc) 2684 : Expr(ArraySubscriptExprClass, t, VK, OK) { 2685 SubExprs[LHS] = lhs; 2686 SubExprs[RHS] = rhs; 2687 ArrayOrMatrixSubscriptExprBits.RBracketLoc = rbracketloc; 2688 setDependence(computeDependence(this)); 2689 } 2690 2691 /// Create an empty array subscript expression. 2692 explicit ArraySubscriptExpr(EmptyShell Shell) 2693 : Expr(ArraySubscriptExprClass, Shell) { } 2694 2695 /// An array access can be written A[4] or 4[A] (both are equivalent). 2696 /// - getBase() and getIdx() always present the normalized view: A[4]. 2697 /// In this case getBase() returns "A" and getIdx() returns "4". 2698 /// - getLHS() and getRHS() present the syntactic view. e.g. for 2699 /// 4[A] getLHS() returns "4". 2700 /// Note: Because vector element access is also written A[4] we must 2701 /// predicate the format conversion in getBase and getIdx only on the 2702 /// the type of the RHS, as it is possible for the LHS to be a vector of 2703 /// integer type 2704 Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); } 2705 const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } 2706 void setLHS(Expr *E) { SubExprs[LHS] = E; } 2707 2708 Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); } 2709 const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } 2710 void setRHS(Expr *E) { SubExprs[RHS] = E; } 2711 2712 Expr *getBase() { return lhsIsBase() ? getLHS() : getRHS(); } 2713 const Expr *getBase() const { return lhsIsBase() ? getLHS() : getRHS(); } 2714 2715 Expr *getIdx() { return lhsIsBase() ? getRHS() : getLHS(); } 2716 const Expr *getIdx() const { return lhsIsBase() ? getRHS() : getLHS(); } 2717 2718 SourceLocation getBeginLoc() const LLVM_READONLY { 2719 return getLHS()->getBeginLoc(); 2720 } 2721 SourceLocation getEndLoc() const { return getRBracketLoc(); } 2722 2723 SourceLocation getRBracketLoc() const { 2724 return ArrayOrMatrixSubscriptExprBits.RBracketLoc; 2725 } 2726 void setRBracketLoc(SourceLocation L) { 2727 ArrayOrMatrixSubscriptExprBits.RBracketLoc = L; 2728 } 2729 2730 SourceLocation getExprLoc() const LLVM_READONLY { 2731 return getBase()->getExprLoc(); 2732 } 2733 2734 static bool classof(const Stmt *T) { 2735 return T->getStmtClass() == ArraySubscriptExprClass; 2736 } 2737 2738 // Iterators 2739 child_range children() { 2740 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); 2741 } 2742 const_child_range children() const { 2743 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR); 2744 } 2745 }; 2746 2747 /// MatrixSubscriptExpr - Matrix subscript expression for the MatrixType 2748 /// extension. 2749 /// MatrixSubscriptExpr can be either incomplete (only Base and RowIdx are set 2750 /// so far, the type is IncompleteMatrixIdx) or complete (Base, RowIdx and 2751 /// ColumnIdx refer to valid expressions). Incomplete matrix expressions only 2752 /// exist during the initial construction of the AST. 2753 class MatrixSubscriptExpr : public Expr { 2754 enum { BASE, ROW_IDX, COLUMN_IDX, END_EXPR }; 2755 Stmt *SubExprs[END_EXPR]; 2756 2757 public: 2758 MatrixSubscriptExpr(Expr *Base, Expr *RowIdx, Expr *ColumnIdx, QualType T, 2759 SourceLocation RBracketLoc) 2760 : Expr(MatrixSubscriptExprClass, T, Base->getValueKind(), 2761 OK_MatrixComponent) { 2762 SubExprs[BASE] = Base; 2763 SubExprs[ROW_IDX] = RowIdx; 2764 SubExprs[COLUMN_IDX] = ColumnIdx; 2765 ArrayOrMatrixSubscriptExprBits.RBracketLoc = RBracketLoc; 2766 setDependence(computeDependence(this)); 2767 } 2768 2769 /// Create an empty matrix subscript expression. 2770 explicit MatrixSubscriptExpr(EmptyShell Shell) 2771 : Expr(MatrixSubscriptExprClass, Shell) {} 2772 2773 bool isIncomplete() const { 2774 bool IsIncomplete = hasPlaceholderType(BuiltinType::IncompleteMatrixIdx); 2775 assert((SubExprs[COLUMN_IDX] || IsIncomplete) && 2776 "expressions without column index must be marked as incomplete"); 2777 return IsIncomplete; 2778 } 2779 Expr *getBase() { return cast<Expr>(SubExprs[BASE]); } 2780 const Expr *getBase() const { return cast<Expr>(SubExprs[BASE]); } 2781 void setBase(Expr *E) { SubExprs[BASE] = E; } 2782 2783 Expr *getRowIdx() { return cast<Expr>(SubExprs[ROW_IDX]); } 2784 const Expr *getRowIdx() const { return cast<Expr>(SubExprs[ROW_IDX]); } 2785 void setRowIdx(Expr *E) { SubExprs[ROW_IDX] = E; } 2786 2787 Expr *getColumnIdx() { return cast_or_null<Expr>(SubExprs[COLUMN_IDX]); } 2788 const Expr *getColumnIdx() const { 2789 assert(!isIncomplete() && 2790 "cannot get the column index of an incomplete expression"); 2791 return cast<Expr>(SubExprs[COLUMN_IDX]); 2792 } 2793 void setColumnIdx(Expr *E) { SubExprs[COLUMN_IDX] = E; } 2794 2795 SourceLocation getBeginLoc() const LLVM_READONLY { 2796 return getBase()->getBeginLoc(); 2797 } 2798 2799 SourceLocation getEndLoc() const { return getRBracketLoc(); } 2800 2801 SourceLocation getExprLoc() const LLVM_READONLY { 2802 return getBase()->getExprLoc(); 2803 } 2804 2805 SourceLocation getRBracketLoc() const { 2806 return ArrayOrMatrixSubscriptExprBits.RBracketLoc; 2807 } 2808 void setRBracketLoc(SourceLocation L) { 2809 ArrayOrMatrixSubscriptExprBits.RBracketLoc = L; 2810 } 2811 2812 static bool classof(const Stmt *T) { 2813 return T->getStmtClass() == MatrixSubscriptExprClass; 2814 } 2815 2816 // Iterators 2817 child_range children() { 2818 return child_range(&SubExprs[0], &SubExprs[0] + END_EXPR); 2819 } 2820 const_child_range children() const { 2821 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR); 2822 } 2823 }; 2824 2825 /// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]). 2826 /// CallExpr itself represents a normal function call, e.g., "f(x, 2)", 2827 /// while its subclasses may represent alternative syntax that (semantically) 2828 /// results in a function call. For example, CXXOperatorCallExpr is 2829 /// a subclass for overloaded operator calls that use operator syntax, e.g., 2830 /// "str1 + str2" to resolve to a function call. 2831 class CallExpr : public Expr { 2832 enum { FN = 0, PREARGS_START = 1 }; 2833 2834 /// The number of arguments in the call expression. 2835 unsigned NumArgs; 2836 2837 /// The location of the right parentheses. This has a different meaning for 2838 /// the derived classes of CallExpr. 2839 SourceLocation RParenLoc; 2840 2841 // CallExpr store some data in trailing objects. However since CallExpr 2842 // is used a base of other expression classes we cannot use 2843 // llvm::TrailingObjects. Instead we manually perform the pointer arithmetic 2844 // and casts. 2845 // 2846 // The trailing objects are in order: 2847 // 2848 // * A single "Stmt *" for the callee expression. 2849 // 2850 // * An array of getNumPreArgs() "Stmt *" for the pre-argument expressions. 2851 // 2852 // * An array of getNumArgs() "Stmt *" for the argument expressions. 2853 // 2854 // * An optional of type FPOptionsOverride. 2855 // 2856 // Note that we store the offset in bytes from the this pointer to the start 2857 // of the trailing objects. It would be perfectly possible to compute it 2858 // based on the dynamic kind of the CallExpr. However 1.) we have plenty of 2859 // space in the bit-fields of Stmt. 2.) It was benchmarked to be faster to 2860 // compute this once and then load the offset from the bit-fields of Stmt, 2861 // instead of re-computing the offset each time the trailing objects are 2862 // accessed. 2863 2864 /// Return a pointer to the start of the trailing array of "Stmt *". 2865 Stmt **getTrailingStmts() { 2866 return reinterpret_cast<Stmt **>(reinterpret_cast<char *>(this) + 2867 CallExprBits.OffsetToTrailingObjects); 2868 } 2869 Stmt *const *getTrailingStmts() const { 2870 return const_cast<CallExpr *>(this)->getTrailingStmts(); 2871 } 2872 2873 /// Map a statement class to the appropriate offset in bytes from the 2874 /// this pointer to the trailing objects. 2875 static unsigned offsetToTrailingObjects(StmtClass SC); 2876 2877 unsigned getSizeOfTrailingStmts() const { 2878 return (1 + getNumPreArgs() + getNumArgs()) * sizeof(Stmt *); 2879 } 2880 2881 size_t getOffsetOfTrailingFPFeatures() const { 2882 assert(hasStoredFPFeatures()); 2883 return CallExprBits.OffsetToTrailingObjects + getSizeOfTrailingStmts(); 2884 } 2885 2886 public: 2887 enum class ADLCallKind : bool { NotADL, UsesADL }; 2888 static constexpr ADLCallKind NotADL = ADLCallKind::NotADL; 2889 static constexpr ADLCallKind UsesADL = ADLCallKind::UsesADL; 2890 2891 protected: 2892 /// Build a call expression, assuming that appropriate storage has been 2893 /// allocated for the trailing objects. 2894 CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs, 2895 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK, 2896 SourceLocation RParenLoc, FPOptionsOverride FPFeatures, 2897 unsigned MinNumArgs, ADLCallKind UsesADL); 2898 2899 /// Build an empty call expression, for deserialization. 2900 CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs, 2901 bool hasFPFeatures, EmptyShell Empty); 2902 2903 /// Return the size in bytes needed for the trailing objects. 2904 /// Used by the derived classes to allocate the right amount of storage. 2905 static unsigned sizeOfTrailingObjects(unsigned NumPreArgs, unsigned NumArgs, 2906 bool HasFPFeatures) { 2907 return (1 + NumPreArgs + NumArgs) * sizeof(Stmt *) + 2908 HasFPFeatures * sizeof(FPOptionsOverride); 2909 } 2910 2911 Stmt *getPreArg(unsigned I) { 2912 assert(I < getNumPreArgs() && "Prearg access out of range!"); 2913 return getTrailingStmts()[PREARGS_START + I]; 2914 } 2915 const Stmt *getPreArg(unsigned I) const { 2916 assert(I < getNumPreArgs() && "Prearg access out of range!"); 2917 return getTrailingStmts()[PREARGS_START + I]; 2918 } 2919 void setPreArg(unsigned I, Stmt *PreArg) { 2920 assert(I < getNumPreArgs() && "Prearg access out of range!"); 2921 getTrailingStmts()[PREARGS_START + I] = PreArg; 2922 } 2923 2924 unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; } 2925 2926 /// Return a pointer to the trailing FPOptions 2927 FPOptionsOverride *getTrailingFPFeatures() { 2928 assert(hasStoredFPFeatures()); 2929 return reinterpret_cast<FPOptionsOverride *>( 2930 reinterpret_cast<char *>(this) + CallExprBits.OffsetToTrailingObjects + 2931 getSizeOfTrailingStmts()); 2932 } 2933 const FPOptionsOverride *getTrailingFPFeatures() const { 2934 assert(hasStoredFPFeatures()); 2935 return reinterpret_cast<const FPOptionsOverride *>( 2936 reinterpret_cast<const char *>(this) + 2937 CallExprBits.OffsetToTrailingObjects + getSizeOfTrailingStmts()); 2938 } 2939 2940 public: 2941 /// Create a call expression. 2942 /// \param Fn The callee expression, 2943 /// \param Args The argument array, 2944 /// \param Ty The type of the call expression (which is *not* the return 2945 /// type in general), 2946 /// \param VK The value kind of the call expression (lvalue, rvalue, ...), 2947 /// \param RParenLoc The location of the right parenthesis in the call 2948 /// expression. 2949 /// \param FPFeatures Floating-point features associated with the call, 2950 /// \param MinNumArgs Specifies the minimum number of arguments. The actual 2951 /// number of arguments will be the greater of Args.size() 2952 /// and MinNumArgs. This is used in a few places to allocate 2953 /// enough storage for the default arguments. 2954 /// \param UsesADL Specifies whether the callee was found through 2955 /// argument-dependent lookup. 2956 /// 2957 /// Note that you can use CreateTemporary if you need a temporary call 2958 /// expression on the stack. 2959 static CallExpr *Create(const ASTContext &Ctx, Expr *Fn, 2960 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK, 2961 SourceLocation RParenLoc, 2962 FPOptionsOverride FPFeatures, unsigned MinNumArgs = 0, 2963 ADLCallKind UsesADL = NotADL); 2964 2965 /// Create a temporary call expression with no arguments in the memory 2966 /// pointed to by Mem. Mem must points to at least sizeof(CallExpr) 2967 /// + sizeof(Stmt *) bytes of storage, aligned to alignof(CallExpr): 2968 /// 2969 /// \code{.cpp} 2970 /// alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)]; 2971 /// CallExpr *TheCall = CallExpr::CreateTemporary(Buffer, etc); 2972 /// \endcode 2973 static CallExpr *CreateTemporary(void *Mem, Expr *Fn, QualType Ty, 2974 ExprValueKind VK, SourceLocation RParenLoc, 2975 ADLCallKind UsesADL = NotADL); 2976 2977 /// Create an empty call expression, for deserialization. 2978 static CallExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumArgs, 2979 bool HasFPFeatures, EmptyShell Empty); 2980 2981 Expr *getCallee() { return cast<Expr>(getTrailingStmts()[FN]); } 2982 const Expr *getCallee() const { return cast<Expr>(getTrailingStmts()[FN]); } 2983 void setCallee(Expr *F) { getTrailingStmts()[FN] = F; } 2984 2985 ADLCallKind getADLCallKind() const { 2986 return static_cast<ADLCallKind>(CallExprBits.UsesADL); 2987 } 2988 void setADLCallKind(ADLCallKind V = UsesADL) { 2989 CallExprBits.UsesADL = static_cast<bool>(V); 2990 } 2991 bool usesADL() const { return getADLCallKind() == UsesADL; } 2992 2993 bool hasStoredFPFeatures() const { return CallExprBits.HasFPFeatures; } 2994 2995 Decl *getCalleeDecl() { return getCallee()->getReferencedDeclOfCallee(); } 2996 const Decl *getCalleeDecl() const { 2997 return getCallee()->getReferencedDeclOfCallee(); 2998 } 2999 3000 /// If the callee is a FunctionDecl, return it. Otherwise return null. 3001 FunctionDecl *getDirectCallee() { 3002 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl()); 3003 } 3004 const FunctionDecl *getDirectCallee() const { 3005 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl()); 3006 } 3007 3008 /// getNumArgs - Return the number of actual arguments to this call. 3009 unsigned getNumArgs() const { return NumArgs; } 3010 3011 /// Retrieve the call arguments. 3012 Expr **getArgs() { 3013 return reinterpret_cast<Expr **>(getTrailingStmts() + PREARGS_START + 3014 getNumPreArgs()); 3015 } 3016 const Expr *const *getArgs() const { 3017 return reinterpret_cast<const Expr *const *>( 3018 getTrailingStmts() + PREARGS_START + getNumPreArgs()); 3019 } 3020 3021 /// getArg - Return the specified argument. 3022 Expr *getArg(unsigned Arg) { 3023 assert(Arg < getNumArgs() && "Arg access out of range!"); 3024 return getArgs()[Arg]; 3025 } 3026 const Expr *getArg(unsigned Arg) const { 3027 assert(Arg < getNumArgs() && "Arg access out of range!"); 3028 return getArgs()[Arg]; 3029 } 3030 3031 /// setArg - Set the specified argument. 3032 /// ! the dependence bits might be stale after calling this setter, it is 3033 /// *caller*'s responsibility to recompute them by calling 3034 /// computeDependence(). 3035 void setArg(unsigned Arg, Expr *ArgExpr) { 3036 assert(Arg < getNumArgs() && "Arg access out of range!"); 3037 getArgs()[Arg] = ArgExpr; 3038 } 3039 3040 /// Compute and set dependence bits. 3041 void computeDependence() { 3042 setDependence(clang::computeDependence( 3043 this, llvm::ArrayRef( 3044 reinterpret_cast<Expr **>(getTrailingStmts() + PREARGS_START), 3045 getNumPreArgs()))); 3046 } 3047 3048 /// Reduce the number of arguments in this call expression. This is used for 3049 /// example during error recovery to drop extra arguments. There is no way 3050 /// to perform the opposite because: 1.) We don't track how much storage 3051 /// we have for the argument array 2.) This would potentially require growing 3052 /// the argument array, something we cannot support since the arguments are 3053 /// stored in a trailing array. 3054 void shrinkNumArgs(unsigned NewNumArgs) { 3055 assert((NewNumArgs <= getNumArgs()) && 3056 "shrinkNumArgs cannot increase the number of arguments!"); 3057 NumArgs = NewNumArgs; 3058 } 3059 3060 /// Bluntly set a new number of arguments without doing any checks whatsoever. 3061 /// Only used during construction of a CallExpr in a few places in Sema. 3062 /// FIXME: Find a way to remove it. 3063 void setNumArgsUnsafe(unsigned NewNumArgs) { NumArgs = NewNumArgs; } 3064 3065 typedef ExprIterator arg_iterator; 3066 typedef ConstExprIterator const_arg_iterator; 3067 typedef llvm::iterator_range<arg_iterator> arg_range; 3068 typedef llvm::iterator_range<const_arg_iterator> const_arg_range; 3069 3070 arg_range arguments() { return arg_range(arg_begin(), arg_end()); } 3071 const_arg_range arguments() const { 3072 return const_arg_range(arg_begin(), arg_end()); 3073 } 3074 3075 arg_iterator arg_begin() { 3076 return getTrailingStmts() + PREARGS_START + getNumPreArgs(); 3077 } 3078 arg_iterator arg_end() { return arg_begin() + getNumArgs(); } 3079 3080 const_arg_iterator arg_begin() const { 3081 return getTrailingStmts() + PREARGS_START + getNumPreArgs(); 3082 } 3083 const_arg_iterator arg_end() const { return arg_begin() + getNumArgs(); } 3084 3085 /// This method provides fast access to all the subexpressions of 3086 /// a CallExpr without going through the slower virtual child_iterator 3087 /// interface. This provides efficient reverse iteration of the 3088 /// subexpressions. This is currently used for CFG construction. 3089 ArrayRef<Stmt *> getRawSubExprs() { 3090 return llvm::ArrayRef(getTrailingStmts(), 3091 PREARGS_START + getNumPreArgs() + getNumArgs()); 3092 } 3093 3094 /// Get FPOptionsOverride from trailing storage. 3095 FPOptionsOverride getStoredFPFeatures() const { 3096 assert(hasStoredFPFeatures()); 3097 return *getTrailingFPFeatures(); 3098 } 3099 /// Set FPOptionsOverride in trailing storage. Used only by Serialization. 3100 void setStoredFPFeatures(FPOptionsOverride F) { 3101 assert(hasStoredFPFeatures()); 3102 *getTrailingFPFeatures() = F; 3103 } 3104 3105 /// Get the FP features status of this operator. Only meaningful for 3106 /// operations on floating point types. 3107 FPOptions getFPFeaturesInEffect(const LangOptions &LO) const { 3108 if (hasStoredFPFeatures()) 3109 return getStoredFPFeatures().applyOverrides(LO); 3110 return FPOptions::defaultWithoutTrailingStorage(LO); 3111 } 3112 3113 FPOptionsOverride getFPFeatures() const { 3114 if (hasStoredFPFeatures()) 3115 return getStoredFPFeatures(); 3116 return FPOptionsOverride(); 3117 } 3118 3119 /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID 3120 /// of the callee. If not, return 0. 3121 unsigned getBuiltinCallee() const; 3122 3123 /// Returns \c true if this is a call to a builtin which does not 3124 /// evaluate side-effects within its arguments. 3125 bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const; 3126 3127 /// getCallReturnType - Get the return type of the call expr. This is not 3128 /// always the type of the expr itself, if the return type is a reference 3129 /// type. 3130 QualType getCallReturnType(const ASTContext &Ctx) const; 3131 3132 /// Returns the WarnUnusedResultAttr that is either declared on the called 3133 /// function, or its return type declaration. 3134 const Attr *getUnusedResultAttr(const ASTContext &Ctx) const; 3135 3136 /// Returns true if this call expression should warn on unused results. 3137 bool hasUnusedResultAttr(const ASTContext &Ctx) const { 3138 return getUnusedResultAttr(Ctx) != nullptr; 3139 } 3140 3141 SourceLocation getRParenLoc() const { return RParenLoc; } 3142 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 3143 3144 SourceLocation getBeginLoc() const LLVM_READONLY; 3145 SourceLocation getEndLoc() const LLVM_READONLY; 3146 3147 /// Return true if this is a call to __assume() or __builtin_assume() with 3148 /// a non-value-dependent constant parameter evaluating as false. 3149 bool isBuiltinAssumeFalse(const ASTContext &Ctx) const; 3150 3151 /// Used by Sema to implement MSVC-compatible delayed name lookup. 3152 /// (Usually Exprs themselves should set dependence). 3153 void markDependentForPostponedNameLookup() { 3154 setDependence(getDependence() | ExprDependence::TypeValueInstantiation); 3155 } 3156 3157 bool isCallToStdMove() const; 3158 3159 static bool classof(const Stmt *T) { 3160 return T->getStmtClass() >= firstCallExprConstant && 3161 T->getStmtClass() <= lastCallExprConstant; 3162 } 3163 3164 // Iterators 3165 child_range children() { 3166 return child_range(getTrailingStmts(), getTrailingStmts() + PREARGS_START + 3167 getNumPreArgs() + getNumArgs()); 3168 } 3169 3170 const_child_range children() const { 3171 return const_child_range(getTrailingStmts(), 3172 getTrailingStmts() + PREARGS_START + 3173 getNumPreArgs() + getNumArgs()); 3174 } 3175 }; 3176 3177 /// Extra data stored in some MemberExpr objects. 3178 struct MemberExprNameQualifier { 3179 /// The nested-name-specifier that qualifies the name, including 3180 /// source-location information. 3181 NestedNameSpecifierLoc QualifierLoc; 3182 3183 /// The DeclAccessPair through which the MemberDecl was found due to 3184 /// name qualifiers. 3185 DeclAccessPair FoundDecl; 3186 }; 3187 3188 /// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F. 3189 /// 3190 class MemberExpr final 3191 : public Expr, 3192 private llvm::TrailingObjects<MemberExpr, MemberExprNameQualifier, 3193 ASTTemplateKWAndArgsInfo, 3194 TemplateArgumentLoc> { 3195 friend class ASTReader; 3196 friend class ASTStmtReader; 3197 friend class ASTStmtWriter; 3198 friend TrailingObjects; 3199 3200 /// Base - the expression for the base pointer or structure references. In 3201 /// X.F, this is "X". 3202 Stmt *Base; 3203 3204 /// MemberDecl - This is the decl being referenced by the field/member name. 3205 /// In X.F, this is the decl referenced by F. 3206 ValueDecl *MemberDecl; 3207 3208 /// MemberDNLoc - Provides source/type location info for the 3209 /// declaration name embedded in MemberDecl. 3210 DeclarationNameLoc MemberDNLoc; 3211 3212 /// MemberLoc - This is the location of the member name. 3213 SourceLocation MemberLoc; 3214 3215 size_t numTrailingObjects(OverloadToken<MemberExprNameQualifier>) const { 3216 return hasQualifierOrFoundDecl(); 3217 } 3218 3219 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const { 3220 return hasTemplateKWAndArgsInfo(); 3221 } 3222 3223 bool hasQualifierOrFoundDecl() const { 3224 return MemberExprBits.HasQualifierOrFoundDecl; 3225 } 3226 3227 bool hasTemplateKWAndArgsInfo() const { 3228 return MemberExprBits.HasTemplateKWAndArgsInfo; 3229 } 3230 3231 MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc, 3232 ValueDecl *MemberDecl, const DeclarationNameInfo &NameInfo, 3233 QualType T, ExprValueKind VK, ExprObjectKind OK, 3234 NonOdrUseReason NOUR); 3235 MemberExpr(EmptyShell Empty) 3236 : Expr(MemberExprClass, Empty), Base(), MemberDecl() {} 3237 3238 public: 3239 static MemberExpr *Create(const ASTContext &C, Expr *Base, bool IsArrow, 3240 SourceLocation OperatorLoc, 3241 NestedNameSpecifierLoc QualifierLoc, 3242 SourceLocation TemplateKWLoc, ValueDecl *MemberDecl, 3243 DeclAccessPair FoundDecl, 3244 DeclarationNameInfo MemberNameInfo, 3245 const TemplateArgumentListInfo *TemplateArgs, 3246 QualType T, ExprValueKind VK, ExprObjectKind OK, 3247 NonOdrUseReason NOUR); 3248 3249 /// Create an implicit MemberExpr, with no location, qualifier, template 3250 /// arguments, and so on. Suitable only for non-static member access. 3251 static MemberExpr *CreateImplicit(const ASTContext &C, Expr *Base, 3252 bool IsArrow, ValueDecl *MemberDecl, 3253 QualType T, ExprValueKind VK, 3254 ExprObjectKind OK) { 3255 return Create(C, Base, IsArrow, SourceLocation(), NestedNameSpecifierLoc(), 3256 SourceLocation(), MemberDecl, 3257 DeclAccessPair::make(MemberDecl, MemberDecl->getAccess()), 3258 DeclarationNameInfo(), nullptr, T, VK, OK, NOUR_None); 3259 } 3260 3261 static MemberExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier, 3262 bool HasFoundDecl, 3263 bool HasTemplateKWAndArgsInfo, 3264 unsigned NumTemplateArgs); 3265 3266 void setBase(Expr *E) { Base = E; } 3267 Expr *getBase() const { return cast<Expr>(Base); } 3268 3269 /// Retrieve the member declaration to which this expression refers. 3270 /// 3271 /// The returned declaration will be a FieldDecl or (in C++) a VarDecl (for 3272 /// static data members), a CXXMethodDecl, or an EnumConstantDecl. 3273 ValueDecl *getMemberDecl() const { return MemberDecl; } 3274 void setMemberDecl(ValueDecl *D); 3275 3276 /// Retrieves the declaration found by lookup. 3277 DeclAccessPair getFoundDecl() const { 3278 if (!hasQualifierOrFoundDecl()) 3279 return DeclAccessPair::make(getMemberDecl(), 3280 getMemberDecl()->getAccess()); 3281 return getTrailingObjects<MemberExprNameQualifier>()->FoundDecl; 3282 } 3283 3284 /// Determines whether this member expression actually had 3285 /// a C++ nested-name-specifier prior to the name of the member, e.g., 3286 /// x->Base::foo. 3287 bool hasQualifier() const { return getQualifier() != nullptr; } 3288 3289 /// If the member name was qualified, retrieves the 3290 /// nested-name-specifier that precedes the member name, with source-location 3291 /// information. 3292 NestedNameSpecifierLoc getQualifierLoc() const { 3293 if (!hasQualifierOrFoundDecl()) 3294 return NestedNameSpecifierLoc(); 3295 return getTrailingObjects<MemberExprNameQualifier>()->QualifierLoc; 3296 } 3297 3298 /// If the member name was qualified, retrieves the 3299 /// nested-name-specifier that precedes the member name. Otherwise, returns 3300 /// NULL. 3301 NestedNameSpecifier *getQualifier() const { 3302 return getQualifierLoc().getNestedNameSpecifier(); 3303 } 3304 3305 /// Retrieve the location of the template keyword preceding 3306 /// the member name, if any. 3307 SourceLocation getTemplateKeywordLoc() const { 3308 if (!hasTemplateKWAndArgsInfo()) 3309 return SourceLocation(); 3310 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc; 3311 } 3312 3313 /// Retrieve the location of the left angle bracket starting the 3314 /// explicit template argument list following the member name, if any. 3315 SourceLocation getLAngleLoc() const { 3316 if (!hasTemplateKWAndArgsInfo()) 3317 return SourceLocation(); 3318 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc; 3319 } 3320 3321 /// Retrieve the location of the right angle bracket ending the 3322 /// explicit template argument list following the member name, if any. 3323 SourceLocation getRAngleLoc() const { 3324 if (!hasTemplateKWAndArgsInfo()) 3325 return SourceLocation(); 3326 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc; 3327 } 3328 3329 /// Determines whether the member name was preceded by the template keyword. 3330 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); } 3331 3332 /// Determines whether the member name was followed by an 3333 /// explicit template argument list. 3334 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); } 3335 3336 /// Copies the template arguments (if present) into the given 3337 /// structure. 3338 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const { 3339 if (hasExplicitTemplateArgs()) 3340 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto( 3341 getTrailingObjects<TemplateArgumentLoc>(), List); 3342 } 3343 3344 /// Retrieve the template arguments provided as part of this 3345 /// template-id. 3346 const TemplateArgumentLoc *getTemplateArgs() const { 3347 if (!hasExplicitTemplateArgs()) 3348 return nullptr; 3349 3350 return getTrailingObjects<TemplateArgumentLoc>(); 3351 } 3352 3353 /// Retrieve the number of template arguments provided as part of this 3354 /// template-id. 3355 unsigned getNumTemplateArgs() const { 3356 if (!hasExplicitTemplateArgs()) 3357 return 0; 3358 3359 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs; 3360 } 3361 3362 ArrayRef<TemplateArgumentLoc> template_arguments() const { 3363 return {getTemplateArgs(), getNumTemplateArgs()}; 3364 } 3365 3366 /// Retrieve the member declaration name info. 3367 DeclarationNameInfo getMemberNameInfo() const { 3368 return DeclarationNameInfo(MemberDecl->getDeclName(), 3369 MemberLoc, MemberDNLoc); 3370 } 3371 3372 SourceLocation getOperatorLoc() const { return MemberExprBits.OperatorLoc; } 3373 3374 bool isArrow() const { return MemberExprBits.IsArrow; } 3375 void setArrow(bool A) { MemberExprBits.IsArrow = A; } 3376 3377 /// getMemberLoc - Return the location of the "member", in X->F, it is the 3378 /// location of 'F'. 3379 SourceLocation getMemberLoc() const { return MemberLoc; } 3380 void setMemberLoc(SourceLocation L) { MemberLoc = L; } 3381 3382 SourceLocation getBeginLoc() const LLVM_READONLY; 3383 SourceLocation getEndLoc() const LLVM_READONLY; 3384 3385 SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; } 3386 3387 /// Determine whether the base of this explicit is implicit. 3388 bool isImplicitAccess() const { 3389 return getBase() && getBase()->isImplicitCXXThis(); 3390 } 3391 3392 /// Returns true if this member expression refers to a method that 3393 /// was resolved from an overloaded set having size greater than 1. 3394 bool hadMultipleCandidates() const { 3395 return MemberExprBits.HadMultipleCandidates; 3396 } 3397 /// Sets the flag telling whether this expression refers to 3398 /// a method that was resolved from an overloaded set having size 3399 /// greater than 1. 3400 void setHadMultipleCandidates(bool V = true) { 3401 MemberExprBits.HadMultipleCandidates = V; 3402 } 3403 3404 /// Returns true if virtual dispatch is performed. 3405 /// If the member access is fully qualified, (i.e. X::f()), virtual 3406 /// dispatching is not performed. In -fapple-kext mode qualified 3407 /// calls to virtual method will still go through the vtable. 3408 bool performsVirtualDispatch(const LangOptions &LO) const { 3409 return LO.AppleKext || !hasQualifier(); 3410 } 3411 3412 /// Is this expression a non-odr-use reference, and if so, why? 3413 /// This is only meaningful if the named member is a static member. 3414 NonOdrUseReason isNonOdrUse() const { 3415 return static_cast<NonOdrUseReason>(MemberExprBits.NonOdrUseReason); 3416 } 3417 3418 static bool classof(const Stmt *T) { 3419 return T->getStmtClass() == MemberExprClass; 3420 } 3421 3422 // Iterators 3423 child_range children() { return child_range(&Base, &Base+1); } 3424 const_child_range children() const { 3425 return const_child_range(&Base, &Base + 1); 3426 } 3427 }; 3428 3429 /// CompoundLiteralExpr - [C99 6.5.2.5] 3430 /// 3431 class CompoundLiteralExpr : public Expr { 3432 /// LParenLoc - If non-null, this is the location of the left paren in a 3433 /// compound literal like "(int){4}". This can be null if this is a 3434 /// synthesized compound expression. 3435 SourceLocation LParenLoc; 3436 3437 /// The type as written. This can be an incomplete array type, in 3438 /// which case the actual expression type will be different. 3439 /// The int part of the pair stores whether this expr is file scope. 3440 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope; 3441 Stmt *Init; 3442 public: 3443 CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo, 3444 QualType T, ExprValueKind VK, Expr *init, bool fileScope) 3445 : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary), 3446 LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) { 3447 setDependence(computeDependence(this)); 3448 } 3449 3450 /// Construct an empty compound literal. 3451 explicit CompoundLiteralExpr(EmptyShell Empty) 3452 : Expr(CompoundLiteralExprClass, Empty) { } 3453 3454 const Expr *getInitializer() const { return cast<Expr>(Init); } 3455 Expr *getInitializer() { return cast<Expr>(Init); } 3456 void setInitializer(Expr *E) { Init = E; } 3457 3458 bool isFileScope() const { return TInfoAndScope.getInt(); } 3459 void setFileScope(bool FS) { TInfoAndScope.setInt(FS); } 3460 3461 SourceLocation getLParenLoc() const { return LParenLoc; } 3462 void setLParenLoc(SourceLocation L) { LParenLoc = L; } 3463 3464 TypeSourceInfo *getTypeSourceInfo() const { 3465 return TInfoAndScope.getPointer(); 3466 } 3467 void setTypeSourceInfo(TypeSourceInfo *tinfo) { 3468 TInfoAndScope.setPointer(tinfo); 3469 } 3470 3471 SourceLocation getBeginLoc() const LLVM_READONLY { 3472 // FIXME: Init should never be null. 3473 if (!Init) 3474 return SourceLocation(); 3475 if (LParenLoc.isInvalid()) 3476 return Init->getBeginLoc(); 3477 return LParenLoc; 3478 } 3479 SourceLocation getEndLoc() const LLVM_READONLY { 3480 // FIXME: Init should never be null. 3481 if (!Init) 3482 return SourceLocation(); 3483 return Init->getEndLoc(); 3484 } 3485 3486 static bool classof(const Stmt *T) { 3487 return T->getStmtClass() == CompoundLiteralExprClass; 3488 } 3489 3490 // Iterators 3491 child_range children() { return child_range(&Init, &Init+1); } 3492 const_child_range children() const { 3493 return const_child_range(&Init, &Init + 1); 3494 } 3495 }; 3496 3497 /// CastExpr - Base class for type casts, including both implicit 3498 /// casts (ImplicitCastExpr) and explicit casts that have some 3499 /// representation in the source code (ExplicitCastExpr's derived 3500 /// classes). 3501 class CastExpr : public Expr { 3502 Stmt *Op; 3503 3504 bool CastConsistency() const; 3505 3506 const CXXBaseSpecifier * const *path_buffer() const { 3507 return const_cast<CastExpr*>(this)->path_buffer(); 3508 } 3509 CXXBaseSpecifier **path_buffer(); 3510 3511 friend class ASTStmtReader; 3512 3513 protected: 3514 CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, const CastKind kind, 3515 Expr *op, unsigned BasePathSize, bool HasFPFeatures) 3516 : Expr(SC, ty, VK, OK_Ordinary), Op(op) { 3517 CastExprBits.Kind = kind; 3518 CastExprBits.PartOfExplicitCast = false; 3519 CastExprBits.BasePathSize = BasePathSize; 3520 assert((CastExprBits.BasePathSize == BasePathSize) && 3521 "BasePathSize overflow!"); 3522 assert(CastConsistency()); 3523 CastExprBits.HasFPFeatures = HasFPFeatures; 3524 } 3525 3526 /// Construct an empty cast. 3527 CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize, 3528 bool HasFPFeatures) 3529 : Expr(SC, Empty) { 3530 CastExprBits.PartOfExplicitCast = false; 3531 CastExprBits.BasePathSize = BasePathSize; 3532 CastExprBits.HasFPFeatures = HasFPFeatures; 3533 assert((CastExprBits.BasePathSize == BasePathSize) && 3534 "BasePathSize overflow!"); 3535 } 3536 3537 /// Return a pointer to the trailing FPOptions. 3538 /// \pre hasStoredFPFeatures() == true 3539 FPOptionsOverride *getTrailingFPFeatures(); 3540 const FPOptionsOverride *getTrailingFPFeatures() const { 3541 return const_cast<CastExpr *>(this)->getTrailingFPFeatures(); 3542 } 3543 3544 public: 3545 CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; } 3546 void setCastKind(CastKind K) { CastExprBits.Kind = K; } 3547 3548 static const char *getCastKindName(CastKind CK); 3549 const char *getCastKindName() const { return getCastKindName(getCastKind()); } 3550 3551 Expr *getSubExpr() { return cast<Expr>(Op); } 3552 const Expr *getSubExpr() const { return cast<Expr>(Op); } 3553 void setSubExpr(Expr *E) { Op = E; } 3554 3555 /// Retrieve the cast subexpression as it was written in the source 3556 /// code, looking through any implicit casts or other intermediate nodes 3557 /// introduced by semantic analysis. 3558 Expr *getSubExprAsWritten(); 3559 const Expr *getSubExprAsWritten() const { 3560 return const_cast<CastExpr *>(this)->getSubExprAsWritten(); 3561 } 3562 3563 /// If this cast applies a user-defined conversion, retrieve the conversion 3564 /// function that it invokes. 3565 NamedDecl *getConversionFunction() const; 3566 3567 typedef CXXBaseSpecifier **path_iterator; 3568 typedef const CXXBaseSpecifier *const *path_const_iterator; 3569 bool path_empty() const { return path_size() == 0; } 3570 unsigned path_size() const { return CastExprBits.BasePathSize; } 3571 path_iterator path_begin() { return path_buffer(); } 3572 path_iterator path_end() { return path_buffer() + path_size(); } 3573 path_const_iterator path_begin() const { return path_buffer(); } 3574 path_const_iterator path_end() const { return path_buffer() + path_size(); } 3575 3576 llvm::iterator_range<path_iterator> path() { 3577 return llvm::make_range(path_begin(), path_end()); 3578 } 3579 llvm::iterator_range<path_const_iterator> path() const { 3580 return llvm::make_range(path_begin(), path_end()); 3581 } 3582 3583 const FieldDecl *getTargetUnionField() const { 3584 assert(getCastKind() == CK_ToUnion); 3585 return getTargetFieldForToUnionCast(getType(), getSubExpr()->getType()); 3586 } 3587 3588 bool hasStoredFPFeatures() const { return CastExprBits.HasFPFeatures; } 3589 3590 /// Get FPOptionsOverride from trailing storage. 3591 FPOptionsOverride getStoredFPFeatures() const { 3592 assert(hasStoredFPFeatures()); 3593 return *getTrailingFPFeatures(); 3594 } 3595 3596 /// Get the FP features status of this operation. Only meaningful for 3597 /// operations on floating point types. 3598 FPOptions getFPFeaturesInEffect(const LangOptions &LO) const { 3599 if (hasStoredFPFeatures()) 3600 return getStoredFPFeatures().applyOverrides(LO); 3601 return FPOptions::defaultWithoutTrailingStorage(LO); 3602 } 3603 3604 FPOptionsOverride getFPFeatures() const { 3605 if (hasStoredFPFeatures()) 3606 return getStoredFPFeatures(); 3607 return FPOptionsOverride(); 3608 } 3609 3610 static const FieldDecl *getTargetFieldForToUnionCast(QualType unionType, 3611 QualType opType); 3612 static const FieldDecl *getTargetFieldForToUnionCast(const RecordDecl *RD, 3613 QualType opType); 3614 3615 static bool classof(const Stmt *T) { 3616 return T->getStmtClass() >= firstCastExprConstant && 3617 T->getStmtClass() <= lastCastExprConstant; 3618 } 3619 3620 // Iterators 3621 child_range children() { return child_range(&Op, &Op+1); } 3622 const_child_range children() const { return const_child_range(&Op, &Op + 1); } 3623 }; 3624 3625 /// ImplicitCastExpr - Allows us to explicitly represent implicit type 3626 /// conversions, which have no direct representation in the original 3627 /// source code. For example: converting T[]->T*, void f()->void 3628 /// (*f)(), float->double, short->int, etc. 3629 /// 3630 /// In C, implicit casts always produce rvalues. However, in C++, an 3631 /// implicit cast whose result is being bound to a reference will be 3632 /// an lvalue or xvalue. For example: 3633 /// 3634 /// @code 3635 /// class Base { }; 3636 /// class Derived : public Base { }; 3637 /// Derived &&ref(); 3638 /// void f(Derived d) { 3639 /// Base& b = d; // initializer is an ImplicitCastExpr 3640 /// // to an lvalue of type Base 3641 /// Base&& r = ref(); // initializer is an ImplicitCastExpr 3642 /// // to an xvalue of type Base 3643 /// } 3644 /// @endcode 3645 class ImplicitCastExpr final 3646 : public CastExpr, 3647 private llvm::TrailingObjects<ImplicitCastExpr, CXXBaseSpecifier *, 3648 FPOptionsOverride> { 3649 3650 ImplicitCastExpr(QualType ty, CastKind kind, Expr *op, 3651 unsigned BasePathLength, FPOptionsOverride FPO, 3652 ExprValueKind VK) 3653 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength, 3654 FPO.requiresTrailingStorage()) { 3655 setDependence(computeDependence(this)); 3656 if (hasStoredFPFeatures()) 3657 *getTrailingFPFeatures() = FPO; 3658 } 3659 3660 /// Construct an empty implicit cast. 3661 explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize, 3662 bool HasFPFeatures) 3663 : CastExpr(ImplicitCastExprClass, Shell, PathSize, HasFPFeatures) {} 3664 3665 unsigned numTrailingObjects(OverloadToken<CXXBaseSpecifier *>) const { 3666 return path_size(); 3667 } 3668 3669 public: 3670 enum OnStack_t { OnStack }; 3671 ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op, 3672 ExprValueKind VK, FPOptionsOverride FPO) 3673 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0, 3674 FPO.requiresTrailingStorage()) { 3675 if (hasStoredFPFeatures()) 3676 *getTrailingFPFeatures() = FPO; 3677 } 3678 3679 bool isPartOfExplicitCast() const { return CastExprBits.PartOfExplicitCast; } 3680 void setIsPartOfExplicitCast(bool PartOfExplicitCast) { 3681 CastExprBits.PartOfExplicitCast = PartOfExplicitCast; 3682 } 3683 3684 static ImplicitCastExpr *Create(const ASTContext &Context, QualType T, 3685 CastKind Kind, Expr *Operand, 3686 const CXXCastPath *BasePath, 3687 ExprValueKind Cat, FPOptionsOverride FPO); 3688 3689 static ImplicitCastExpr *CreateEmpty(const ASTContext &Context, 3690 unsigned PathSize, bool HasFPFeatures); 3691 3692 SourceLocation getBeginLoc() const LLVM_READONLY { 3693 return getSubExpr()->getBeginLoc(); 3694 } 3695 SourceLocation getEndLoc() const LLVM_READONLY { 3696 return getSubExpr()->getEndLoc(); 3697 } 3698 3699 static bool classof(const Stmt *T) { 3700 return T->getStmtClass() == ImplicitCastExprClass; 3701 } 3702 3703 friend TrailingObjects; 3704 friend class CastExpr; 3705 }; 3706 3707 /// ExplicitCastExpr - An explicit cast written in the source 3708 /// code. 3709 /// 3710 /// This class is effectively an abstract class, because it provides 3711 /// the basic representation of an explicitly-written cast without 3712 /// specifying which kind of cast (C cast, functional cast, static 3713 /// cast, etc.) was written; specific derived classes represent the 3714 /// particular style of cast and its location information. 3715 /// 3716 /// Unlike implicit casts, explicit cast nodes have two different 3717 /// types: the type that was written into the source code, and the 3718 /// actual type of the expression as determined by semantic 3719 /// analysis. These types may differ slightly. For example, in C++ one 3720 /// can cast to a reference type, which indicates that the resulting 3721 /// expression will be an lvalue or xvalue. The reference type, however, 3722 /// will not be used as the type of the expression. 3723 class ExplicitCastExpr : public CastExpr { 3724 /// TInfo - Source type info for the (written) type 3725 /// this expression is casting to. 3726 TypeSourceInfo *TInfo; 3727 3728 protected: 3729 ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK, 3730 CastKind kind, Expr *op, unsigned PathSize, 3731 bool HasFPFeatures, TypeSourceInfo *writtenTy) 3732 : CastExpr(SC, exprTy, VK, kind, op, PathSize, HasFPFeatures), 3733 TInfo(writtenTy) { 3734 setDependence(computeDependence(this)); 3735 } 3736 3737 /// Construct an empty explicit cast. 3738 ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize, 3739 bool HasFPFeatures) 3740 : CastExpr(SC, Shell, PathSize, HasFPFeatures) {} 3741 3742 public: 3743 /// getTypeInfoAsWritten - Returns the type source info for the type 3744 /// that this expression is casting to. 3745 TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; } 3746 void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; } 3747 3748 /// getTypeAsWritten - Returns the type that this expression is 3749 /// casting to, as written in the source code. 3750 QualType getTypeAsWritten() const { return TInfo->getType(); } 3751 3752 static bool classof(const Stmt *T) { 3753 return T->getStmtClass() >= firstExplicitCastExprConstant && 3754 T->getStmtClass() <= lastExplicitCastExprConstant; 3755 } 3756 }; 3757 3758 /// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style 3759 /// cast in C++ (C++ [expr.cast]), which uses the syntax 3760 /// (Type)expr. For example: @c (int)f. 3761 class CStyleCastExpr final 3762 : public ExplicitCastExpr, 3763 private llvm::TrailingObjects<CStyleCastExpr, CXXBaseSpecifier *, 3764 FPOptionsOverride> { 3765 SourceLocation LPLoc; // the location of the left paren 3766 SourceLocation RPLoc; // the location of the right paren 3767 3768 CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op, 3769 unsigned PathSize, FPOptionsOverride FPO, 3770 TypeSourceInfo *writtenTy, SourceLocation l, SourceLocation r) 3771 : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize, 3772 FPO.requiresTrailingStorage(), writtenTy), 3773 LPLoc(l), RPLoc(r) { 3774 if (hasStoredFPFeatures()) 3775 *getTrailingFPFeatures() = FPO; 3776 } 3777 3778 /// Construct an empty C-style explicit cast. 3779 explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize, 3780 bool HasFPFeatures) 3781 : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize, HasFPFeatures) {} 3782 3783 unsigned numTrailingObjects(OverloadToken<CXXBaseSpecifier *>) const { 3784 return path_size(); 3785 } 3786 3787 public: 3788 static CStyleCastExpr * 3789 Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K, 3790 Expr *Op, const CXXCastPath *BasePath, FPOptionsOverride FPO, 3791 TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation R); 3792 3793 static CStyleCastExpr *CreateEmpty(const ASTContext &Context, 3794 unsigned PathSize, bool HasFPFeatures); 3795 3796 SourceLocation getLParenLoc() const { return LPLoc; } 3797 void setLParenLoc(SourceLocation L) { LPLoc = L; } 3798 3799 SourceLocation getRParenLoc() const { return RPLoc; } 3800 void setRParenLoc(SourceLocation L) { RPLoc = L; } 3801 3802 SourceLocation getBeginLoc() const LLVM_READONLY { return LPLoc; } 3803 SourceLocation getEndLoc() const LLVM_READONLY { 3804 return getSubExpr()->getEndLoc(); 3805 } 3806 3807 static bool classof(const Stmt *T) { 3808 return T->getStmtClass() == CStyleCastExprClass; 3809 } 3810 3811 friend TrailingObjects; 3812 friend class CastExpr; 3813 }; 3814 3815 /// A builtin binary operation expression such as "x + y" or "x <= y". 3816 /// 3817 /// This expression node kind describes a builtin binary operation, 3818 /// such as "x + y" for integer values "x" and "y". The operands will 3819 /// already have been converted to appropriate types (e.g., by 3820 /// performing promotions or conversions). 3821 /// 3822 /// In C++, where operators may be overloaded, a different kind of 3823 /// expression node (CXXOperatorCallExpr) is used to express the 3824 /// invocation of an overloaded operator with operator syntax. Within 3825 /// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is 3826 /// used to store an expression "x + y" depends on the subexpressions 3827 /// for x and y. If neither x or y is type-dependent, and the "+" 3828 /// operator resolves to a built-in operation, BinaryOperator will be 3829 /// used to express the computation (x and y may still be 3830 /// value-dependent). If either x or y is type-dependent, or if the 3831 /// "+" resolves to an overloaded operator, CXXOperatorCallExpr will 3832 /// be used to express the computation. 3833 class BinaryOperator : public Expr { 3834 enum { LHS, RHS, END_EXPR }; 3835 Stmt *SubExprs[END_EXPR]; 3836 3837 public: 3838 typedef BinaryOperatorKind Opcode; 3839 3840 protected: 3841 size_t offsetOfTrailingStorage() const; 3842 3843 /// Return a pointer to the trailing FPOptions 3844 FPOptionsOverride *getTrailingFPFeatures() { 3845 assert(BinaryOperatorBits.HasFPFeatures); 3846 return reinterpret_cast<FPOptionsOverride *>( 3847 reinterpret_cast<char *>(this) + offsetOfTrailingStorage()); 3848 } 3849 const FPOptionsOverride *getTrailingFPFeatures() const { 3850 assert(BinaryOperatorBits.HasFPFeatures); 3851 return reinterpret_cast<const FPOptionsOverride *>( 3852 reinterpret_cast<const char *>(this) + offsetOfTrailingStorage()); 3853 } 3854 3855 /// Build a binary operator, assuming that appropriate storage has been 3856 /// allocated for the trailing objects when needed. 3857 BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, Opcode opc, 3858 QualType ResTy, ExprValueKind VK, ExprObjectKind OK, 3859 SourceLocation opLoc, FPOptionsOverride FPFeatures); 3860 3861 /// Construct an empty binary operator. 3862 explicit BinaryOperator(EmptyShell Empty) : Expr(BinaryOperatorClass, Empty) { 3863 BinaryOperatorBits.Opc = BO_Comma; 3864 } 3865 3866 public: 3867 static BinaryOperator *CreateEmpty(const ASTContext &C, bool hasFPFeatures); 3868 3869 static BinaryOperator *Create(const ASTContext &C, Expr *lhs, Expr *rhs, 3870 Opcode opc, QualType ResTy, ExprValueKind VK, 3871 ExprObjectKind OK, SourceLocation opLoc, 3872 FPOptionsOverride FPFeatures); 3873 SourceLocation getExprLoc() const { return getOperatorLoc(); } 3874 SourceLocation getOperatorLoc() const { return BinaryOperatorBits.OpLoc; } 3875 void setOperatorLoc(SourceLocation L) { BinaryOperatorBits.OpLoc = L; } 3876 3877 Opcode getOpcode() const { 3878 return static_cast<Opcode>(BinaryOperatorBits.Opc); 3879 } 3880 void setOpcode(Opcode Opc) { BinaryOperatorBits.Opc = Opc; } 3881 3882 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } 3883 void setLHS(Expr *E) { SubExprs[LHS] = E; } 3884 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } 3885 void setRHS(Expr *E) { SubExprs[RHS] = E; } 3886 3887 SourceLocation getBeginLoc() const LLVM_READONLY { 3888 return getLHS()->getBeginLoc(); 3889 } 3890 SourceLocation getEndLoc() const LLVM_READONLY { 3891 return getRHS()->getEndLoc(); 3892 } 3893 3894 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it 3895 /// corresponds to, e.g. "<<=". 3896 static StringRef getOpcodeStr(Opcode Op); 3897 3898 StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); } 3899 3900 /// Retrieve the binary opcode that corresponds to the given 3901 /// overloaded operator. 3902 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO); 3903 3904 /// Retrieve the overloaded operator kind that corresponds to 3905 /// the given binary opcode. 3906 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc); 3907 3908 /// predicates to categorize the respective opcodes. 3909 static bool isPtrMemOp(Opcode Opc) { 3910 return Opc == BO_PtrMemD || Opc == BO_PtrMemI; 3911 } 3912 bool isPtrMemOp() const { return isPtrMemOp(getOpcode()); } 3913 3914 static bool isMultiplicativeOp(Opcode Opc) { 3915 return Opc >= BO_Mul && Opc <= BO_Rem; 3916 } 3917 bool isMultiplicativeOp() const { return isMultiplicativeOp(getOpcode()); } 3918 static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; } 3919 bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); } 3920 static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; } 3921 bool isShiftOp() const { return isShiftOp(getOpcode()); } 3922 3923 static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; } 3924 bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); } 3925 3926 static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; } 3927 bool isRelationalOp() const { return isRelationalOp(getOpcode()); } 3928 3929 static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; } 3930 bool isEqualityOp() const { return isEqualityOp(getOpcode()); } 3931 3932 static bool isComparisonOp(Opcode Opc) { return Opc >= BO_Cmp && Opc<=BO_NE; } 3933 bool isComparisonOp() const { return isComparisonOp(getOpcode()); } 3934 3935 static bool isCommaOp(Opcode Opc) { return Opc == BO_Comma; } 3936 bool isCommaOp() const { return isCommaOp(getOpcode()); } 3937 3938 static Opcode negateComparisonOp(Opcode Opc) { 3939 switch (Opc) { 3940 default: 3941 llvm_unreachable("Not a comparison operator."); 3942 case BO_LT: return BO_GE; 3943 case BO_GT: return BO_LE; 3944 case BO_LE: return BO_GT; 3945 case BO_GE: return BO_LT; 3946 case BO_EQ: return BO_NE; 3947 case BO_NE: return BO_EQ; 3948 } 3949 } 3950 3951 static Opcode reverseComparisonOp(Opcode Opc) { 3952 switch (Opc) { 3953 default: 3954 llvm_unreachable("Not a comparison operator."); 3955 case BO_LT: return BO_GT; 3956 case BO_GT: return BO_LT; 3957 case BO_LE: return BO_GE; 3958 case BO_GE: return BO_LE; 3959 case BO_EQ: 3960 case BO_NE: 3961 return Opc; 3962 } 3963 } 3964 3965 static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; } 3966 bool isLogicalOp() const { return isLogicalOp(getOpcode()); } 3967 3968 static bool isAssignmentOp(Opcode Opc) { 3969 return Opc >= BO_Assign && Opc <= BO_OrAssign; 3970 } 3971 bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); } 3972 3973 static bool isCompoundAssignmentOp(Opcode Opc) { 3974 return Opc > BO_Assign && Opc <= BO_OrAssign; 3975 } 3976 bool isCompoundAssignmentOp() const { 3977 return isCompoundAssignmentOp(getOpcode()); 3978 } 3979 static Opcode getOpForCompoundAssignment(Opcode Opc) { 3980 assert(isCompoundAssignmentOp(Opc)); 3981 if (Opc >= BO_AndAssign) 3982 return Opcode(unsigned(Opc) - BO_AndAssign + BO_And); 3983 else 3984 return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul); 3985 } 3986 3987 static bool isShiftAssignOp(Opcode Opc) { 3988 return Opc == BO_ShlAssign || Opc == BO_ShrAssign; 3989 } 3990 bool isShiftAssignOp() const { 3991 return isShiftAssignOp(getOpcode()); 3992 } 3993 3994 /// Return true if a binary operator using the specified opcode and operands 3995 /// would match the 'p = (i8*)nullptr + n' idiom for casting a pointer-sized 3996 /// integer to a pointer. 3997 static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc, 3998 const Expr *LHS, 3999 const Expr *RHS); 4000 4001 static bool classof(const Stmt *S) { 4002 return S->getStmtClass() >= firstBinaryOperatorConstant && 4003 S->getStmtClass() <= lastBinaryOperatorConstant; 4004 } 4005 4006 // Iterators 4007 child_range children() { 4008 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); 4009 } 4010 const_child_range children() const { 4011 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR); 4012 } 4013 4014 /// Set and fetch the bit that shows whether FPFeatures needs to be 4015 /// allocated in Trailing Storage 4016 void setHasStoredFPFeatures(bool B) { BinaryOperatorBits.HasFPFeatures = B; } 4017 bool hasStoredFPFeatures() const { return BinaryOperatorBits.HasFPFeatures; } 4018 4019 /// Get FPFeatures from trailing storage 4020 FPOptionsOverride getStoredFPFeatures() const { 4021 assert(hasStoredFPFeatures()); 4022 return *getTrailingFPFeatures(); 4023 } 4024 /// Set FPFeatures in trailing storage, used only by Serialization 4025 void setStoredFPFeatures(FPOptionsOverride F) { 4026 assert(BinaryOperatorBits.HasFPFeatures); 4027 *getTrailingFPFeatures() = F; 4028 } 4029 4030 /// Get the FP features status of this operator. Only meaningful for 4031 /// operations on floating point types. 4032 FPOptions getFPFeaturesInEffect(const LangOptions &LO) const { 4033 if (BinaryOperatorBits.HasFPFeatures) 4034 return getStoredFPFeatures().applyOverrides(LO); 4035 return FPOptions::defaultWithoutTrailingStorage(LO); 4036 } 4037 4038 // This is used in ASTImporter 4039 FPOptionsOverride getFPFeatures() const { 4040 if (BinaryOperatorBits.HasFPFeatures) 4041 return getStoredFPFeatures(); 4042 return FPOptionsOverride(); 4043 } 4044 4045 /// Get the FP contractability status of this operator. Only meaningful for 4046 /// operations on floating point types. 4047 bool isFPContractableWithinStatement(const LangOptions &LO) const { 4048 return getFPFeaturesInEffect(LO).allowFPContractWithinStatement(); 4049 } 4050 4051 /// Get the FENV_ACCESS status of this operator. Only meaningful for 4052 /// operations on floating point types. 4053 bool isFEnvAccessOn(const LangOptions &LO) const { 4054 return getFPFeaturesInEffect(LO).getAllowFEnvAccess(); 4055 } 4056 4057 protected: 4058 BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, Opcode opc, 4059 QualType ResTy, ExprValueKind VK, ExprObjectKind OK, 4060 SourceLocation opLoc, FPOptionsOverride FPFeatures, 4061 bool dead2); 4062 4063 /// Construct an empty BinaryOperator, SC is CompoundAssignOperator. 4064 BinaryOperator(StmtClass SC, EmptyShell Empty) : Expr(SC, Empty) { 4065 BinaryOperatorBits.Opc = BO_MulAssign; 4066 } 4067 4068 /// Return the size in bytes needed for the trailing objects. 4069 /// Used to allocate the right amount of storage. 4070 static unsigned sizeOfTrailingObjects(bool HasFPFeatures) { 4071 return HasFPFeatures * sizeof(FPOptionsOverride); 4072 } 4073 }; 4074 4075 /// CompoundAssignOperator - For compound assignments (e.g. +=), we keep 4076 /// track of the type the operation is performed in. Due to the semantics of 4077 /// these operators, the operands are promoted, the arithmetic performed, an 4078 /// implicit conversion back to the result type done, then the assignment takes 4079 /// place. This captures the intermediate type which the computation is done 4080 /// in. 4081 class CompoundAssignOperator : public BinaryOperator { 4082 QualType ComputationLHSType; 4083 QualType ComputationResultType; 4084 4085 /// Construct an empty CompoundAssignOperator. 4086 explicit CompoundAssignOperator(const ASTContext &C, EmptyShell Empty, 4087 bool hasFPFeatures) 4088 : BinaryOperator(CompoundAssignOperatorClass, Empty) {} 4089 4090 protected: 4091 CompoundAssignOperator(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, 4092 QualType ResType, ExprValueKind VK, ExprObjectKind OK, 4093 SourceLocation OpLoc, FPOptionsOverride FPFeatures, 4094 QualType CompLHSType, QualType CompResultType) 4095 : BinaryOperator(C, lhs, rhs, opc, ResType, VK, OK, OpLoc, FPFeatures, 4096 true), 4097 ComputationLHSType(CompLHSType), ComputationResultType(CompResultType) { 4098 assert(isCompoundAssignmentOp() && 4099 "Only should be used for compound assignments"); 4100 } 4101 4102 public: 4103 static CompoundAssignOperator *CreateEmpty(const ASTContext &C, 4104 bool hasFPFeatures); 4105 4106 static CompoundAssignOperator * 4107 Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, 4108 ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, 4109 FPOptionsOverride FPFeatures, QualType CompLHSType = QualType(), 4110 QualType CompResultType = QualType()); 4111 4112 // The two computation types are the type the LHS is converted 4113 // to for the computation and the type of the result; the two are 4114 // distinct in a few cases (specifically, int+=ptr and ptr-=ptr). 4115 QualType getComputationLHSType() const { return ComputationLHSType; } 4116 void setComputationLHSType(QualType T) { ComputationLHSType = T; } 4117 4118 QualType getComputationResultType() const { return ComputationResultType; } 4119 void setComputationResultType(QualType T) { ComputationResultType = T; } 4120 4121 static bool classof(const Stmt *S) { 4122 return S->getStmtClass() == CompoundAssignOperatorClass; 4123 } 4124 }; 4125 4126 inline size_t BinaryOperator::offsetOfTrailingStorage() const { 4127 assert(BinaryOperatorBits.HasFPFeatures); 4128 return isa<CompoundAssignOperator>(this) ? sizeof(CompoundAssignOperator) 4129 : sizeof(BinaryOperator); 4130 } 4131 4132 /// AbstractConditionalOperator - An abstract base class for 4133 /// ConditionalOperator and BinaryConditionalOperator. 4134 class AbstractConditionalOperator : public Expr { 4135 SourceLocation QuestionLoc, ColonLoc; 4136 friend class ASTStmtReader; 4137 4138 protected: 4139 AbstractConditionalOperator(StmtClass SC, QualType T, ExprValueKind VK, 4140 ExprObjectKind OK, SourceLocation qloc, 4141 SourceLocation cloc) 4142 : Expr(SC, T, VK, OK), QuestionLoc(qloc), ColonLoc(cloc) {} 4143 4144 AbstractConditionalOperator(StmtClass SC, EmptyShell Empty) 4145 : Expr(SC, Empty) { } 4146 4147 public: 4148 /// getCond - Return the expression representing the condition for 4149 /// the ?: operator. 4150 Expr *getCond() const; 4151 4152 /// getTrueExpr - Return the subexpression representing the value of 4153 /// the expression if the condition evaluates to true. 4154 Expr *getTrueExpr() const; 4155 4156 /// getFalseExpr - Return the subexpression representing the value of 4157 /// the expression if the condition evaluates to false. This is 4158 /// the same as getRHS. 4159 Expr *getFalseExpr() const; 4160 4161 SourceLocation getQuestionLoc() const { return QuestionLoc; } 4162 SourceLocation getColonLoc() const { return ColonLoc; } 4163 4164 static bool classof(const Stmt *T) { 4165 return T->getStmtClass() == ConditionalOperatorClass || 4166 T->getStmtClass() == BinaryConditionalOperatorClass; 4167 } 4168 }; 4169 4170 /// ConditionalOperator - The ?: ternary operator. The GNU "missing 4171 /// middle" extension is a BinaryConditionalOperator. 4172 class ConditionalOperator : public AbstractConditionalOperator { 4173 enum { COND, LHS, RHS, END_EXPR }; 4174 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides. 4175 4176 friend class ASTStmtReader; 4177 public: 4178 ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs, 4179 SourceLocation CLoc, Expr *rhs, QualType t, 4180 ExprValueKind VK, ExprObjectKind OK) 4181 : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK, QLoc, 4182 CLoc) { 4183 SubExprs[COND] = cond; 4184 SubExprs[LHS] = lhs; 4185 SubExprs[RHS] = rhs; 4186 setDependence(computeDependence(this)); 4187 } 4188 4189 /// Build an empty conditional operator. 4190 explicit ConditionalOperator(EmptyShell Empty) 4191 : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { } 4192 4193 /// getCond - Return the expression representing the condition for 4194 /// the ?: operator. 4195 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); } 4196 4197 /// getTrueExpr - Return the subexpression representing the value of 4198 /// the expression if the condition evaluates to true. 4199 Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); } 4200 4201 /// getFalseExpr - Return the subexpression representing the value of 4202 /// the expression if the condition evaluates to false. This is 4203 /// the same as getRHS. 4204 Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); } 4205 4206 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } 4207 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } 4208 4209 SourceLocation getBeginLoc() const LLVM_READONLY { 4210 return getCond()->getBeginLoc(); 4211 } 4212 SourceLocation getEndLoc() const LLVM_READONLY { 4213 return getRHS()->getEndLoc(); 4214 } 4215 4216 static bool classof(const Stmt *T) { 4217 return T->getStmtClass() == ConditionalOperatorClass; 4218 } 4219 4220 // Iterators 4221 child_range children() { 4222 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); 4223 } 4224 const_child_range children() const { 4225 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR); 4226 } 4227 }; 4228 4229 /// BinaryConditionalOperator - The GNU extension to the conditional 4230 /// operator which allows the middle operand to be omitted. 4231 /// 4232 /// This is a different expression kind on the assumption that almost 4233 /// every client ends up needing to know that these are different. 4234 class BinaryConditionalOperator : public AbstractConditionalOperator { 4235 enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS }; 4236 4237 /// - the common condition/left-hand-side expression, which will be 4238 /// evaluated as the opaque value 4239 /// - the condition, expressed in terms of the opaque value 4240 /// - the left-hand-side, expressed in terms of the opaque value 4241 /// - the right-hand-side 4242 Stmt *SubExprs[NUM_SUBEXPRS]; 4243 OpaqueValueExpr *OpaqueValue; 4244 4245 friend class ASTStmtReader; 4246 public: 4247 BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue, 4248 Expr *cond, Expr *lhs, Expr *rhs, 4249 SourceLocation qloc, SourceLocation cloc, 4250 QualType t, ExprValueKind VK, ExprObjectKind OK) 4251 : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK, 4252 qloc, cloc), 4253 OpaqueValue(opaqueValue) { 4254 SubExprs[COMMON] = common; 4255 SubExprs[COND] = cond; 4256 SubExprs[LHS] = lhs; 4257 SubExprs[RHS] = rhs; 4258 assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value"); 4259 setDependence(computeDependence(this)); 4260 } 4261 4262 /// Build an empty conditional operator. 4263 explicit BinaryConditionalOperator(EmptyShell Empty) 4264 : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { } 4265 4266 /// getCommon - Return the common expression, written to the 4267 /// left of the condition. The opaque value will be bound to the 4268 /// result of this expression. 4269 Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); } 4270 4271 /// getOpaqueValue - Return the opaque value placeholder. 4272 OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; } 4273 4274 /// getCond - Return the condition expression; this is defined 4275 /// in terms of the opaque value. 4276 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); } 4277 4278 /// getTrueExpr - Return the subexpression which will be 4279 /// evaluated if the condition evaluates to true; this is defined 4280 /// in terms of the opaque value. 4281 Expr *getTrueExpr() const { 4282 return cast<Expr>(SubExprs[LHS]); 4283 } 4284 4285 /// getFalseExpr - Return the subexpression which will be 4286 /// evaluated if the condnition evaluates to false; this is 4287 /// defined in terms of the opaque value. 4288 Expr *getFalseExpr() const { 4289 return cast<Expr>(SubExprs[RHS]); 4290 } 4291 4292 SourceLocation getBeginLoc() const LLVM_READONLY { 4293 return getCommon()->getBeginLoc(); 4294 } 4295 SourceLocation getEndLoc() const LLVM_READONLY { 4296 return getFalseExpr()->getEndLoc(); 4297 } 4298 4299 static bool classof(const Stmt *T) { 4300 return T->getStmtClass() == BinaryConditionalOperatorClass; 4301 } 4302 4303 // Iterators 4304 child_range children() { 4305 return child_range(SubExprs, SubExprs + NUM_SUBEXPRS); 4306 } 4307 const_child_range children() const { 4308 return const_child_range(SubExprs, SubExprs + NUM_SUBEXPRS); 4309 } 4310 }; 4311 4312 inline Expr *AbstractConditionalOperator::getCond() const { 4313 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this)) 4314 return co->getCond(); 4315 return cast<BinaryConditionalOperator>(this)->getCond(); 4316 } 4317 4318 inline Expr *AbstractConditionalOperator::getTrueExpr() const { 4319 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this)) 4320 return co->getTrueExpr(); 4321 return cast<BinaryConditionalOperator>(this)->getTrueExpr(); 4322 } 4323 4324 inline Expr *AbstractConditionalOperator::getFalseExpr() const { 4325 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this)) 4326 return co->getFalseExpr(); 4327 return cast<BinaryConditionalOperator>(this)->getFalseExpr(); 4328 } 4329 4330 /// AddrLabelExpr - The GNU address of label extension, representing &&label. 4331 class AddrLabelExpr : public Expr { 4332 SourceLocation AmpAmpLoc, LabelLoc; 4333 LabelDecl *Label; 4334 public: 4335 AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L, 4336 QualType t) 4337 : Expr(AddrLabelExprClass, t, VK_PRValue, OK_Ordinary), AmpAmpLoc(AALoc), 4338 LabelLoc(LLoc), Label(L) { 4339 setDependence(ExprDependence::None); 4340 } 4341 4342 /// Build an empty address of a label expression. 4343 explicit AddrLabelExpr(EmptyShell Empty) 4344 : Expr(AddrLabelExprClass, Empty) { } 4345 4346 SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; } 4347 void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; } 4348 SourceLocation getLabelLoc() const { return LabelLoc; } 4349 void setLabelLoc(SourceLocation L) { LabelLoc = L; } 4350 4351 SourceLocation getBeginLoc() const LLVM_READONLY { return AmpAmpLoc; } 4352 SourceLocation getEndLoc() const LLVM_READONLY { return LabelLoc; } 4353 4354 LabelDecl *getLabel() const { return Label; } 4355 void setLabel(LabelDecl *L) { Label = L; } 4356 4357 static bool classof(const Stmt *T) { 4358 return T->getStmtClass() == AddrLabelExprClass; 4359 } 4360 4361 // Iterators 4362 child_range children() { 4363 return child_range(child_iterator(), child_iterator()); 4364 } 4365 const_child_range children() const { 4366 return const_child_range(const_child_iterator(), const_child_iterator()); 4367 } 4368 }; 4369 4370 /// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}). 4371 /// The StmtExpr contains a single CompoundStmt node, which it evaluates and 4372 /// takes the value of the last subexpression. 4373 /// 4374 /// A StmtExpr is always an r-value; values "returned" out of a 4375 /// StmtExpr will be copied. 4376 class StmtExpr : public Expr { 4377 Stmt *SubStmt; 4378 SourceLocation LParenLoc, RParenLoc; 4379 public: 4380 StmtExpr(CompoundStmt *SubStmt, QualType T, SourceLocation LParenLoc, 4381 SourceLocation RParenLoc, unsigned TemplateDepth) 4382 : Expr(StmtExprClass, T, VK_PRValue, OK_Ordinary), SubStmt(SubStmt), 4383 LParenLoc(LParenLoc), RParenLoc(RParenLoc) { 4384 setDependence(computeDependence(this, TemplateDepth)); 4385 // FIXME: A templated statement expression should have an associated 4386 // DeclContext so that nested declarations always have a dependent context. 4387 StmtExprBits.TemplateDepth = TemplateDepth; 4388 } 4389 4390 /// Build an empty statement expression. 4391 explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { } 4392 4393 CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); } 4394 const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); } 4395 void setSubStmt(CompoundStmt *S) { SubStmt = S; } 4396 4397 SourceLocation getBeginLoc() const LLVM_READONLY { return LParenLoc; } 4398 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; } 4399 4400 SourceLocation getLParenLoc() const { return LParenLoc; } 4401 void setLParenLoc(SourceLocation L) { LParenLoc = L; } 4402 SourceLocation getRParenLoc() const { return RParenLoc; } 4403 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 4404 4405 unsigned getTemplateDepth() const { return StmtExprBits.TemplateDepth; } 4406 4407 static bool classof(const Stmt *T) { 4408 return T->getStmtClass() == StmtExprClass; 4409 } 4410 4411 // Iterators 4412 child_range children() { return child_range(&SubStmt, &SubStmt+1); } 4413 const_child_range children() const { 4414 return const_child_range(&SubStmt, &SubStmt + 1); 4415 } 4416 }; 4417 4418 /// ShuffleVectorExpr - clang-specific builtin-in function 4419 /// __builtin_shufflevector. 4420 /// This AST node represents a operator that does a constant 4421 /// shuffle, similar to LLVM's shufflevector instruction. It takes 4422 /// two vectors and a variable number of constant indices, 4423 /// and returns the appropriately shuffled vector. 4424 class ShuffleVectorExpr : public Expr { 4425 SourceLocation BuiltinLoc, RParenLoc; 4426 4427 // SubExprs - the list of values passed to the __builtin_shufflevector 4428 // function. The first two are vectors, and the rest are constant 4429 // indices. The number of values in this list is always 4430 // 2+the number of indices in the vector type. 4431 Stmt **SubExprs; 4432 unsigned NumExprs; 4433 4434 public: 4435 ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args, QualType Type, 4436 SourceLocation BLoc, SourceLocation RP); 4437 4438 /// Build an empty vector-shuffle expression. 4439 explicit ShuffleVectorExpr(EmptyShell Empty) 4440 : Expr(ShuffleVectorExprClass, Empty), SubExprs(nullptr) { } 4441 4442 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 4443 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; } 4444 4445 SourceLocation getRParenLoc() const { return RParenLoc; } 4446 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 4447 4448 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; } 4449 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; } 4450 4451 static bool classof(const Stmt *T) { 4452 return T->getStmtClass() == ShuffleVectorExprClass; 4453 } 4454 4455 /// getNumSubExprs - Return the size of the SubExprs array. This includes the 4456 /// constant expression, the actual arguments passed in, and the function 4457 /// pointers. 4458 unsigned getNumSubExprs() const { return NumExprs; } 4459 4460 /// Retrieve the array of expressions. 4461 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); } 4462 4463 /// getExpr - Return the Expr at the specified index. 4464 Expr *getExpr(unsigned Index) { 4465 assert((Index < NumExprs) && "Arg access out of range!"); 4466 return cast<Expr>(SubExprs[Index]); 4467 } 4468 const Expr *getExpr(unsigned Index) const { 4469 assert((Index < NumExprs) && "Arg access out of range!"); 4470 return cast<Expr>(SubExprs[Index]); 4471 } 4472 4473 void setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs); 4474 4475 llvm::APSInt getShuffleMaskIdx(const ASTContext &Ctx, unsigned N) const { 4476 assert((N < NumExprs - 2) && "Shuffle idx out of range!"); 4477 return getExpr(N+2)->EvaluateKnownConstInt(Ctx); 4478 } 4479 4480 // Iterators 4481 child_range children() { 4482 return child_range(&SubExprs[0], &SubExprs[0]+NumExprs); 4483 } 4484 const_child_range children() const { 4485 return const_child_range(&SubExprs[0], &SubExprs[0] + NumExprs); 4486 } 4487 }; 4488 4489 /// ConvertVectorExpr - Clang builtin function __builtin_convertvector 4490 /// This AST node provides support for converting a vector type to another 4491 /// vector type of the same arity. 4492 class ConvertVectorExpr : public Expr { 4493 private: 4494 Stmt *SrcExpr; 4495 TypeSourceInfo *TInfo; 4496 SourceLocation BuiltinLoc, RParenLoc; 4497 4498 friend class ASTReader; 4499 friend class ASTStmtReader; 4500 explicit ConvertVectorExpr(EmptyShell Empty) : Expr(ConvertVectorExprClass, Empty) {} 4501 4502 public: 4503 ConvertVectorExpr(Expr *SrcExpr, TypeSourceInfo *TI, QualType DstType, 4504 ExprValueKind VK, ExprObjectKind OK, 4505 SourceLocation BuiltinLoc, SourceLocation RParenLoc) 4506 : Expr(ConvertVectorExprClass, DstType, VK, OK), SrcExpr(SrcExpr), 4507 TInfo(TI), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) { 4508 setDependence(computeDependence(this)); 4509 } 4510 4511 /// getSrcExpr - Return the Expr to be converted. 4512 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); } 4513 4514 /// getTypeSourceInfo - Return the destination type. 4515 TypeSourceInfo *getTypeSourceInfo() const { 4516 return TInfo; 4517 } 4518 void setTypeSourceInfo(TypeSourceInfo *ti) { 4519 TInfo = ti; 4520 } 4521 4522 /// getBuiltinLoc - Return the location of the __builtin_convertvector token. 4523 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 4524 4525 /// getRParenLoc - Return the location of final right parenthesis. 4526 SourceLocation getRParenLoc() const { return RParenLoc; } 4527 4528 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; } 4529 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; } 4530 4531 static bool classof(const Stmt *T) { 4532 return T->getStmtClass() == ConvertVectorExprClass; 4533 } 4534 4535 // Iterators 4536 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); } 4537 const_child_range children() const { 4538 return const_child_range(&SrcExpr, &SrcExpr + 1); 4539 } 4540 }; 4541 4542 /// ChooseExpr - GNU builtin-in function __builtin_choose_expr. 4543 /// This AST node is similar to the conditional operator (?:) in C, with 4544 /// the following exceptions: 4545 /// - the test expression must be a integer constant expression. 4546 /// - the expression returned acts like the chosen subexpression in every 4547 /// visible way: the type is the same as that of the chosen subexpression, 4548 /// and all predicates (whether it's an l-value, whether it's an integer 4549 /// constant expression, etc.) return the same result as for the chosen 4550 /// sub-expression. 4551 class ChooseExpr : public Expr { 4552 enum { COND, LHS, RHS, END_EXPR }; 4553 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides. 4554 SourceLocation BuiltinLoc, RParenLoc; 4555 bool CondIsTrue; 4556 public: 4557 ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs, QualType t, 4558 ExprValueKind VK, ExprObjectKind OK, SourceLocation RP, 4559 bool condIsTrue) 4560 : Expr(ChooseExprClass, t, VK, OK), BuiltinLoc(BLoc), RParenLoc(RP), 4561 CondIsTrue(condIsTrue) { 4562 SubExprs[COND] = cond; 4563 SubExprs[LHS] = lhs; 4564 SubExprs[RHS] = rhs; 4565 4566 setDependence(computeDependence(this)); 4567 } 4568 4569 /// Build an empty __builtin_choose_expr. 4570 explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { } 4571 4572 /// isConditionTrue - Return whether the condition is true (i.e. not 4573 /// equal to zero). 4574 bool isConditionTrue() const { 4575 assert(!isConditionDependent() && 4576 "Dependent condition isn't true or false"); 4577 return CondIsTrue; 4578 } 4579 void setIsConditionTrue(bool isTrue) { CondIsTrue = isTrue; } 4580 4581 bool isConditionDependent() const { 4582 return getCond()->isTypeDependent() || getCond()->isValueDependent(); 4583 } 4584 4585 /// getChosenSubExpr - Return the subexpression chosen according to the 4586 /// condition. 4587 Expr *getChosenSubExpr() const { 4588 return isConditionTrue() ? getLHS() : getRHS(); 4589 } 4590 4591 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); } 4592 void setCond(Expr *E) { SubExprs[COND] = E; } 4593 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } 4594 void setLHS(Expr *E) { SubExprs[LHS] = E; } 4595 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } 4596 void setRHS(Expr *E) { SubExprs[RHS] = E; } 4597 4598 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 4599 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; } 4600 4601 SourceLocation getRParenLoc() const { return RParenLoc; } 4602 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 4603 4604 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; } 4605 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; } 4606 4607 static bool classof(const Stmt *T) { 4608 return T->getStmtClass() == ChooseExprClass; 4609 } 4610 4611 // Iterators 4612 child_range children() { 4613 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); 4614 } 4615 const_child_range children() const { 4616 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR); 4617 } 4618 }; 4619 4620 /// GNUNullExpr - Implements the GNU __null extension, which is a name 4621 /// for a null pointer constant that has integral type (e.g., int or 4622 /// long) and is the same size and alignment as a pointer. The __null 4623 /// extension is typically only used by system headers, which define 4624 /// NULL as __null in C++ rather than using 0 (which is an integer 4625 /// that may not match the size of a pointer). 4626 class GNUNullExpr : public Expr { 4627 /// TokenLoc - The location of the __null keyword. 4628 SourceLocation TokenLoc; 4629 4630 public: 4631 GNUNullExpr(QualType Ty, SourceLocation Loc) 4632 : Expr(GNUNullExprClass, Ty, VK_PRValue, OK_Ordinary), TokenLoc(Loc) { 4633 setDependence(ExprDependence::None); 4634 } 4635 4636 /// Build an empty GNU __null expression. 4637 explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { } 4638 4639 /// getTokenLocation - The location of the __null token. 4640 SourceLocation getTokenLocation() const { return TokenLoc; } 4641 void setTokenLocation(SourceLocation L) { TokenLoc = L; } 4642 4643 SourceLocation getBeginLoc() const LLVM_READONLY { return TokenLoc; } 4644 SourceLocation getEndLoc() const LLVM_READONLY { return TokenLoc; } 4645 4646 static bool classof(const Stmt *T) { 4647 return T->getStmtClass() == GNUNullExprClass; 4648 } 4649 4650 // Iterators 4651 child_range children() { 4652 return child_range(child_iterator(), child_iterator()); 4653 } 4654 const_child_range children() const { 4655 return const_child_range(const_child_iterator(), const_child_iterator()); 4656 } 4657 }; 4658 4659 /// Represents a call to the builtin function \c __builtin_va_arg. 4660 class VAArgExpr : public Expr { 4661 Stmt *Val; 4662 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfo; 4663 SourceLocation BuiltinLoc, RParenLoc; 4664 public: 4665 VAArgExpr(SourceLocation BLoc, Expr *e, TypeSourceInfo *TInfo, 4666 SourceLocation RPLoc, QualType t, bool IsMS) 4667 : Expr(VAArgExprClass, t, VK_PRValue, OK_Ordinary), Val(e), 4668 TInfo(TInfo, IsMS), BuiltinLoc(BLoc), RParenLoc(RPLoc) { 4669 setDependence(computeDependence(this)); 4670 } 4671 4672 /// Create an empty __builtin_va_arg expression. 4673 explicit VAArgExpr(EmptyShell Empty) 4674 : Expr(VAArgExprClass, Empty), Val(nullptr), TInfo(nullptr, false) {} 4675 4676 const Expr *getSubExpr() const { return cast<Expr>(Val); } 4677 Expr *getSubExpr() { return cast<Expr>(Val); } 4678 void setSubExpr(Expr *E) { Val = E; } 4679 4680 /// Returns whether this is really a Win64 ABI va_arg expression. 4681 bool isMicrosoftABI() const { return TInfo.getInt(); } 4682 void setIsMicrosoftABI(bool IsMS) { TInfo.setInt(IsMS); } 4683 4684 TypeSourceInfo *getWrittenTypeInfo() const { return TInfo.getPointer(); } 4685 void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo.setPointer(TI); } 4686 4687 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 4688 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; } 4689 4690 SourceLocation getRParenLoc() const { return RParenLoc; } 4691 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 4692 4693 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; } 4694 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; } 4695 4696 static bool classof(const Stmt *T) { 4697 return T->getStmtClass() == VAArgExprClass; 4698 } 4699 4700 // Iterators 4701 child_range children() { return child_range(&Val, &Val+1); } 4702 const_child_range children() const { 4703 return const_child_range(&Val, &Val + 1); 4704 } 4705 }; 4706 4707 /// Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(), 4708 /// __builtin_FUNCTION(), __builtin_FUNCSIG(), __builtin_FILE(), 4709 /// __builtin_FILE_NAME() or __builtin_source_location(). 4710 class SourceLocExpr final : public Expr { 4711 SourceLocation BuiltinLoc, RParenLoc; 4712 DeclContext *ParentContext; 4713 4714 public: 4715 enum IdentKind { 4716 Function, 4717 FuncSig, 4718 File, 4719 FileName, 4720 Line, 4721 Column, 4722 SourceLocStruct 4723 }; 4724 4725 SourceLocExpr(const ASTContext &Ctx, IdentKind Type, QualType ResultTy, 4726 SourceLocation BLoc, SourceLocation RParenLoc, 4727 DeclContext *Context); 4728 4729 /// Build an empty call expression. 4730 explicit SourceLocExpr(EmptyShell Empty) : Expr(SourceLocExprClass, Empty) {} 4731 4732 /// Return the result of evaluating this SourceLocExpr in the specified 4733 /// (and possibly null) default argument or initialization context. 4734 APValue EvaluateInContext(const ASTContext &Ctx, 4735 const Expr *DefaultExpr) const; 4736 4737 /// Return a string representing the name of the specific builtin function. 4738 StringRef getBuiltinStr() const; 4739 4740 IdentKind getIdentKind() const { 4741 return static_cast<IdentKind>(SourceLocExprBits.Kind); 4742 } 4743 4744 bool isIntType() const { 4745 switch (getIdentKind()) { 4746 case File: 4747 case FileName: 4748 case Function: 4749 case FuncSig: 4750 case SourceLocStruct: 4751 return false; 4752 case Line: 4753 case Column: 4754 return true; 4755 } 4756 llvm_unreachable("unknown source location expression kind"); 4757 } 4758 4759 /// If the SourceLocExpr has been resolved return the subexpression 4760 /// representing the resolved value. Otherwise return null. 4761 const DeclContext *getParentContext() const { return ParentContext; } 4762 DeclContext *getParentContext() { return ParentContext; } 4763 4764 SourceLocation getLocation() const { return BuiltinLoc; } 4765 SourceLocation getBeginLoc() const { return BuiltinLoc; } 4766 SourceLocation getEndLoc() const { return RParenLoc; } 4767 4768 child_range children() { 4769 return child_range(child_iterator(), child_iterator()); 4770 } 4771 4772 const_child_range children() const { 4773 return const_child_range(child_iterator(), child_iterator()); 4774 } 4775 4776 static bool classof(const Stmt *T) { 4777 return T->getStmtClass() == SourceLocExprClass; 4778 } 4779 4780 private: 4781 friend class ASTStmtReader; 4782 }; 4783 4784 /// Describes an C or C++ initializer list. 4785 /// 4786 /// InitListExpr describes an initializer list, which can be used to 4787 /// initialize objects of different types, including 4788 /// struct/class/union types, arrays, and vectors. For example: 4789 /// 4790 /// @code 4791 /// struct foo x = { 1, { 2, 3 } }; 4792 /// @endcode 4793 /// 4794 /// Prior to semantic analysis, an initializer list will represent the 4795 /// initializer list as written by the user, but will have the 4796 /// placeholder type "void". This initializer list is called the 4797 /// syntactic form of the initializer, and may contain C99 designated 4798 /// initializers (represented as DesignatedInitExprs), initializations 4799 /// of subobject members without explicit braces, and so on. Clients 4800 /// interested in the original syntax of the initializer list should 4801 /// use the syntactic form of the initializer list. 4802 /// 4803 /// After semantic analysis, the initializer list will represent the 4804 /// semantic form of the initializer, where the initializations of all 4805 /// subobjects are made explicit with nested InitListExpr nodes and 4806 /// C99 designators have been eliminated by placing the designated 4807 /// initializations into the subobject they initialize. Additionally, 4808 /// any "holes" in the initialization, where no initializer has been 4809 /// specified for a particular subobject, will be replaced with 4810 /// implicitly-generated ImplicitValueInitExpr expressions that 4811 /// value-initialize the subobjects. Note, however, that the 4812 /// initializer lists may still have fewer initializers than there are 4813 /// elements to initialize within the object. 4814 /// 4815 /// After semantic analysis has completed, given an initializer list, 4816 /// method isSemanticForm() returns true if and only if this is the 4817 /// semantic form of the initializer list (note: the same AST node 4818 /// may at the same time be the syntactic form). 4819 /// Given the semantic form of the initializer list, one can retrieve 4820 /// the syntactic form of that initializer list (when different) 4821 /// using method getSyntacticForm(); the method returns null if applied 4822 /// to a initializer list which is already in syntactic form. 4823 /// Similarly, given the syntactic form (i.e., an initializer list such 4824 /// that isSemanticForm() returns false), one can retrieve the semantic 4825 /// form using method getSemanticForm(). 4826 /// Since many initializer lists have the same syntactic and semantic forms, 4827 /// getSyntacticForm() may return NULL, indicating that the current 4828 /// semantic initializer list also serves as its syntactic form. 4829 class InitListExpr : public Expr { 4830 // FIXME: Eliminate this vector in favor of ASTContext allocation 4831 typedef ASTVector<Stmt *> InitExprsTy; 4832 InitExprsTy InitExprs; 4833 SourceLocation LBraceLoc, RBraceLoc; 4834 4835 /// The alternative form of the initializer list (if it exists). 4836 /// The int part of the pair stores whether this initializer list is 4837 /// in semantic form. If not null, the pointer points to: 4838 /// - the syntactic form, if this is in semantic form; 4839 /// - the semantic form, if this is in syntactic form. 4840 llvm::PointerIntPair<InitListExpr *, 1, bool> AltForm; 4841 4842 /// Either: 4843 /// If this initializer list initializes an array with more elements than 4844 /// there are initializers in the list, specifies an expression to be used 4845 /// for value initialization of the rest of the elements. 4846 /// Or 4847 /// If this initializer list initializes a union, specifies which 4848 /// field within the union will be initialized. 4849 llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit; 4850 4851 public: 4852 InitListExpr(const ASTContext &C, SourceLocation lbraceloc, 4853 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc); 4854 4855 /// Build an empty initializer list. 4856 explicit InitListExpr(EmptyShell Empty) 4857 : Expr(InitListExprClass, Empty), AltForm(nullptr, true) { } 4858 4859 unsigned getNumInits() const { return InitExprs.size(); } 4860 4861 /// Retrieve the set of initializers. 4862 Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); } 4863 4864 /// Retrieve the set of initializers. 4865 Expr * const *getInits() const { 4866 return reinterpret_cast<Expr * const *>(InitExprs.data()); 4867 } 4868 4869 ArrayRef<Expr *> inits() { return llvm::ArrayRef(getInits(), getNumInits()); } 4870 4871 ArrayRef<Expr *> inits() const { 4872 return llvm::ArrayRef(getInits(), getNumInits()); 4873 } 4874 4875 const Expr *getInit(unsigned Init) const { 4876 assert(Init < getNumInits() && "Initializer access out of range!"); 4877 return cast_or_null<Expr>(InitExprs[Init]); 4878 } 4879 4880 Expr *getInit(unsigned Init) { 4881 assert(Init < getNumInits() && "Initializer access out of range!"); 4882 return cast_or_null<Expr>(InitExprs[Init]); 4883 } 4884 4885 void setInit(unsigned Init, Expr *expr) { 4886 assert(Init < getNumInits() && "Initializer access out of range!"); 4887 InitExprs[Init] = expr; 4888 4889 if (expr) 4890 setDependence(getDependence() | expr->getDependence()); 4891 } 4892 4893 /// Mark the semantic form of the InitListExpr as error when the semantic 4894 /// analysis fails. 4895 void markError() { 4896 assert(isSemanticForm()); 4897 setDependence(getDependence() | ExprDependence::ErrorDependent); 4898 } 4899 4900 /// Reserve space for some number of initializers. 4901 void reserveInits(const ASTContext &C, unsigned NumInits); 4902 4903 /// Specify the number of initializers 4904 /// 4905 /// If there are more than @p NumInits initializers, the remaining 4906 /// initializers will be destroyed. If there are fewer than @p 4907 /// NumInits initializers, NULL expressions will be added for the 4908 /// unknown initializers. 4909 void resizeInits(const ASTContext &Context, unsigned NumInits); 4910 4911 /// Updates the initializer at index @p Init with the new 4912 /// expression @p expr, and returns the old expression at that 4913 /// location. 4914 /// 4915 /// When @p Init is out of range for this initializer list, the 4916 /// initializer list will be extended with NULL expressions to 4917 /// accommodate the new entry. 4918 Expr *updateInit(const ASTContext &C, unsigned Init, Expr *expr); 4919 4920 /// If this initializer list initializes an array with more elements 4921 /// than there are initializers in the list, specifies an expression to be 4922 /// used for value initialization of the rest of the elements. 4923 Expr *getArrayFiller() { 4924 return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>(); 4925 } 4926 const Expr *getArrayFiller() const { 4927 return const_cast<InitListExpr *>(this)->getArrayFiller(); 4928 } 4929 void setArrayFiller(Expr *filler); 4930 4931 /// Return true if this is an array initializer and its array "filler" 4932 /// has been set. 4933 bool hasArrayFiller() const { return getArrayFiller(); } 4934 4935 /// Determine whether this initializer list contains a designated initializer. 4936 bool hasDesignatedInit() const { 4937 return std::any_of(begin(), end(), [](const Stmt *S) { 4938 return isa<DesignatedInitExpr>(S); 4939 }); 4940 } 4941 4942 /// If this initializes a union, specifies which field in the 4943 /// union to initialize. 4944 /// 4945 /// Typically, this field is the first named field within the 4946 /// union. However, a designated initializer can specify the 4947 /// initialization of a different field within the union. 4948 FieldDecl *getInitializedFieldInUnion() { 4949 return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>(); 4950 } 4951 const FieldDecl *getInitializedFieldInUnion() const { 4952 return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion(); 4953 } 4954 void setInitializedFieldInUnion(FieldDecl *FD) { 4955 assert((FD == nullptr 4956 || getInitializedFieldInUnion() == nullptr 4957 || getInitializedFieldInUnion() == FD) 4958 && "Only one field of a union may be initialized at a time!"); 4959 ArrayFillerOrUnionFieldInit = FD; 4960 } 4961 4962 // Explicit InitListExpr's originate from source code (and have valid source 4963 // locations). Implicit InitListExpr's are created by the semantic analyzer. 4964 // FIXME: This is wrong; InitListExprs created by semantic analysis have 4965 // valid source locations too! 4966 bool isExplicit() const { 4967 return LBraceLoc.isValid() && RBraceLoc.isValid(); 4968 } 4969 4970 /// Is this an initializer for an array of characters, initialized by a string 4971 /// literal or an @encode? 4972 bool isStringLiteralInit() const; 4973 4974 /// Is this a transparent initializer list (that is, an InitListExpr that is 4975 /// purely syntactic, and whose semantics are that of the sole contained 4976 /// initializer)? 4977 bool isTransparent() const; 4978 4979 /// Is this the zero initializer {0} in a language which considers it 4980 /// idiomatic? 4981 bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const; 4982 4983 SourceLocation getLBraceLoc() const { return LBraceLoc; } 4984 void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; } 4985 SourceLocation getRBraceLoc() const { return RBraceLoc; } 4986 void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; } 4987 4988 bool isSemanticForm() const { return AltForm.getInt(); } 4989 InitListExpr *getSemanticForm() const { 4990 return isSemanticForm() ? nullptr : AltForm.getPointer(); 4991 } 4992 bool isSyntacticForm() const { 4993 return !AltForm.getInt() || !AltForm.getPointer(); 4994 } 4995 InitListExpr *getSyntacticForm() const { 4996 return isSemanticForm() ? AltForm.getPointer() : nullptr; 4997 } 4998 4999 void setSyntacticForm(InitListExpr *Init) { 5000 AltForm.setPointer(Init); 5001 AltForm.setInt(true); 5002 Init->AltForm.setPointer(this); 5003 Init->AltForm.setInt(false); 5004 } 5005 5006 bool hadArrayRangeDesignator() const { 5007 return InitListExprBits.HadArrayRangeDesignator != 0; 5008 } 5009 void sawArrayRangeDesignator(bool ARD = true) { 5010 InitListExprBits.HadArrayRangeDesignator = ARD; 5011 } 5012 5013 SourceLocation getBeginLoc() const LLVM_READONLY; 5014 SourceLocation getEndLoc() const LLVM_READONLY; 5015 5016 static bool classof(const Stmt *T) { 5017 return T->getStmtClass() == InitListExprClass; 5018 } 5019 5020 // Iterators 5021 child_range children() { 5022 const_child_range CCR = const_cast<const InitListExpr *>(this)->children(); 5023 return child_range(cast_away_const(CCR.begin()), 5024 cast_away_const(CCR.end())); 5025 } 5026 5027 const_child_range children() const { 5028 // FIXME: This does not include the array filler expression. 5029 if (InitExprs.empty()) 5030 return const_child_range(const_child_iterator(), const_child_iterator()); 5031 return const_child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size()); 5032 } 5033 5034 typedef InitExprsTy::iterator iterator; 5035 typedef InitExprsTy::const_iterator const_iterator; 5036 typedef InitExprsTy::reverse_iterator reverse_iterator; 5037 typedef InitExprsTy::const_reverse_iterator const_reverse_iterator; 5038 5039 iterator begin() { return InitExprs.begin(); } 5040 const_iterator begin() const { return InitExprs.begin(); } 5041 iterator end() { return InitExprs.end(); } 5042 const_iterator end() const { return InitExprs.end(); } 5043 reverse_iterator rbegin() { return InitExprs.rbegin(); } 5044 const_reverse_iterator rbegin() const { return InitExprs.rbegin(); } 5045 reverse_iterator rend() { return InitExprs.rend(); } 5046 const_reverse_iterator rend() const { return InitExprs.rend(); } 5047 5048 friend class ASTStmtReader; 5049 friend class ASTStmtWriter; 5050 }; 5051 5052 /// Represents a C99 designated initializer expression. 5053 /// 5054 /// A designated initializer expression (C99 6.7.8) contains one or 5055 /// more designators (which can be field designators, array 5056 /// designators, or GNU array-range designators) followed by an 5057 /// expression that initializes the field or element(s) that the 5058 /// designators refer to. For example, given: 5059 /// 5060 /// @code 5061 /// struct point { 5062 /// double x; 5063 /// double y; 5064 /// }; 5065 /// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 }; 5066 /// @endcode 5067 /// 5068 /// The InitListExpr contains three DesignatedInitExprs, the first of 5069 /// which covers @c [2].y=1.0. This DesignatedInitExpr will have two 5070 /// designators, one array designator for @c [2] followed by one field 5071 /// designator for @c .y. The initialization expression will be 1.0. 5072 class DesignatedInitExpr final 5073 : public Expr, 5074 private llvm::TrailingObjects<DesignatedInitExpr, Stmt *> { 5075 public: 5076 /// Forward declaration of the Designator class. 5077 class Designator; 5078 5079 private: 5080 /// The location of the '=' or ':' prior to the actual initializer 5081 /// expression. 5082 SourceLocation EqualOrColonLoc; 5083 5084 /// Whether this designated initializer used the GNU deprecated 5085 /// syntax rather than the C99 '=' syntax. 5086 unsigned GNUSyntax : 1; 5087 5088 /// The number of designators in this initializer expression. 5089 unsigned NumDesignators : 15; 5090 5091 /// The number of subexpressions of this initializer expression, 5092 /// which contains both the initializer and any additional 5093 /// expressions used by array and array-range designators. 5094 unsigned NumSubExprs : 16; 5095 5096 /// The designators in this designated initialization 5097 /// expression. 5098 Designator *Designators; 5099 5100 DesignatedInitExpr(const ASTContext &C, QualType Ty, 5101 llvm::ArrayRef<Designator> Designators, 5102 SourceLocation EqualOrColonLoc, bool GNUSyntax, 5103 ArrayRef<Expr *> IndexExprs, Expr *Init); 5104 5105 explicit DesignatedInitExpr(unsigned NumSubExprs) 5106 : Expr(DesignatedInitExprClass, EmptyShell()), 5107 NumDesignators(0), NumSubExprs(NumSubExprs), Designators(nullptr) { } 5108 5109 public: 5110 /// Represents a single C99 designator. 5111 /// 5112 /// @todo This class is infuriatingly similar to clang::Designator, 5113 /// but minor differences (storing indices vs. storing pointers) 5114 /// keep us from reusing it. Try harder, later, to rectify these 5115 /// differences. 5116 class Designator { 5117 /// A field designator, e.g., ".x". 5118 struct FieldDesignatorInfo { 5119 /// Refers to the field that is being initialized. The low bit 5120 /// of this field determines whether this is actually a pointer 5121 /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When 5122 /// initially constructed, a field designator will store an 5123 /// IdentifierInfo*. After semantic analysis has resolved that 5124 /// name, the field designator will instead store a FieldDecl*. 5125 uintptr_t NameOrField; 5126 5127 /// The location of the '.' in the designated initializer. 5128 SourceLocation DotLoc; 5129 5130 /// The location of the field name in the designated initializer. 5131 SourceLocation FieldLoc; 5132 5133 FieldDesignatorInfo(const IdentifierInfo *II, SourceLocation DotLoc, 5134 SourceLocation FieldLoc) 5135 : NameOrField(reinterpret_cast<uintptr_t>(II) | 0x1), DotLoc(DotLoc), 5136 FieldLoc(FieldLoc) {} 5137 }; 5138 5139 /// An array or GNU array-range designator, e.g., "[9]" or "[10...15]". 5140 struct ArrayOrRangeDesignatorInfo { 5141 /// Location of the first index expression within the designated 5142 /// initializer expression's list of subexpressions. 5143 unsigned Index; 5144 5145 /// The location of the '[' starting the array range designator. 5146 SourceLocation LBracketLoc; 5147 5148 /// The location of the ellipsis separating the start and end 5149 /// indices. Only valid for GNU array-range designators. 5150 SourceLocation EllipsisLoc; 5151 5152 /// The location of the ']' terminating the array range designator. 5153 SourceLocation RBracketLoc; 5154 5155 ArrayOrRangeDesignatorInfo(unsigned Index, SourceLocation LBracketLoc, 5156 SourceLocation RBracketLoc) 5157 : Index(Index), LBracketLoc(LBracketLoc), RBracketLoc(RBracketLoc) {} 5158 5159 ArrayOrRangeDesignatorInfo(unsigned Index, 5160 SourceLocation LBracketLoc, 5161 SourceLocation EllipsisLoc, 5162 SourceLocation RBracketLoc) 5163 : Index(Index), LBracketLoc(LBracketLoc), EllipsisLoc(EllipsisLoc), 5164 RBracketLoc(RBracketLoc) {} 5165 }; 5166 5167 /// The kind of designator this describes. 5168 enum DesignatorKind { 5169 FieldDesignator, 5170 ArrayDesignator, 5171 ArrayRangeDesignator 5172 }; 5173 5174 DesignatorKind Kind; 5175 5176 union { 5177 /// A field designator, e.g., ".x". 5178 struct FieldDesignatorInfo FieldInfo; 5179 5180 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]". 5181 struct ArrayOrRangeDesignatorInfo ArrayOrRangeInfo; 5182 }; 5183 5184 Designator(DesignatorKind Kind) : Kind(Kind) {} 5185 5186 public: 5187 Designator() {} 5188 5189 bool isFieldDesignator() const { return Kind == FieldDesignator; } 5190 bool isArrayDesignator() const { return Kind == ArrayDesignator; } 5191 bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; } 5192 5193 //===------------------------------------------------------------------===// 5194 // FieldDesignatorInfo 5195 5196 /// Creates a field designator. 5197 static Designator CreateFieldDesignator(const IdentifierInfo *FieldName, 5198 SourceLocation DotLoc, 5199 SourceLocation FieldLoc) { 5200 Designator D(FieldDesignator); 5201 new (&D.FieldInfo) FieldDesignatorInfo(FieldName, DotLoc, FieldLoc); 5202 return D; 5203 } 5204 5205 const IdentifierInfo *getFieldName() const; 5206 5207 FieldDecl *getFieldDecl() const { 5208 assert(isFieldDesignator() && "Only valid on a field designator"); 5209 if (FieldInfo.NameOrField & 0x01) 5210 return nullptr; 5211 return reinterpret_cast<FieldDecl *>(FieldInfo.NameOrField); 5212 } 5213 5214 void setFieldDecl(FieldDecl *FD) { 5215 assert(isFieldDesignator() && "Only valid on a field designator"); 5216 FieldInfo.NameOrField = reinterpret_cast<uintptr_t>(FD); 5217 } 5218 5219 SourceLocation getDotLoc() const { 5220 assert(isFieldDesignator() && "Only valid on a field designator"); 5221 return FieldInfo.DotLoc; 5222 } 5223 5224 SourceLocation getFieldLoc() const { 5225 assert(isFieldDesignator() && "Only valid on a field designator"); 5226 return FieldInfo.FieldLoc; 5227 } 5228 5229 //===------------------------------------------------------------------===// 5230 // ArrayOrRangeDesignator 5231 5232 /// Creates an array designator. 5233 static Designator CreateArrayDesignator(unsigned Index, 5234 SourceLocation LBracketLoc, 5235 SourceLocation RBracketLoc) { 5236 Designator D(ArrayDesignator); 5237 new (&D.ArrayOrRangeInfo) ArrayOrRangeDesignatorInfo(Index, LBracketLoc, 5238 RBracketLoc); 5239 return D; 5240 } 5241 5242 /// Creates a GNU array-range designator. 5243 static Designator CreateArrayRangeDesignator(unsigned Index, 5244 SourceLocation LBracketLoc, 5245 SourceLocation EllipsisLoc, 5246 SourceLocation RBracketLoc) { 5247 Designator D(ArrayRangeDesignator); 5248 new (&D.ArrayOrRangeInfo) ArrayOrRangeDesignatorInfo(Index, LBracketLoc, 5249 EllipsisLoc, 5250 RBracketLoc); 5251 return D; 5252 } 5253 5254 unsigned getArrayIndex() const { 5255 assert((isArrayDesignator() || isArrayRangeDesignator()) && 5256 "Only valid on an array or array-range designator"); 5257 return ArrayOrRangeInfo.Index; 5258 } 5259 5260 SourceLocation getLBracketLoc() const { 5261 assert((isArrayDesignator() || isArrayRangeDesignator()) && 5262 "Only valid on an array or array-range designator"); 5263 return ArrayOrRangeInfo.LBracketLoc; 5264 } 5265 5266 SourceLocation getEllipsisLoc() const { 5267 assert(isArrayRangeDesignator() && 5268 "Only valid on an array-range designator"); 5269 return ArrayOrRangeInfo.EllipsisLoc; 5270 } 5271 5272 SourceLocation getRBracketLoc() const { 5273 assert((isArrayDesignator() || isArrayRangeDesignator()) && 5274 "Only valid on an array or array-range designator"); 5275 return ArrayOrRangeInfo.RBracketLoc; 5276 } 5277 5278 SourceLocation getBeginLoc() const LLVM_READONLY { 5279 if (isFieldDesignator()) 5280 return getDotLoc().isInvalid() ? getFieldLoc() : getDotLoc(); 5281 return getLBracketLoc(); 5282 } 5283 5284 SourceLocation getEndLoc() const LLVM_READONLY { 5285 return isFieldDesignator() ? getFieldLoc() : getRBracketLoc(); 5286 } 5287 5288 SourceRange getSourceRange() const LLVM_READONLY { 5289 return SourceRange(getBeginLoc(), getEndLoc()); 5290 } 5291 }; 5292 5293 static DesignatedInitExpr *Create(const ASTContext &C, 5294 llvm::ArrayRef<Designator> Designators, 5295 ArrayRef<Expr*> IndexExprs, 5296 SourceLocation EqualOrColonLoc, 5297 bool GNUSyntax, Expr *Init); 5298 5299 static DesignatedInitExpr *CreateEmpty(const ASTContext &C, 5300 unsigned NumIndexExprs); 5301 5302 /// Returns the number of designators in this initializer. 5303 unsigned size() const { return NumDesignators; } 5304 5305 // Iterator access to the designators. 5306 llvm::MutableArrayRef<Designator> designators() { 5307 return {Designators, NumDesignators}; 5308 } 5309 5310 llvm::ArrayRef<Designator> designators() const { 5311 return {Designators, NumDesignators}; 5312 } 5313 5314 Designator *getDesignator(unsigned Idx) { return &designators()[Idx]; } 5315 const Designator *getDesignator(unsigned Idx) const { 5316 return &designators()[Idx]; 5317 } 5318 5319 void setDesignators(const ASTContext &C, const Designator *Desigs, 5320 unsigned NumDesigs); 5321 5322 Expr *getArrayIndex(const Designator &D) const; 5323 Expr *getArrayRangeStart(const Designator &D) const; 5324 Expr *getArrayRangeEnd(const Designator &D) const; 5325 5326 /// Retrieve the location of the '=' that precedes the 5327 /// initializer value itself, if present. 5328 SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; } 5329 void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; } 5330 5331 /// Whether this designated initializer should result in direct-initialization 5332 /// of the designated subobject (eg, '{.foo{1, 2, 3}}'). 5333 bool isDirectInit() const { return EqualOrColonLoc.isInvalid(); } 5334 5335 /// Determines whether this designated initializer used the 5336 /// deprecated GNU syntax for designated initializers. 5337 bool usesGNUSyntax() const { return GNUSyntax; } 5338 void setGNUSyntax(bool GNU) { GNUSyntax = GNU; } 5339 5340 /// Retrieve the initializer value. 5341 Expr *getInit() const { 5342 return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin()); 5343 } 5344 5345 void setInit(Expr *init) { 5346 *child_begin() = init; 5347 } 5348 5349 /// Retrieve the total number of subexpressions in this 5350 /// designated initializer expression, including the actual 5351 /// initialized value and any expressions that occur within array 5352 /// and array-range designators. 5353 unsigned getNumSubExprs() const { return NumSubExprs; } 5354 5355 Expr *getSubExpr(unsigned Idx) const { 5356 assert(Idx < NumSubExprs && "Subscript out of range"); 5357 return cast<Expr>(getTrailingObjects<Stmt *>()[Idx]); 5358 } 5359 5360 void setSubExpr(unsigned Idx, Expr *E) { 5361 assert(Idx < NumSubExprs && "Subscript out of range"); 5362 getTrailingObjects<Stmt *>()[Idx] = E; 5363 } 5364 5365 /// Replaces the designator at index @p Idx with the series 5366 /// of designators in [First, Last). 5367 void ExpandDesignator(const ASTContext &C, unsigned Idx, 5368 const Designator *First, const Designator *Last); 5369 5370 SourceRange getDesignatorsSourceRange() const; 5371 5372 SourceLocation getBeginLoc() const LLVM_READONLY; 5373 SourceLocation getEndLoc() const LLVM_READONLY; 5374 5375 static bool classof(const Stmt *T) { 5376 return T->getStmtClass() == DesignatedInitExprClass; 5377 } 5378 5379 // Iterators 5380 child_range children() { 5381 Stmt **begin = getTrailingObjects<Stmt *>(); 5382 return child_range(begin, begin + NumSubExprs); 5383 } 5384 const_child_range children() const { 5385 Stmt * const *begin = getTrailingObjects<Stmt *>(); 5386 return const_child_range(begin, begin + NumSubExprs); 5387 } 5388 5389 friend TrailingObjects; 5390 }; 5391 5392 /// Represents a place-holder for an object not to be initialized by 5393 /// anything. 5394 /// 5395 /// This only makes sense when it appears as part of an updater of a 5396 /// DesignatedInitUpdateExpr (see below). The base expression of a DIUE 5397 /// initializes a big object, and the NoInitExpr's mark the spots within the 5398 /// big object not to be overwritten by the updater. 5399 /// 5400 /// \see DesignatedInitUpdateExpr 5401 class NoInitExpr : public Expr { 5402 public: 5403 explicit NoInitExpr(QualType ty) 5404 : Expr(NoInitExprClass, ty, VK_PRValue, OK_Ordinary) { 5405 setDependence(computeDependence(this)); 5406 } 5407 5408 explicit NoInitExpr(EmptyShell Empty) 5409 : Expr(NoInitExprClass, Empty) { } 5410 5411 static bool classof(const Stmt *T) { 5412 return T->getStmtClass() == NoInitExprClass; 5413 } 5414 5415 SourceLocation getBeginLoc() const LLVM_READONLY { return SourceLocation(); } 5416 SourceLocation getEndLoc() const LLVM_READONLY { return SourceLocation(); } 5417 5418 // Iterators 5419 child_range children() { 5420 return child_range(child_iterator(), child_iterator()); 5421 } 5422 const_child_range children() const { 5423 return const_child_range(const_child_iterator(), const_child_iterator()); 5424 } 5425 }; 5426 5427 // In cases like: 5428 // struct Q { int a, b, c; }; 5429 // Q *getQ(); 5430 // void foo() { 5431 // struct A { Q q; } a = { *getQ(), .q.b = 3 }; 5432 // } 5433 // 5434 // We will have an InitListExpr for a, with type A, and then a 5435 // DesignatedInitUpdateExpr for "a.q" with type Q. The "base" for this DIUE 5436 // is the call expression *getQ(); the "updater" for the DIUE is ".q.b = 3" 5437 // 5438 class DesignatedInitUpdateExpr : public Expr { 5439 // BaseAndUpdaterExprs[0] is the base expression; 5440 // BaseAndUpdaterExprs[1] is an InitListExpr overwriting part of the base. 5441 Stmt *BaseAndUpdaterExprs[2]; 5442 5443 public: 5444 DesignatedInitUpdateExpr(const ASTContext &C, SourceLocation lBraceLoc, 5445 Expr *baseExprs, SourceLocation rBraceLoc); 5446 5447 explicit DesignatedInitUpdateExpr(EmptyShell Empty) 5448 : Expr(DesignatedInitUpdateExprClass, Empty) { } 5449 5450 SourceLocation getBeginLoc() const LLVM_READONLY; 5451 SourceLocation getEndLoc() const LLVM_READONLY; 5452 5453 static bool classof(const Stmt *T) { 5454 return T->getStmtClass() == DesignatedInitUpdateExprClass; 5455 } 5456 5457 Expr *getBase() const { return cast<Expr>(BaseAndUpdaterExprs[0]); } 5458 void setBase(Expr *Base) { BaseAndUpdaterExprs[0] = Base; } 5459 5460 InitListExpr *getUpdater() const { 5461 return cast<InitListExpr>(BaseAndUpdaterExprs[1]); 5462 } 5463 void setUpdater(Expr *Updater) { BaseAndUpdaterExprs[1] = Updater; } 5464 5465 // Iterators 5466 // children = the base and the updater 5467 child_range children() { 5468 return child_range(&BaseAndUpdaterExprs[0], &BaseAndUpdaterExprs[0] + 2); 5469 } 5470 const_child_range children() const { 5471 return const_child_range(&BaseAndUpdaterExprs[0], 5472 &BaseAndUpdaterExprs[0] + 2); 5473 } 5474 }; 5475 5476 /// Represents a loop initializing the elements of an array. 5477 /// 5478 /// The need to initialize the elements of an array occurs in a number of 5479 /// contexts: 5480 /// 5481 /// * in the implicit copy/move constructor for a class with an array member 5482 /// * when a lambda-expression captures an array by value 5483 /// * when a decomposition declaration decomposes an array 5484 /// 5485 /// There are two subexpressions: a common expression (the source array) 5486 /// that is evaluated once up-front, and a per-element initializer that 5487 /// runs once for each array element. 5488 /// 5489 /// Within the per-element initializer, the common expression may be referenced 5490 /// via an OpaqueValueExpr, and the current index may be obtained via an 5491 /// ArrayInitIndexExpr. 5492 class ArrayInitLoopExpr : public Expr { 5493 Stmt *SubExprs[2]; 5494 5495 explicit ArrayInitLoopExpr(EmptyShell Empty) 5496 : Expr(ArrayInitLoopExprClass, Empty), SubExprs{} {} 5497 5498 public: 5499 explicit ArrayInitLoopExpr(QualType T, Expr *CommonInit, Expr *ElementInit) 5500 : Expr(ArrayInitLoopExprClass, T, VK_PRValue, OK_Ordinary), 5501 SubExprs{CommonInit, ElementInit} { 5502 setDependence(computeDependence(this)); 5503 } 5504 5505 /// Get the common subexpression shared by all initializations (the source 5506 /// array). 5507 OpaqueValueExpr *getCommonExpr() const { 5508 return cast<OpaqueValueExpr>(SubExprs[0]); 5509 } 5510 5511 /// Get the initializer to use for each array element. 5512 Expr *getSubExpr() const { return cast<Expr>(SubExprs[1]); } 5513 5514 llvm::APInt getArraySize() const { 5515 return cast<ConstantArrayType>(getType()->castAsArrayTypeUnsafe()) 5516 ->getSize(); 5517 } 5518 5519 static bool classof(const Stmt *S) { 5520 return S->getStmtClass() == ArrayInitLoopExprClass; 5521 } 5522 5523 SourceLocation getBeginLoc() const LLVM_READONLY { 5524 return getCommonExpr()->getBeginLoc(); 5525 } 5526 SourceLocation getEndLoc() const LLVM_READONLY { 5527 return getCommonExpr()->getEndLoc(); 5528 } 5529 5530 child_range children() { 5531 return child_range(SubExprs, SubExprs + 2); 5532 } 5533 const_child_range children() const { 5534 return const_child_range(SubExprs, SubExprs + 2); 5535 } 5536 5537 friend class ASTReader; 5538 friend class ASTStmtReader; 5539 friend class ASTStmtWriter; 5540 }; 5541 5542 /// Represents the index of the current element of an array being 5543 /// initialized by an ArrayInitLoopExpr. This can only appear within the 5544 /// subexpression of an ArrayInitLoopExpr. 5545 class ArrayInitIndexExpr : public Expr { 5546 explicit ArrayInitIndexExpr(EmptyShell Empty) 5547 : Expr(ArrayInitIndexExprClass, Empty) {} 5548 5549 public: 5550 explicit ArrayInitIndexExpr(QualType T) 5551 : Expr(ArrayInitIndexExprClass, T, VK_PRValue, OK_Ordinary) { 5552 setDependence(ExprDependence::None); 5553 } 5554 5555 static bool classof(const Stmt *S) { 5556 return S->getStmtClass() == ArrayInitIndexExprClass; 5557 } 5558 5559 SourceLocation getBeginLoc() const LLVM_READONLY { return SourceLocation(); } 5560 SourceLocation getEndLoc() const LLVM_READONLY { return SourceLocation(); } 5561 5562 child_range children() { 5563 return child_range(child_iterator(), child_iterator()); 5564 } 5565 const_child_range children() const { 5566 return const_child_range(const_child_iterator(), const_child_iterator()); 5567 } 5568 5569 friend class ASTReader; 5570 friend class ASTStmtReader; 5571 }; 5572 5573 /// Represents an implicitly-generated value initialization of 5574 /// an object of a given type. 5575 /// 5576 /// Implicit value initializations occur within semantic initializer 5577 /// list expressions (InitListExpr) as placeholders for subobject 5578 /// initializations not explicitly specified by the user. 5579 /// 5580 /// \see InitListExpr 5581 class ImplicitValueInitExpr : public Expr { 5582 public: 5583 explicit ImplicitValueInitExpr(QualType ty) 5584 : Expr(ImplicitValueInitExprClass, ty, VK_PRValue, OK_Ordinary) { 5585 setDependence(computeDependence(this)); 5586 } 5587 5588 /// Construct an empty implicit value initialization. 5589 explicit ImplicitValueInitExpr(EmptyShell Empty) 5590 : Expr(ImplicitValueInitExprClass, Empty) { } 5591 5592 static bool classof(const Stmt *T) { 5593 return T->getStmtClass() == ImplicitValueInitExprClass; 5594 } 5595 5596 SourceLocation getBeginLoc() const LLVM_READONLY { return SourceLocation(); } 5597 SourceLocation getEndLoc() const LLVM_READONLY { return SourceLocation(); } 5598 5599 // Iterators 5600 child_range children() { 5601 return child_range(child_iterator(), child_iterator()); 5602 } 5603 const_child_range children() const { 5604 return const_child_range(const_child_iterator(), const_child_iterator()); 5605 } 5606 }; 5607 5608 class ParenListExpr final 5609 : public Expr, 5610 private llvm::TrailingObjects<ParenListExpr, Stmt *> { 5611 friend class ASTStmtReader; 5612 friend TrailingObjects; 5613 5614 /// The location of the left and right parentheses. 5615 SourceLocation LParenLoc, RParenLoc; 5616 5617 /// Build a paren list. 5618 ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs, 5619 SourceLocation RParenLoc); 5620 5621 /// Build an empty paren list. 5622 ParenListExpr(EmptyShell Empty, unsigned NumExprs); 5623 5624 public: 5625 /// Create a paren list. 5626 static ParenListExpr *Create(const ASTContext &Ctx, SourceLocation LParenLoc, 5627 ArrayRef<Expr *> Exprs, 5628 SourceLocation RParenLoc); 5629 5630 /// Create an empty paren list. 5631 static ParenListExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumExprs); 5632 5633 /// Return the number of expressions in this paren list. 5634 unsigned getNumExprs() const { return ParenListExprBits.NumExprs; } 5635 5636 Expr *getExpr(unsigned Init) { 5637 assert(Init < getNumExprs() && "Initializer access out of range!"); 5638 return getExprs()[Init]; 5639 } 5640 5641 const Expr *getExpr(unsigned Init) const { 5642 return const_cast<ParenListExpr *>(this)->getExpr(Init); 5643 } 5644 5645 Expr **getExprs() { 5646 return reinterpret_cast<Expr **>(getTrailingObjects<Stmt *>()); 5647 } 5648 5649 ArrayRef<Expr *> exprs() { return llvm::ArrayRef(getExprs(), getNumExprs()); } 5650 5651 SourceLocation getLParenLoc() const { return LParenLoc; } 5652 SourceLocation getRParenLoc() const { return RParenLoc; } 5653 SourceLocation getBeginLoc() const { return getLParenLoc(); } 5654 SourceLocation getEndLoc() const { return getRParenLoc(); } 5655 5656 static bool classof(const Stmt *T) { 5657 return T->getStmtClass() == ParenListExprClass; 5658 } 5659 5660 // Iterators 5661 child_range children() { 5662 return child_range(getTrailingObjects<Stmt *>(), 5663 getTrailingObjects<Stmt *>() + getNumExprs()); 5664 } 5665 const_child_range children() const { 5666 return const_child_range(getTrailingObjects<Stmt *>(), 5667 getTrailingObjects<Stmt *>() + getNumExprs()); 5668 } 5669 }; 5670 5671 /// Represents a C11 generic selection. 5672 /// 5673 /// A generic selection (C11 6.5.1.1) contains an unevaluated controlling 5674 /// expression, followed by one or more generic associations. Each generic 5675 /// association specifies a type name and an expression, or "default" and an 5676 /// expression (in which case it is known as a default generic association). 5677 /// The type and value of the generic selection are identical to those of its 5678 /// result expression, which is defined as the expression in the generic 5679 /// association with a type name that is compatible with the type of the 5680 /// controlling expression, or the expression in the default generic association 5681 /// if no types are compatible. For example: 5682 /// 5683 /// @code 5684 /// _Generic(X, double: 1, float: 2, default: 3) 5685 /// @endcode 5686 /// 5687 /// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f 5688 /// or 3 if "hello". 5689 /// 5690 /// As an extension, generic selections are allowed in C++, where the following 5691 /// additional semantics apply: 5692 /// 5693 /// Any generic selection whose controlling expression is type-dependent or 5694 /// which names a dependent type in its association list is result-dependent, 5695 /// which means that the choice of result expression is dependent. 5696 /// Result-dependent generic associations are both type- and value-dependent. 5697 /// 5698 /// We also allow an extended form in both C and C++ where the controlling 5699 /// predicate for the selection expression is a type rather than an expression. 5700 /// This type argument form does not perform any conversions for the 5701 /// controlling type, which makes it suitable for use with qualified type 5702 /// associations, which is not possible with the expression form. 5703 class GenericSelectionExpr final 5704 : public Expr, 5705 private llvm::TrailingObjects<GenericSelectionExpr, Stmt *, 5706 TypeSourceInfo *> { 5707 friend class ASTStmtReader; 5708 friend class ASTStmtWriter; 5709 friend TrailingObjects; 5710 5711 /// The number of association expressions and the index of the result 5712 /// expression in the case where the generic selection expression is not 5713 /// result-dependent. The result index is equal to ResultDependentIndex 5714 /// if and only if the generic selection expression is result-dependent. 5715 unsigned NumAssocs : 15; 5716 unsigned ResultIndex : 15; // NB: ResultDependentIndex is tied to this width. 5717 unsigned IsExprPredicate : 1; 5718 enum : unsigned { 5719 ResultDependentIndex = 0x7FFF 5720 }; 5721 5722 unsigned getIndexOfControllingExpression() const { 5723 // If controlled by an expression, the first offset into the Stmt * 5724 // trailing array is the controlling expression, the associated expressions 5725 // follow this. 5726 assert(isExprPredicate() && "Asking for the controlling expression of a " 5727 "selection expr predicated by a type"); 5728 return 0; 5729 } 5730 5731 unsigned getIndexOfControllingType() const { 5732 // If controlled by a type, the first offset into the TypeSourceInfo * 5733 // trailing array is the controlling type, the associated types follow this. 5734 assert(isTypePredicate() && "Asking for the controlling type of a " 5735 "selection expr predicated by an expression"); 5736 return 0; 5737 } 5738 5739 unsigned getIndexOfStartOfAssociatedExprs() const { 5740 // If the predicate is a type, then the associated expressions are the only 5741 // Stmt * in the trailing array, otherwise we need to offset past the 5742 // predicate expression. 5743 return (int)isExprPredicate(); 5744 } 5745 5746 unsigned getIndexOfStartOfAssociatedTypes() const { 5747 // If the predicate is a type, then the associated types follow it in the 5748 // trailing array. Otherwise, the associated types are the only 5749 // TypeSourceInfo * in the trailing array. 5750 return (int)isTypePredicate(); 5751 } 5752 5753 5754 /// The location of the "default" and of the right parenthesis. 5755 SourceLocation DefaultLoc, RParenLoc; 5756 5757 // GenericSelectionExpr is followed by several trailing objects. 5758 // They are (in order): 5759 // 5760 // * A single Stmt * for the controlling expression or a TypeSourceInfo * for 5761 // the controlling type, depending on the result of isTypePredicate() or 5762 // isExprPredicate(). 5763 // * An array of getNumAssocs() Stmt * for the association expressions. 5764 // * An array of getNumAssocs() TypeSourceInfo *, one for each of the 5765 // association expressions. 5766 unsigned numTrailingObjects(OverloadToken<Stmt *>) const { 5767 // Add one to account for the controlling expression; the remainder 5768 // are the associated expressions. 5769 return getNumAssocs() + (int)isExprPredicate(); 5770 } 5771 5772 unsigned numTrailingObjects(OverloadToken<TypeSourceInfo *>) const { 5773 // Add one to account for the controlling type predicate, the remainder 5774 // are the associated types. 5775 return getNumAssocs() + (int)isTypePredicate(); 5776 } 5777 5778 template <bool Const> class AssociationIteratorTy; 5779 /// Bundle together an association expression and its TypeSourceInfo. 5780 /// The Const template parameter is for the const and non-const versions 5781 /// of AssociationTy. 5782 template <bool Const> class AssociationTy { 5783 friend class GenericSelectionExpr; 5784 template <bool OtherConst> friend class AssociationIteratorTy; 5785 using ExprPtrTy = std::conditional_t<Const, const Expr *, Expr *>; 5786 using TSIPtrTy = 5787 std::conditional_t<Const, const TypeSourceInfo *, TypeSourceInfo *>; 5788 ExprPtrTy E; 5789 TSIPtrTy TSI; 5790 bool Selected; 5791 AssociationTy(ExprPtrTy E, TSIPtrTy TSI, bool Selected) 5792 : E(E), TSI(TSI), Selected(Selected) {} 5793 5794 public: 5795 ExprPtrTy getAssociationExpr() const { return E; } 5796 TSIPtrTy getTypeSourceInfo() const { return TSI; } 5797 QualType getType() const { return TSI ? TSI->getType() : QualType(); } 5798 bool isSelected() const { return Selected; } 5799 AssociationTy *operator->() { return this; } 5800 const AssociationTy *operator->() const { return this; } 5801 }; // class AssociationTy 5802 5803 /// Iterator over const and non-const Association objects. The Association 5804 /// objects are created on the fly when the iterator is dereferenced. 5805 /// This abstract over how exactly the association expressions and the 5806 /// corresponding TypeSourceInfo * are stored. 5807 template <bool Const> 5808 class AssociationIteratorTy 5809 : public llvm::iterator_facade_base< 5810 AssociationIteratorTy<Const>, std::input_iterator_tag, 5811 AssociationTy<Const>, std::ptrdiff_t, AssociationTy<Const>, 5812 AssociationTy<Const>> { 5813 friend class GenericSelectionExpr; 5814 // FIXME: This iterator could conceptually be a random access iterator, and 5815 // it would be nice if we could strengthen the iterator category someday. 5816 // However this iterator does not satisfy two requirements of forward 5817 // iterators: 5818 // a) reference = T& or reference = const T& 5819 // b) If It1 and It2 are both dereferenceable, then It1 == It2 if and only 5820 // if *It1 and *It2 are bound to the same objects. 5821 // An alternative design approach was discussed during review; 5822 // store an Association object inside the iterator, and return a reference 5823 // to it when dereferenced. This idea was discarded beacuse of nasty 5824 // lifetime issues: 5825 // AssociationIterator It = ...; 5826 // const Association &Assoc = *It++; // Oops, Assoc is dangling. 5827 using BaseTy = typename AssociationIteratorTy::iterator_facade_base; 5828 using StmtPtrPtrTy = 5829 std::conditional_t<Const, const Stmt *const *, Stmt **>; 5830 using TSIPtrPtrTy = std::conditional_t<Const, const TypeSourceInfo *const *, 5831 TypeSourceInfo **>; 5832 StmtPtrPtrTy E; // = nullptr; FIXME: Once support for gcc 4.8 is dropped. 5833 TSIPtrPtrTy TSI; // Kept in sync with E. 5834 unsigned Offset = 0, SelectedOffset = 0; 5835 AssociationIteratorTy(StmtPtrPtrTy E, TSIPtrPtrTy TSI, unsigned Offset, 5836 unsigned SelectedOffset) 5837 : E(E), TSI(TSI), Offset(Offset), SelectedOffset(SelectedOffset) {} 5838 5839 public: 5840 AssociationIteratorTy() : E(nullptr), TSI(nullptr) {} 5841 typename BaseTy::reference operator*() const { 5842 return AssociationTy<Const>(cast<Expr>(*E), *TSI, 5843 Offset == SelectedOffset); 5844 } 5845 typename BaseTy::pointer operator->() const { return **this; } 5846 using BaseTy::operator++; 5847 AssociationIteratorTy &operator++() { 5848 ++E; 5849 ++TSI; 5850 ++Offset; 5851 return *this; 5852 } 5853 bool operator==(AssociationIteratorTy Other) const { return E == Other.E; } 5854 }; // class AssociationIterator 5855 5856 /// Build a non-result-dependent generic selection expression accepting an 5857 /// expression predicate. 5858 GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc, 5859 Expr *ControllingExpr, 5860 ArrayRef<TypeSourceInfo *> AssocTypes, 5861 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc, 5862 SourceLocation RParenLoc, 5863 bool ContainsUnexpandedParameterPack, 5864 unsigned ResultIndex); 5865 5866 /// Build a result-dependent generic selection expression accepting an 5867 /// expression predicate. 5868 GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc, 5869 Expr *ControllingExpr, 5870 ArrayRef<TypeSourceInfo *> AssocTypes, 5871 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc, 5872 SourceLocation RParenLoc, 5873 bool ContainsUnexpandedParameterPack); 5874 5875 /// Build a non-result-dependent generic selection expression accepting a 5876 /// type predicate. 5877 GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc, 5878 TypeSourceInfo *ControllingType, 5879 ArrayRef<TypeSourceInfo *> AssocTypes, 5880 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc, 5881 SourceLocation RParenLoc, 5882 bool ContainsUnexpandedParameterPack, 5883 unsigned ResultIndex); 5884 5885 /// Build a result-dependent generic selection expression accepting a type 5886 /// predicate. 5887 GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc, 5888 TypeSourceInfo *ControllingType, 5889 ArrayRef<TypeSourceInfo *> AssocTypes, 5890 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc, 5891 SourceLocation RParenLoc, 5892 bool ContainsUnexpandedParameterPack); 5893 5894 /// Build an empty generic selection expression for deserialization. 5895 explicit GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs); 5896 5897 public: 5898 /// Create a non-result-dependent generic selection expression accepting an 5899 /// expression predicate. 5900 static GenericSelectionExpr * 5901 Create(const ASTContext &Context, SourceLocation GenericLoc, 5902 Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> AssocTypes, 5903 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc, 5904 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack, 5905 unsigned ResultIndex); 5906 5907 /// Create a result-dependent generic selection expression accepting an 5908 /// expression predicate. 5909 static GenericSelectionExpr * 5910 Create(const ASTContext &Context, SourceLocation GenericLoc, 5911 Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> AssocTypes, 5912 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc, 5913 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack); 5914 5915 /// Create a non-result-dependent generic selection expression accepting a 5916 /// type predicate. 5917 static GenericSelectionExpr * 5918 Create(const ASTContext &Context, SourceLocation GenericLoc, 5919 TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes, 5920 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc, 5921 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack, 5922 unsigned ResultIndex); 5923 5924 /// Create a result-dependent generic selection expression accepting a type 5925 /// predicate 5926 static GenericSelectionExpr * 5927 Create(const ASTContext &Context, SourceLocation GenericLoc, 5928 TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes, 5929 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc, 5930 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack); 5931 5932 /// Create an empty generic selection expression for deserialization. 5933 static GenericSelectionExpr *CreateEmpty(const ASTContext &Context, 5934 unsigned NumAssocs); 5935 5936 using Association = AssociationTy<false>; 5937 using ConstAssociation = AssociationTy<true>; 5938 using AssociationIterator = AssociationIteratorTy<false>; 5939 using ConstAssociationIterator = AssociationIteratorTy<true>; 5940 using association_range = llvm::iterator_range<AssociationIterator>; 5941 using const_association_range = 5942 llvm::iterator_range<ConstAssociationIterator>; 5943 5944 /// The number of association expressions. 5945 unsigned getNumAssocs() const { return NumAssocs; } 5946 5947 /// The zero-based index of the result expression's generic association in 5948 /// the generic selection's association list. Defined only if the 5949 /// generic selection is not result-dependent. 5950 unsigned getResultIndex() const { 5951 assert(!isResultDependent() && 5952 "Generic selection is result-dependent but getResultIndex called!"); 5953 return ResultIndex; 5954 } 5955 5956 /// Whether this generic selection is result-dependent. 5957 bool isResultDependent() const { return ResultIndex == ResultDependentIndex; } 5958 5959 /// Whether this generic selection uses an expression as its controlling 5960 /// argument. 5961 bool isExprPredicate() const { return IsExprPredicate; } 5962 /// Whether this generic selection uses a type as its controlling argument. 5963 bool isTypePredicate() const { return !IsExprPredicate; } 5964 5965 /// Return the controlling expression of this generic selection expression. 5966 /// Only valid to call if the selection expression used an expression as its 5967 /// controlling argument. 5968 Expr *getControllingExpr() { 5969 return cast<Expr>( 5970 getTrailingObjects<Stmt *>()[getIndexOfControllingExpression()]); 5971 } 5972 const Expr *getControllingExpr() const { 5973 return cast<Expr>( 5974 getTrailingObjects<Stmt *>()[getIndexOfControllingExpression()]); 5975 } 5976 5977 /// Return the controlling type of this generic selection expression. Only 5978 /// valid to call if the selection expression used a type as its controlling 5979 /// argument. 5980 TypeSourceInfo *getControllingType() { 5981 return getTrailingObjects<TypeSourceInfo *>()[getIndexOfControllingType()]; 5982 } 5983 const TypeSourceInfo* getControllingType() const { 5984 return getTrailingObjects<TypeSourceInfo *>()[getIndexOfControllingType()]; 5985 } 5986 5987 /// Return the result expression of this controlling expression. Defined if 5988 /// and only if the generic selection expression is not result-dependent. 5989 Expr *getResultExpr() { 5990 return cast<Expr>( 5991 getTrailingObjects<Stmt *>()[getIndexOfStartOfAssociatedExprs() + 5992 getResultIndex()]); 5993 } 5994 const Expr *getResultExpr() const { 5995 return cast<Expr>( 5996 getTrailingObjects<Stmt *>()[getIndexOfStartOfAssociatedExprs() + 5997 getResultIndex()]); 5998 } 5999 6000 ArrayRef<Expr *> getAssocExprs() const { 6001 return {reinterpret_cast<Expr *const *>(getTrailingObjects<Stmt *>() + 6002 getIndexOfStartOfAssociatedExprs()), 6003 NumAssocs}; 6004 } 6005 ArrayRef<TypeSourceInfo *> getAssocTypeSourceInfos() const { 6006 return {getTrailingObjects<TypeSourceInfo *>() + 6007 getIndexOfStartOfAssociatedTypes(), 6008 NumAssocs}; 6009 } 6010 6011 /// Return the Ith association expression with its TypeSourceInfo, 6012 /// bundled together in GenericSelectionExpr::(Const)Association. 6013 Association getAssociation(unsigned I) { 6014 assert(I < getNumAssocs() && 6015 "Out-of-range index in GenericSelectionExpr::getAssociation!"); 6016 return Association( 6017 cast<Expr>( 6018 getTrailingObjects<Stmt *>()[getIndexOfStartOfAssociatedExprs() + 6019 I]), 6020 getTrailingObjects< 6021 TypeSourceInfo *>()[getIndexOfStartOfAssociatedTypes() + I], 6022 !isResultDependent() && (getResultIndex() == I)); 6023 } 6024 ConstAssociation getAssociation(unsigned I) const { 6025 assert(I < getNumAssocs() && 6026 "Out-of-range index in GenericSelectionExpr::getAssociation!"); 6027 return ConstAssociation( 6028 cast<Expr>( 6029 getTrailingObjects<Stmt *>()[getIndexOfStartOfAssociatedExprs() + 6030 I]), 6031 getTrailingObjects< 6032 TypeSourceInfo *>()[getIndexOfStartOfAssociatedTypes() + I], 6033 !isResultDependent() && (getResultIndex() == I)); 6034 } 6035 6036 association_range associations() { 6037 AssociationIterator Begin(getTrailingObjects<Stmt *>() + 6038 getIndexOfStartOfAssociatedExprs(), 6039 getTrailingObjects<TypeSourceInfo *>() + 6040 getIndexOfStartOfAssociatedTypes(), 6041 /*Offset=*/0, ResultIndex); 6042 AssociationIterator End(Begin.E + NumAssocs, Begin.TSI + NumAssocs, 6043 /*Offset=*/NumAssocs, ResultIndex); 6044 return llvm::make_range(Begin, End); 6045 } 6046 6047 const_association_range associations() const { 6048 ConstAssociationIterator Begin(getTrailingObjects<Stmt *>() + 6049 getIndexOfStartOfAssociatedExprs(), 6050 getTrailingObjects<TypeSourceInfo *>() + 6051 getIndexOfStartOfAssociatedTypes(), 6052 /*Offset=*/0, ResultIndex); 6053 ConstAssociationIterator End(Begin.E + NumAssocs, Begin.TSI + NumAssocs, 6054 /*Offset=*/NumAssocs, ResultIndex); 6055 return llvm::make_range(Begin, End); 6056 } 6057 6058 SourceLocation getGenericLoc() const { 6059 return GenericSelectionExprBits.GenericLoc; 6060 } 6061 SourceLocation getDefaultLoc() const { return DefaultLoc; } 6062 SourceLocation getRParenLoc() const { return RParenLoc; } 6063 SourceLocation getBeginLoc() const { return getGenericLoc(); } 6064 SourceLocation getEndLoc() const { return getRParenLoc(); } 6065 6066 static bool classof(const Stmt *T) { 6067 return T->getStmtClass() == GenericSelectionExprClass; 6068 } 6069 6070 child_range children() { 6071 return child_range(getTrailingObjects<Stmt *>(), 6072 getTrailingObjects<Stmt *>() + 6073 numTrailingObjects(OverloadToken<Stmt *>())); 6074 } 6075 const_child_range children() const { 6076 return const_child_range(getTrailingObjects<Stmt *>(), 6077 getTrailingObjects<Stmt *>() + 6078 numTrailingObjects(OverloadToken<Stmt *>())); 6079 } 6080 }; 6081 6082 //===----------------------------------------------------------------------===// 6083 // Clang Extensions 6084 //===----------------------------------------------------------------------===// 6085 6086 /// ExtVectorElementExpr - This represents access to specific elements of a 6087 /// vector, and may occur on the left hand side or right hand side. For example 6088 /// the following is legal: "V.xy = V.zw" if V is a 4 element extended vector. 6089 /// 6090 /// Note that the base may have either vector or pointer to vector type, just 6091 /// like a struct field reference. 6092 /// 6093 class ExtVectorElementExpr : public Expr { 6094 Stmt *Base; 6095 IdentifierInfo *Accessor; 6096 SourceLocation AccessorLoc; 6097 public: 6098 ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base, 6099 IdentifierInfo &accessor, SourceLocation loc) 6100 : Expr(ExtVectorElementExprClass, ty, VK, 6101 (VK == VK_PRValue ? OK_Ordinary : OK_VectorComponent)), 6102 Base(base), Accessor(&accessor), AccessorLoc(loc) { 6103 setDependence(computeDependence(this)); 6104 } 6105 6106 /// Build an empty vector element expression. 6107 explicit ExtVectorElementExpr(EmptyShell Empty) 6108 : Expr(ExtVectorElementExprClass, Empty) { } 6109 6110 const Expr *getBase() const { return cast<Expr>(Base); } 6111 Expr *getBase() { return cast<Expr>(Base); } 6112 void setBase(Expr *E) { Base = E; } 6113 6114 IdentifierInfo &getAccessor() const { return *Accessor; } 6115 void setAccessor(IdentifierInfo *II) { Accessor = II; } 6116 6117 SourceLocation getAccessorLoc() const { return AccessorLoc; } 6118 void setAccessorLoc(SourceLocation L) { AccessorLoc = L; } 6119 6120 /// getNumElements - Get the number of components being selected. 6121 unsigned getNumElements() const; 6122 6123 /// containsDuplicateElements - Return true if any element access is 6124 /// repeated. 6125 bool containsDuplicateElements() const; 6126 6127 /// getEncodedElementAccess - Encode the elements accessed into an llvm 6128 /// aggregate Constant of ConstantInt(s). 6129 void getEncodedElementAccess(SmallVectorImpl<uint32_t> &Elts) const; 6130 6131 SourceLocation getBeginLoc() const LLVM_READONLY { 6132 return getBase()->getBeginLoc(); 6133 } 6134 SourceLocation getEndLoc() const LLVM_READONLY { return AccessorLoc; } 6135 6136 /// isArrow - Return true if the base expression is a pointer to vector, 6137 /// return false if the base expression is a vector. 6138 bool isArrow() const; 6139 6140 static bool classof(const Stmt *T) { 6141 return T->getStmtClass() == ExtVectorElementExprClass; 6142 } 6143 6144 // Iterators 6145 child_range children() { return child_range(&Base, &Base+1); } 6146 const_child_range children() const { 6147 return const_child_range(&Base, &Base + 1); 6148 } 6149 }; 6150 6151 /// BlockExpr - Adaptor class for mixing a BlockDecl with expressions. 6152 /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body } 6153 class BlockExpr : public Expr { 6154 protected: 6155 BlockDecl *TheBlock; 6156 public: 6157 BlockExpr(BlockDecl *BD, QualType ty) 6158 : Expr(BlockExprClass, ty, VK_PRValue, OK_Ordinary), TheBlock(BD) { 6159 setDependence(computeDependence(this)); 6160 } 6161 6162 /// Build an empty block expression. 6163 explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { } 6164 6165 const BlockDecl *getBlockDecl() const { return TheBlock; } 6166 BlockDecl *getBlockDecl() { return TheBlock; } 6167 void setBlockDecl(BlockDecl *BD) { TheBlock = BD; } 6168 6169 // Convenience functions for probing the underlying BlockDecl. 6170 SourceLocation getCaretLocation() const; 6171 const Stmt *getBody() const; 6172 Stmt *getBody(); 6173 6174 SourceLocation getBeginLoc() const LLVM_READONLY { 6175 return getCaretLocation(); 6176 } 6177 SourceLocation getEndLoc() const LLVM_READONLY { 6178 return getBody()->getEndLoc(); 6179 } 6180 6181 /// getFunctionType - Return the underlying function type for this block. 6182 const FunctionProtoType *getFunctionType() const; 6183 6184 static bool classof(const Stmt *T) { 6185 return T->getStmtClass() == BlockExprClass; 6186 } 6187 6188 // Iterators 6189 child_range children() { 6190 return child_range(child_iterator(), child_iterator()); 6191 } 6192 const_child_range children() const { 6193 return const_child_range(const_child_iterator(), const_child_iterator()); 6194 } 6195 }; 6196 6197 /// Copy initialization expr of a __block variable and a boolean flag that 6198 /// indicates whether the expression can throw. 6199 struct BlockVarCopyInit { 6200 BlockVarCopyInit() = default; 6201 BlockVarCopyInit(Expr *CopyExpr, bool CanThrow) 6202 : ExprAndFlag(CopyExpr, CanThrow) {} 6203 void setExprAndFlag(Expr *CopyExpr, bool CanThrow) { 6204 ExprAndFlag.setPointerAndInt(CopyExpr, CanThrow); 6205 } 6206 Expr *getCopyExpr() const { return ExprAndFlag.getPointer(); } 6207 bool canThrow() const { return ExprAndFlag.getInt(); } 6208 llvm::PointerIntPair<Expr *, 1, bool> ExprAndFlag; 6209 }; 6210 6211 /// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2] 6212 /// This AST node provides support for reinterpreting a type to another 6213 /// type of the same size. 6214 class AsTypeExpr : public Expr { 6215 private: 6216 Stmt *SrcExpr; 6217 SourceLocation BuiltinLoc, RParenLoc; 6218 6219 friend class ASTReader; 6220 friend class ASTStmtReader; 6221 explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {} 6222 6223 public: 6224 AsTypeExpr(Expr *SrcExpr, QualType DstType, ExprValueKind VK, 6225 ExprObjectKind OK, SourceLocation BuiltinLoc, 6226 SourceLocation RParenLoc) 6227 : Expr(AsTypeExprClass, DstType, VK, OK), SrcExpr(SrcExpr), 6228 BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) { 6229 setDependence(computeDependence(this)); 6230 } 6231 6232 /// getSrcExpr - Return the Expr to be converted. 6233 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); } 6234 6235 /// getBuiltinLoc - Return the location of the __builtin_astype token. 6236 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 6237 6238 /// getRParenLoc - Return the location of final right parenthesis. 6239 SourceLocation getRParenLoc() const { return RParenLoc; } 6240 6241 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; } 6242 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; } 6243 6244 static bool classof(const Stmt *T) { 6245 return T->getStmtClass() == AsTypeExprClass; 6246 } 6247 6248 // Iterators 6249 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); } 6250 const_child_range children() const { 6251 return const_child_range(&SrcExpr, &SrcExpr + 1); 6252 } 6253 }; 6254 6255 /// PseudoObjectExpr - An expression which accesses a pseudo-object 6256 /// l-value. A pseudo-object is an abstract object, accesses to which 6257 /// are translated to calls. The pseudo-object expression has a 6258 /// syntactic form, which shows how the expression was actually 6259 /// written in the source code, and a semantic form, which is a series 6260 /// of expressions to be executed in order which detail how the 6261 /// operation is actually evaluated. Optionally, one of the semantic 6262 /// forms may also provide a result value for the expression. 6263 /// 6264 /// If any of the semantic-form expressions is an OpaqueValueExpr, 6265 /// that OVE is required to have a source expression, and it is bound 6266 /// to the result of that source expression. Such OVEs may appear 6267 /// only in subsequent semantic-form expressions and as 6268 /// sub-expressions of the syntactic form. 6269 /// 6270 /// PseudoObjectExpr should be used only when an operation can be 6271 /// usefully described in terms of fairly simple rewrite rules on 6272 /// objects and functions that are meant to be used by end-developers. 6273 /// For example, under the Itanium ABI, dynamic casts are implemented 6274 /// as a call to a runtime function called __dynamic_cast; using this 6275 /// class to describe that would be inappropriate because that call is 6276 /// not really part of the user-visible semantics, and instead the 6277 /// cast is properly reflected in the AST and IR-generation has been 6278 /// taught to generate the call as necessary. In contrast, an 6279 /// Objective-C property access is semantically defined to be 6280 /// equivalent to a particular message send, and this is very much 6281 /// part of the user model. The name of this class encourages this 6282 /// modelling design. 6283 class PseudoObjectExpr final 6284 : public Expr, 6285 private llvm::TrailingObjects<PseudoObjectExpr, Expr *> { 6286 // PseudoObjectExprBits.NumSubExprs - The number of sub-expressions. 6287 // Always at least two, because the first sub-expression is the 6288 // syntactic form. 6289 6290 // PseudoObjectExprBits.ResultIndex - The index of the 6291 // sub-expression holding the result. 0 means the result is void, 6292 // which is unambiguous because it's the index of the syntactic 6293 // form. Note that this is therefore 1 higher than the value passed 6294 // in to Create, which is an index within the semantic forms. 6295 // Note also that ASTStmtWriter assumes this encoding. 6296 6297 Expr **getSubExprsBuffer() { return getTrailingObjects<Expr *>(); } 6298 const Expr * const *getSubExprsBuffer() const { 6299 return getTrailingObjects<Expr *>(); 6300 } 6301 6302 PseudoObjectExpr(QualType type, ExprValueKind VK, 6303 Expr *syntactic, ArrayRef<Expr*> semantic, 6304 unsigned resultIndex); 6305 6306 PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs); 6307 6308 unsigned getNumSubExprs() const { 6309 return PseudoObjectExprBits.NumSubExprs; 6310 } 6311 6312 public: 6313 /// NoResult - A value for the result index indicating that there is 6314 /// no semantic result. 6315 enum : unsigned { NoResult = ~0U }; 6316 6317 static PseudoObjectExpr *Create(const ASTContext &Context, Expr *syntactic, 6318 ArrayRef<Expr*> semantic, 6319 unsigned resultIndex); 6320 6321 static PseudoObjectExpr *Create(const ASTContext &Context, EmptyShell shell, 6322 unsigned numSemanticExprs); 6323 6324 /// Return the syntactic form of this expression, i.e. the 6325 /// expression it actually looks like. Likely to be expressed in 6326 /// terms of OpaqueValueExprs bound in the semantic form. 6327 Expr *getSyntacticForm() { return getSubExprsBuffer()[0]; } 6328 const Expr *getSyntacticForm() const { return getSubExprsBuffer()[0]; } 6329 6330 /// Return the index of the result-bearing expression into the semantics 6331 /// expressions, or PseudoObjectExpr::NoResult if there is none. 6332 unsigned getResultExprIndex() const { 6333 if (PseudoObjectExprBits.ResultIndex == 0) return NoResult; 6334 return PseudoObjectExprBits.ResultIndex - 1; 6335 } 6336 6337 /// Return the result-bearing expression, or null if there is none. 6338 Expr *getResultExpr() { 6339 if (PseudoObjectExprBits.ResultIndex == 0) 6340 return nullptr; 6341 return getSubExprsBuffer()[PseudoObjectExprBits.ResultIndex]; 6342 } 6343 const Expr *getResultExpr() const { 6344 return const_cast<PseudoObjectExpr*>(this)->getResultExpr(); 6345 } 6346 6347 unsigned getNumSemanticExprs() const { return getNumSubExprs() - 1; } 6348 6349 typedef Expr * const *semantics_iterator; 6350 typedef const Expr * const *const_semantics_iterator; 6351 semantics_iterator semantics_begin() { 6352 return getSubExprsBuffer() + 1; 6353 } 6354 const_semantics_iterator semantics_begin() const { 6355 return getSubExprsBuffer() + 1; 6356 } 6357 semantics_iterator semantics_end() { 6358 return getSubExprsBuffer() + getNumSubExprs(); 6359 } 6360 const_semantics_iterator semantics_end() const { 6361 return getSubExprsBuffer() + getNumSubExprs(); 6362 } 6363 6364 ArrayRef<Expr*> semantics() { 6365 return ArrayRef(semantics_begin(), semantics_end()); 6366 } 6367 ArrayRef<const Expr*> semantics() const { 6368 return ArrayRef(semantics_begin(), semantics_end()); 6369 } 6370 6371 Expr *getSemanticExpr(unsigned index) { 6372 assert(index + 1 < getNumSubExprs()); 6373 return getSubExprsBuffer()[index + 1]; 6374 } 6375 const Expr *getSemanticExpr(unsigned index) const { 6376 return const_cast<PseudoObjectExpr*>(this)->getSemanticExpr(index); 6377 } 6378 6379 SourceLocation getExprLoc() const LLVM_READONLY { 6380 return getSyntacticForm()->getExprLoc(); 6381 } 6382 6383 SourceLocation getBeginLoc() const LLVM_READONLY { 6384 return getSyntacticForm()->getBeginLoc(); 6385 } 6386 SourceLocation getEndLoc() const LLVM_READONLY { 6387 return getSyntacticForm()->getEndLoc(); 6388 } 6389 6390 child_range children() { 6391 const_child_range CCR = 6392 const_cast<const PseudoObjectExpr *>(this)->children(); 6393 return child_range(cast_away_const(CCR.begin()), 6394 cast_away_const(CCR.end())); 6395 } 6396 const_child_range children() const { 6397 Stmt *const *cs = const_cast<Stmt *const *>( 6398 reinterpret_cast<const Stmt *const *>(getSubExprsBuffer())); 6399 return const_child_range(cs, cs + getNumSubExprs()); 6400 } 6401 6402 static bool classof(const Stmt *T) { 6403 return T->getStmtClass() == PseudoObjectExprClass; 6404 } 6405 6406 friend TrailingObjects; 6407 friend class ASTStmtReader; 6408 }; 6409 6410 /// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, 6411 /// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the 6412 /// similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>, 6413 /// and corresponding __opencl_atomic_* for OpenCL 2.0. 6414 /// All of these instructions take one primary pointer, at least one memory 6415 /// order. The instructions for which getScopeModel returns non-null value 6416 /// take one synch scope. 6417 class AtomicExpr : public Expr { 6418 public: 6419 enum AtomicOp { 6420 #define BUILTIN(ID, TYPE, ATTRS) 6421 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) AO ## ID, 6422 #include "clang/Basic/Builtins.def" 6423 // Avoid trailing comma 6424 BI_First = 0 6425 }; 6426 6427 private: 6428 /// Location of sub-expressions. 6429 /// The location of Scope sub-expression is NumSubExprs - 1, which is 6430 /// not fixed, therefore is not defined in enum. 6431 enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, WEAK, END_EXPR }; 6432 Stmt *SubExprs[END_EXPR + 1]; 6433 unsigned NumSubExprs; 6434 SourceLocation BuiltinLoc, RParenLoc; 6435 AtomicOp Op; 6436 6437 friend class ASTStmtReader; 6438 public: 6439 AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args, QualType t, 6440 AtomicOp op, SourceLocation RP); 6441 6442 /// Determine the number of arguments the specified atomic builtin 6443 /// should have. 6444 static unsigned getNumSubExprs(AtomicOp Op); 6445 6446 /// Build an empty AtomicExpr. 6447 explicit AtomicExpr(EmptyShell Empty) : Expr(AtomicExprClass, Empty) { } 6448 6449 Expr *getPtr() const { 6450 return cast<Expr>(SubExprs[PTR]); 6451 } 6452 Expr *getOrder() const { 6453 return cast<Expr>(SubExprs[ORDER]); 6454 } 6455 Expr *getScope() const { 6456 assert(getScopeModel() && "No scope"); 6457 return cast<Expr>(SubExprs[NumSubExprs - 1]); 6458 } 6459 Expr *getVal1() const { 6460 if (Op == AO__c11_atomic_init || Op == AO__opencl_atomic_init) 6461 return cast<Expr>(SubExprs[ORDER]); 6462 assert(NumSubExprs > VAL1); 6463 return cast<Expr>(SubExprs[VAL1]); 6464 } 6465 Expr *getOrderFail() const { 6466 assert(NumSubExprs > ORDER_FAIL); 6467 return cast<Expr>(SubExprs[ORDER_FAIL]); 6468 } 6469 Expr *getVal2() const { 6470 if (Op == AO__atomic_exchange) 6471 return cast<Expr>(SubExprs[ORDER_FAIL]); 6472 assert(NumSubExprs > VAL2); 6473 return cast<Expr>(SubExprs[VAL2]); 6474 } 6475 Expr *getWeak() const { 6476 assert(NumSubExprs > WEAK); 6477 return cast<Expr>(SubExprs[WEAK]); 6478 } 6479 QualType getValueType() const; 6480 6481 AtomicOp getOp() const { return Op; } 6482 unsigned getNumSubExprs() const { return NumSubExprs; } 6483 6484 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); } 6485 const Expr * const *getSubExprs() const { 6486 return reinterpret_cast<Expr * const *>(SubExprs); 6487 } 6488 6489 bool isVolatile() const { 6490 return getPtr()->getType()->getPointeeType().isVolatileQualified(); 6491 } 6492 6493 bool isCmpXChg() const { 6494 return getOp() == AO__c11_atomic_compare_exchange_strong || 6495 getOp() == AO__c11_atomic_compare_exchange_weak || 6496 getOp() == AO__hip_atomic_compare_exchange_strong || 6497 getOp() == AO__opencl_atomic_compare_exchange_strong || 6498 getOp() == AO__opencl_atomic_compare_exchange_weak || 6499 getOp() == AO__hip_atomic_compare_exchange_weak || 6500 getOp() == AO__atomic_compare_exchange || 6501 getOp() == AO__atomic_compare_exchange_n; 6502 } 6503 6504 bool isOpenCL() const { 6505 return getOp() >= AO__opencl_atomic_init && 6506 getOp() <= AO__opencl_atomic_fetch_max; 6507 } 6508 6509 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 6510 SourceLocation getRParenLoc() const { return RParenLoc; } 6511 6512 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; } 6513 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; } 6514 6515 static bool classof(const Stmt *T) { 6516 return T->getStmtClass() == AtomicExprClass; 6517 } 6518 6519 // Iterators 6520 child_range children() { 6521 return child_range(SubExprs, SubExprs+NumSubExprs); 6522 } 6523 const_child_range children() const { 6524 return const_child_range(SubExprs, SubExprs + NumSubExprs); 6525 } 6526 6527 /// Get atomic scope model for the atomic op code. 6528 /// \return empty atomic scope model if the atomic op code does not have 6529 /// scope operand. 6530 static std::unique_ptr<AtomicScopeModel> getScopeModel(AtomicOp Op) { 6531 auto Kind = 6532 (Op >= AO__opencl_atomic_load && Op <= AO__opencl_atomic_fetch_max) 6533 ? AtomicScopeModelKind::OpenCL 6534 : (Op >= AO__hip_atomic_load && Op <= AO__hip_atomic_fetch_max) 6535 ? AtomicScopeModelKind::HIP 6536 : AtomicScopeModelKind::None; 6537 return AtomicScopeModel::create(Kind); 6538 } 6539 6540 /// Get atomic scope model. 6541 /// \return empty atomic scope model if this atomic expression does not have 6542 /// scope operand. 6543 std::unique_ptr<AtomicScopeModel> getScopeModel() const { 6544 return getScopeModel(getOp()); 6545 } 6546 }; 6547 6548 /// TypoExpr - Internal placeholder for expressions where typo correction 6549 /// still needs to be performed and/or an error diagnostic emitted. 6550 class TypoExpr : public Expr { 6551 // The location for the typo name. 6552 SourceLocation TypoLoc; 6553 6554 public: 6555 TypoExpr(QualType T, SourceLocation TypoLoc) 6556 : Expr(TypoExprClass, T, VK_LValue, OK_Ordinary), TypoLoc(TypoLoc) { 6557 assert(T->isDependentType() && "TypoExpr given a non-dependent type"); 6558 setDependence(ExprDependence::TypeValueInstantiation | 6559 ExprDependence::Error); 6560 } 6561 6562 child_range children() { 6563 return child_range(child_iterator(), child_iterator()); 6564 } 6565 const_child_range children() const { 6566 return const_child_range(const_child_iterator(), const_child_iterator()); 6567 } 6568 6569 SourceLocation getBeginLoc() const LLVM_READONLY { return TypoLoc; } 6570 SourceLocation getEndLoc() const LLVM_READONLY { return TypoLoc; } 6571 6572 static bool classof(const Stmt *T) { 6573 return T->getStmtClass() == TypoExprClass; 6574 } 6575 6576 }; 6577 6578 /// Frontend produces RecoveryExprs on semantic errors that prevent creating 6579 /// other well-formed expressions. E.g. when type-checking of a binary operator 6580 /// fails, we cannot produce a BinaryOperator expression. Instead, we can choose 6581 /// to produce a recovery expression storing left and right operands. 6582 /// 6583 /// RecoveryExpr does not have any semantic meaning in C++, it is only useful to 6584 /// preserve expressions in AST that would otherwise be dropped. It captures 6585 /// subexpressions of some expression that we could not construct and source 6586 /// range covered by the expression. 6587 /// 6588 /// By default, RecoveryExpr uses dependence-bits to take advantage of existing 6589 /// machinery to deal with dependent code in C++, e.g. RecoveryExpr is preserved 6590 /// in `decltype(<broken-expr>)` as part of the `DependentDecltypeType`. In 6591 /// addition to that, clang does not report most errors on dependent 6592 /// expressions, so we get rid of bogus errors for free. However, note that 6593 /// unlike other dependent expressions, RecoveryExpr can be produced in 6594 /// non-template contexts. 6595 /// 6596 /// We will preserve the type in RecoveryExpr when the type is known, e.g. 6597 /// preserving the return type for a broken non-overloaded function call, a 6598 /// overloaded call where all candidates have the same return type. In this 6599 /// case, the expression is not type-dependent (unless the known type is itself 6600 /// dependent) 6601 /// 6602 /// One can also reliably suppress all bogus errors on expressions containing 6603 /// recovery expressions by examining results of Expr::containsErrors(). 6604 class RecoveryExpr final : public Expr, 6605 private llvm::TrailingObjects<RecoveryExpr, Expr *> { 6606 public: 6607 static RecoveryExpr *Create(ASTContext &Ctx, QualType T, 6608 SourceLocation BeginLoc, SourceLocation EndLoc, 6609 ArrayRef<Expr *> SubExprs); 6610 static RecoveryExpr *CreateEmpty(ASTContext &Ctx, unsigned NumSubExprs); 6611 6612 ArrayRef<Expr *> subExpressions() { 6613 auto *B = getTrailingObjects<Expr *>(); 6614 return llvm::ArrayRef(B, B + NumExprs); 6615 } 6616 6617 ArrayRef<const Expr *> subExpressions() const { 6618 return const_cast<RecoveryExpr *>(this)->subExpressions(); 6619 } 6620 6621 child_range children() { 6622 Stmt **B = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>()); 6623 return child_range(B, B + NumExprs); 6624 } 6625 6626 SourceLocation getBeginLoc() const { return BeginLoc; } 6627 SourceLocation getEndLoc() const { return EndLoc; } 6628 6629 static bool classof(const Stmt *T) { 6630 return T->getStmtClass() == RecoveryExprClass; 6631 } 6632 6633 private: 6634 RecoveryExpr(ASTContext &Ctx, QualType T, SourceLocation BeginLoc, 6635 SourceLocation EndLoc, ArrayRef<Expr *> SubExprs); 6636 RecoveryExpr(EmptyShell Empty, unsigned NumSubExprs) 6637 : Expr(RecoveryExprClass, Empty), NumExprs(NumSubExprs) {} 6638 6639 size_t numTrailingObjects(OverloadToken<Stmt *>) const { return NumExprs; } 6640 6641 SourceLocation BeginLoc, EndLoc; 6642 unsigned NumExprs; 6643 friend TrailingObjects; 6644 friend class ASTStmtReader; 6645 friend class ASTStmtWriter; 6646 }; 6647 6648 } // end namespace clang 6649 6650 #endif // LLVM_CLANG_AST_EXPR_H 6651