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