1 //===--- Expr.h - Classes for representing expressions ----------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines the Expr interface and subclasses. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #ifndef LLVM_CLANG_AST_EXPR_H 15 #define LLVM_CLANG_AST_EXPR_H 16 17 #include "clang/AST/APValue.h" 18 #include "clang/AST/ASTVector.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclAccessPair.h" 21 #include "clang/AST/OperationKinds.h" 22 #include "clang/AST/Stmt.h" 23 #include "clang/AST/TemplateBase.h" 24 #include "clang/AST/Type.h" 25 #include "clang/Basic/CharInfo.h" 26 #include "clang/Basic/TypeTraits.h" 27 #include "llvm/ADT/APFloat.h" 28 #include "llvm/ADT/APSInt.h" 29 #include "llvm/ADT/SmallVector.h" 30 #include "llvm/ADT/StringRef.h" 31 #include "llvm/Support/Compiler.h" 32 33 namespace clang { 34 class APValue; 35 class ASTContext; 36 class BlockDecl; 37 class CXXBaseSpecifier; 38 class CXXMemberCallExpr; 39 class CXXOperatorCallExpr; 40 class CastExpr; 41 class Decl; 42 class IdentifierInfo; 43 class MaterializeTemporaryExpr; 44 class NamedDecl; 45 class ObjCPropertyRefExpr; 46 class OpaqueValueExpr; 47 class ParmVarDecl; 48 class TargetInfo; 49 class ValueDecl; 50 51 /// \brief A simple array of base specifiers. 52 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath; 53 54 /// \brief An adjustment to be made to the temporary created when emitting a 55 /// reference binding, which accesses a particular subobject of that temporary. 56 struct SubobjectAdjustment { 57 enum { 58 DerivedToBaseAdjustment, 59 FieldAdjustment, 60 MemberPointerAdjustment 61 } Kind; 62 63 64 struct DTB { 65 const CastExpr *BasePath; 66 const CXXRecordDecl *DerivedClass; 67 }; 68 69 struct P { 70 const MemberPointerType *MPT; 71 Expr *RHS; 72 }; 73 74 union { 75 struct DTB DerivedToBase; 76 FieldDecl *Field; 77 struct P Ptr; 78 }; 79 80 SubobjectAdjustment(const CastExpr *BasePath, 81 const CXXRecordDecl *DerivedClass) 82 : Kind(DerivedToBaseAdjustment) { 83 DerivedToBase.BasePath = BasePath; 84 DerivedToBase.DerivedClass = DerivedClass; 85 } 86 87 SubobjectAdjustment(FieldDecl *Field) 88 : Kind(FieldAdjustment) { 89 this->Field = Field; 90 } 91 92 SubobjectAdjustment(const MemberPointerType *MPT, Expr *RHS) 93 : Kind(MemberPointerAdjustment) { 94 this->Ptr.MPT = MPT; 95 this->Ptr.RHS = RHS; 96 } 97 }; 98 99 /// Expr - This represents one expression. Note that Expr's are subclasses of 100 /// Stmt. This allows an expression to be transparently used any place a Stmt 101 /// is required. 102 /// 103 class Expr : public Stmt { 104 QualType TR; 105 106 protected: 107 Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK, 108 bool TD, bool VD, bool ID, bool ContainsUnexpandedParameterPack) 109 : Stmt(SC) 110 { 111 ExprBits.TypeDependent = TD; 112 ExprBits.ValueDependent = VD; 113 ExprBits.InstantiationDependent = ID; 114 ExprBits.ValueKind = VK; 115 ExprBits.ObjectKind = OK; 116 ExprBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack; 117 setType(T); 118 } 119 120 /// \brief Construct an empty expression. 121 explicit Expr(StmtClass SC, EmptyShell) : Stmt(SC) { } 122 123 public: 124 QualType getType() const { return TR; } 125 void setType(QualType t) { 126 // In C++, the type of an expression is always adjusted so that it 127 // will not have reference type an expression will never have 128 // reference type (C++ [expr]p6). Use 129 // QualType::getNonReferenceType() to retrieve the non-reference 130 // type. Additionally, inspect Expr::isLvalue to determine whether 131 // an expression that is adjusted in this manner should be 132 // considered an lvalue. 133 assert((t.isNull() || !t->isReferenceType()) && 134 "Expressions can't have reference type"); 135 136 TR = t; 137 } 138 139 /// isValueDependent - Determines whether this expression is 140 /// value-dependent (C++ [temp.dep.constexpr]). For example, the 141 /// array bound of "Chars" in the following example is 142 /// value-dependent. 143 /// @code 144 /// template<int Size, char (&Chars)[Size]> struct meta_string; 145 /// @endcode 146 bool isValueDependent() const { return ExprBits.ValueDependent; } 147 148 /// \brief Set whether this expression is value-dependent or not. 149 void setValueDependent(bool VD) { 150 ExprBits.ValueDependent = VD; 151 if (VD) 152 ExprBits.InstantiationDependent = true; 153 } 154 155 /// isTypeDependent - Determines whether this expression is 156 /// type-dependent (C++ [temp.dep.expr]), which means that its type 157 /// could change from one template instantiation to the next. For 158 /// example, the expressions "x" and "x + y" are type-dependent in 159 /// the following code, but "y" is not type-dependent: 160 /// @code 161 /// template<typename T> 162 /// void add(T x, int y) { 163 /// x + y; 164 /// } 165 /// @endcode 166 bool isTypeDependent() const { return ExprBits.TypeDependent; } 167 168 /// \brief Set whether this expression is type-dependent or not. 169 void setTypeDependent(bool TD) { 170 ExprBits.TypeDependent = TD; 171 if (TD) 172 ExprBits.InstantiationDependent = true; 173 } 174 175 /// \brief Whether this expression is instantiation-dependent, meaning that 176 /// it depends in some way on a template parameter, even if neither its type 177 /// nor (constant) value can change due to the template instantiation. 178 /// 179 /// In the following example, the expression \c sizeof(sizeof(T() + T())) is 180 /// instantiation-dependent (since it involves a template parameter \c T), but 181 /// is neither type- nor value-dependent, since the type of the inner 182 /// \c sizeof is known (\c std::size_t) and therefore the size of the outer 183 /// \c sizeof is known. 184 /// 185 /// \code 186 /// template<typename T> 187 /// void f(T x, T y) { 188 /// sizeof(sizeof(T() + T()); 189 /// } 190 /// \endcode 191 /// 192 bool isInstantiationDependent() const { 193 return ExprBits.InstantiationDependent; 194 } 195 196 /// \brief Set whether this expression is instantiation-dependent or not. 197 void setInstantiationDependent(bool ID) { 198 ExprBits.InstantiationDependent = ID; 199 } 200 201 /// \brief Whether this expression contains an unexpanded parameter 202 /// pack (for C++11 variadic templates). 203 /// 204 /// Given the following function template: 205 /// 206 /// \code 207 /// template<typename F, typename ...Types> 208 /// void forward(const F &f, Types &&...args) { 209 /// f(static_cast<Types&&>(args)...); 210 /// } 211 /// \endcode 212 /// 213 /// The expressions \c args and \c static_cast<Types&&>(args) both 214 /// contain parameter packs. 215 bool containsUnexpandedParameterPack() const { 216 return ExprBits.ContainsUnexpandedParameterPack; 217 } 218 219 /// \brief Set the bit that describes whether this expression 220 /// contains an unexpanded parameter pack. 221 void setContainsUnexpandedParameterPack(bool PP = true) { 222 ExprBits.ContainsUnexpandedParameterPack = PP; 223 } 224 225 /// getExprLoc - Return the preferred location for the arrow when diagnosing 226 /// a problem with a generic expression. 227 SourceLocation getExprLoc() const LLVM_READONLY; 228 229 /// isUnusedResultAWarning - Return true if this immediate expression should 230 /// be warned about if the result is unused. If so, fill in expr, location, 231 /// and ranges with expr to warn on and source locations/ranges appropriate 232 /// for a warning. 233 bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc, 234 SourceRange &R1, SourceRange &R2, 235 ASTContext &Ctx) const; 236 237 /// isLValue - True if this expression is an "l-value" according to 238 /// the rules of the current language. C and C++ give somewhat 239 /// different rules for this concept, but in general, the result of 240 /// an l-value expression identifies a specific object whereas the 241 /// result of an r-value expression is a value detached from any 242 /// specific storage. 243 /// 244 /// C++11 divides the concept of "r-value" into pure r-values 245 /// ("pr-values") and so-called expiring values ("x-values"), which 246 /// identify specific objects that can be safely cannibalized for 247 /// their resources. This is an unfortunate abuse of terminology on 248 /// the part of the C++ committee. In Clang, when we say "r-value", 249 /// we generally mean a pr-value. 250 bool isLValue() const { return getValueKind() == VK_LValue; } 251 bool isRValue() const { return getValueKind() == VK_RValue; } 252 bool isXValue() const { return getValueKind() == VK_XValue; } 253 bool isGLValue() const { return getValueKind() != VK_RValue; } 254 255 enum LValueClassification { 256 LV_Valid, 257 LV_NotObjectType, 258 LV_IncompleteVoidType, 259 LV_DuplicateVectorComponents, 260 LV_InvalidExpression, 261 LV_InvalidMessageExpression, 262 LV_MemberFunction, 263 LV_SubObjCPropertySetting, 264 LV_ClassTemporary, 265 LV_ArrayTemporary 266 }; 267 /// Reasons why an expression might not be an l-value. 268 LValueClassification ClassifyLValue(ASTContext &Ctx) const; 269 270 enum isModifiableLvalueResult { 271 MLV_Valid, 272 MLV_NotObjectType, 273 MLV_IncompleteVoidType, 274 MLV_DuplicateVectorComponents, 275 MLV_InvalidExpression, 276 MLV_LValueCast, // Specialized form of MLV_InvalidExpression. 277 MLV_IncompleteType, 278 MLV_ConstQualified, 279 MLV_ArrayType, 280 MLV_ReadonlyProperty, 281 MLV_NoSetterProperty, 282 MLV_MemberFunction, 283 MLV_SubObjCPropertySetting, 284 MLV_InvalidMessageExpression, 285 MLV_ClassTemporary, 286 MLV_ArrayTemporary 287 }; 288 /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type, 289 /// does not have an incomplete type, does not have a const-qualified type, 290 /// and if it is a structure or union, does not have any member (including, 291 /// recursively, any member or element of all contained aggregates or unions) 292 /// with a const-qualified type. 293 /// 294 /// \param Loc [in,out] - A source location which *may* be filled 295 /// in with the location of the expression making this a 296 /// non-modifiable lvalue, if specified. 297 isModifiableLvalueResult isModifiableLvalue(ASTContext &Ctx, 298 SourceLocation *Loc = 0) const; 299 300 /// \brief The return type of classify(). Represents the C++11 expression 301 /// taxonomy. 302 class Classification { 303 public: 304 /// \brief The various classification results. Most of these mean prvalue. 305 enum Kinds { 306 CL_LValue, 307 CL_XValue, 308 CL_Function, // Functions cannot be lvalues in C. 309 CL_Void, // Void cannot be an lvalue in C. 310 CL_AddressableVoid, // Void expression whose address can be taken in C. 311 CL_DuplicateVectorComponents, // A vector shuffle with dupes. 312 CL_MemberFunction, // An expression referring to a member function 313 CL_SubObjCPropertySetting, 314 CL_ClassTemporary, // A temporary of class type, or subobject thereof. 315 CL_ArrayTemporary, // A temporary of array type. 316 CL_ObjCMessageRValue, // ObjC message is an rvalue 317 CL_PRValue // A prvalue for any other reason, of any other type 318 }; 319 /// \brief The results of modification testing. 320 enum ModifiableType { 321 CM_Untested, // testModifiable was false. 322 CM_Modifiable, 323 CM_RValue, // Not modifiable because it's an rvalue 324 CM_Function, // Not modifiable because it's a function; C++ only 325 CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext 326 CM_NoSetterProperty,// Implicit assignment to ObjC property without setter 327 CM_ConstQualified, 328 CM_ArrayType, 329 CM_IncompleteType 330 }; 331 332 private: 333 friend class Expr; 334 335 unsigned short Kind; 336 unsigned short Modifiable; 337 338 explicit Classification(Kinds k, ModifiableType m) 339 : Kind(k), Modifiable(m) 340 {} 341 342 public: 343 Classification() {} 344 345 Kinds getKind() const { return static_cast<Kinds>(Kind); } 346 ModifiableType getModifiable() const { 347 assert(Modifiable != CM_Untested && "Did not test for modifiability."); 348 return static_cast<ModifiableType>(Modifiable); 349 } 350 bool isLValue() const { return Kind == CL_LValue; } 351 bool isXValue() const { return Kind == CL_XValue; } 352 bool isGLValue() const { return Kind <= CL_XValue; } 353 bool isPRValue() const { return Kind >= CL_Function; } 354 bool isRValue() const { return Kind >= CL_XValue; } 355 bool isModifiable() const { return getModifiable() == CM_Modifiable; } 356 357 /// \brief Create a simple, modifiably lvalue 358 static Classification makeSimpleLValue() { 359 return Classification(CL_LValue, CM_Modifiable); 360 } 361 362 }; 363 /// \brief Classify - Classify this expression according to the C++11 364 /// expression taxonomy. 365 /// 366 /// C++11 defines ([basic.lval]) a new taxonomy of expressions to replace the 367 /// old lvalue vs rvalue. This function determines the type of expression this 368 /// is. There are three expression types: 369 /// - lvalues are classical lvalues as in C++03. 370 /// - prvalues are equivalent to rvalues in C++03. 371 /// - xvalues are expressions yielding unnamed rvalue references, e.g. a 372 /// function returning an rvalue reference. 373 /// lvalues and xvalues are collectively referred to as glvalues, while 374 /// prvalues and xvalues together form rvalues. 375 Classification Classify(ASTContext &Ctx) const { 376 return ClassifyImpl(Ctx, 0); 377 } 378 379 /// \brief ClassifyModifiable - Classify this expression according to the 380 /// C++11 expression taxonomy, and see if it is valid on the left side 381 /// of an assignment. 382 /// 383 /// This function extends classify in that it also tests whether the 384 /// expression is modifiable (C99 6.3.2.1p1). 385 /// \param Loc A source location that might be filled with a relevant location 386 /// if the expression is not modifiable. 387 Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{ 388 return ClassifyImpl(Ctx, &Loc); 389 } 390 391 /// getValueKindForType - Given a formal return or parameter type, 392 /// give its value kind. 393 static ExprValueKind getValueKindForType(QualType T) { 394 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 395 return (isa<LValueReferenceType>(RT) 396 ? VK_LValue 397 : (RT->getPointeeType()->isFunctionType() 398 ? VK_LValue : VK_XValue)); 399 return VK_RValue; 400 } 401 402 /// getValueKind - The value kind that this expression produces. 403 ExprValueKind getValueKind() const { 404 return static_cast<ExprValueKind>(ExprBits.ValueKind); 405 } 406 407 /// getObjectKind - The object kind that this expression produces. 408 /// Object kinds are meaningful only for expressions that yield an 409 /// l-value or x-value. 410 ExprObjectKind getObjectKind() const { 411 return static_cast<ExprObjectKind>(ExprBits.ObjectKind); 412 } 413 414 bool isOrdinaryOrBitFieldObject() const { 415 ExprObjectKind OK = getObjectKind(); 416 return (OK == OK_Ordinary || OK == OK_BitField); 417 } 418 419 /// setValueKind - Set the value kind produced by this expression. 420 void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; } 421 422 /// setObjectKind - Set the object kind produced by this expression. 423 void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; } 424 425 private: 426 Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const; 427 428 public: 429 430 /// \brief If this expression refers to a bit-field, retrieve the 431 /// declaration of that bit-field. 432 FieldDecl *getBitField(); 433 434 const FieldDecl *getBitField() const { 435 return const_cast<Expr*>(this)->getBitField(); 436 } 437 438 /// \brief If this expression is an l-value for an Objective C 439 /// property, find the underlying property reference expression. 440 const ObjCPropertyRefExpr *getObjCProperty() const; 441 442 /// \brief Check if this expression is the ObjC 'self' implicit parameter. 443 bool isObjCSelfExpr() const; 444 445 /// \brief Returns whether this expression refers to a vector element. 446 bool refersToVectorElement() const; 447 448 /// \brief Returns whether this expression has a placeholder type. 449 bool hasPlaceholderType() const { 450 return getType()->isPlaceholderType(); 451 } 452 453 /// \brief Returns whether this expression has a specific placeholder type. 454 bool hasPlaceholderType(BuiltinType::Kind K) const { 455 assert(BuiltinType::isPlaceholderTypeKind(K)); 456 if (const BuiltinType *BT = dyn_cast<BuiltinType>(getType())) 457 return BT->getKind() == K; 458 return false; 459 } 460 461 /// isKnownToHaveBooleanValue - Return true if this is an integer expression 462 /// that is known to return 0 or 1. This happens for _Bool/bool expressions 463 /// but also int expressions which are produced by things like comparisons in 464 /// C. 465 bool isKnownToHaveBooleanValue() const; 466 467 /// isIntegerConstantExpr - Return true if this expression is a valid integer 468 /// constant expression, and, if so, return its value in Result. If not a 469 /// valid i-c-e, return false and fill in Loc (if specified) with the location 470 /// of the invalid expression. 471 /// 472 /// Note: This does not perform the implicit conversions required by C++11 473 /// [expr.const]p5. 474 bool isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx, 475 SourceLocation *Loc = 0, 476 bool isEvaluated = true) const; 477 bool isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc = 0) const; 478 479 /// isCXX98IntegralConstantExpr - Return true if this expression is an 480 /// integral constant expression in C++98. Can only be used in C++. 481 bool isCXX98IntegralConstantExpr(ASTContext &Ctx) const; 482 483 /// isCXX11ConstantExpr - Return true if this expression is a constant 484 /// expression in C++11. Can only be used in C++. 485 /// 486 /// Note: This does not perform the implicit conversions required by C++11 487 /// [expr.const]p5. 488 bool isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result = 0, 489 SourceLocation *Loc = 0) const; 490 491 /// isPotentialConstantExpr - Return true if this function's definition 492 /// might be usable in a constant expression in C++11, if it were marked 493 /// constexpr. Return false if the function can never produce a constant 494 /// expression, along with diagnostics describing why not. 495 static bool isPotentialConstantExpr(const FunctionDecl *FD, 496 SmallVectorImpl< 497 PartialDiagnosticAt> &Diags); 498 499 /// isConstantInitializer - Returns true if this expression can be emitted to 500 /// IR as a constant, and thus can be used as a constant initializer in C. 501 bool isConstantInitializer(ASTContext &Ctx, bool ForRef) const; 502 503 /// EvalStatus is a struct with detailed info about an evaluation in progress. 504 struct EvalStatus { 505 /// HasSideEffects - Whether the evaluated expression has side effects. 506 /// For example, (f() && 0) can be folded, but it still has side effects. 507 bool HasSideEffects; 508 509 /// Diag - If this is non-null, it will be filled in with a stack of notes 510 /// indicating why evaluation failed (or why it failed to produce a constant 511 /// expression). 512 /// If the expression is unfoldable, the notes will indicate why it's not 513 /// foldable. If the expression is foldable, but not a constant expression, 514 /// the notes will describes why it isn't a constant expression. If the 515 /// expression *is* a constant expression, no notes will be produced. 516 SmallVectorImpl<PartialDiagnosticAt> *Diag; 517 518 EvalStatus() : HasSideEffects(false), Diag(0) {} 519 520 // hasSideEffects - Return true if the evaluated expression has 521 // side effects. 522 bool hasSideEffects() const { 523 return HasSideEffects; 524 } 525 }; 526 527 /// EvalResult is a struct with detailed info about an evaluated expression. 528 struct EvalResult : EvalStatus { 529 /// Val - This is the value the expression can be folded to. 530 APValue Val; 531 532 // isGlobalLValue - Return true if the evaluated lvalue expression 533 // is global. 534 bool isGlobalLValue() const; 535 }; 536 537 /// EvaluateAsRValue - Return true if this is a constant which we can fold to 538 /// an rvalue using any crazy technique (that has nothing to do with language 539 /// standards) that we want to, even if the expression has side-effects. If 540 /// this function returns true, it returns the folded constant in Result. If 541 /// the expression is a glvalue, an lvalue-to-rvalue conversion will be 542 /// applied. 543 bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const; 544 545 /// EvaluateAsBooleanCondition - Return true if this is a constant 546 /// which we we can fold and convert to a boolean condition using 547 /// any crazy technique that we want to, even if the expression has 548 /// side-effects. 549 bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx) const; 550 551 enum SideEffectsKind { SE_NoSideEffects, SE_AllowSideEffects }; 552 553 /// EvaluateAsInt - Return true if this is a constant which we can fold and 554 /// convert to an integer, using any crazy technique that we want to. 555 bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx, 556 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const; 557 558 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 559 /// constant folded without side-effects, but discard the result. 560 bool isEvaluatable(const ASTContext &Ctx) const; 561 562 /// HasSideEffects - This routine returns true for all those expressions 563 /// which have any effect other than producing a value. Example is a function 564 /// call, volatile variable read, or throwing an exception. 565 bool HasSideEffects(const ASTContext &Ctx) const; 566 567 /// \brief Determine whether this expression involves a call to any function 568 /// that is not trivial. 569 bool hasNonTrivialCall(ASTContext &Ctx); 570 571 /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded 572 /// integer. This must be called on an expression that constant folds to an 573 /// integer. 574 llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, 575 SmallVectorImpl<PartialDiagnosticAt> *Diag=0) const; 576 577 void EvaluateForOverflow(const ASTContext &Ctx, 578 SmallVectorImpl<PartialDiagnosticAt> *Diag) const; 579 580 /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an 581 /// lvalue with link time known address, with no side-effects. 582 bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const; 583 584 /// EvaluateAsInitializer - Evaluate an expression as if it were the 585 /// initializer of the given declaration. Returns true if the initializer 586 /// can be folded to a constant, and produces any relevant notes. In C++11, 587 /// notes will be produced if the expression is not a constant expression. 588 bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx, 589 const VarDecl *VD, 590 SmallVectorImpl<PartialDiagnosticAt> &Notes) const; 591 592 /// \brief Enumeration used to describe the kind of Null pointer constant 593 /// returned from \c isNullPointerConstant(). 594 enum NullPointerConstantKind { 595 /// \brief Expression is not a Null pointer constant. 596 NPCK_NotNull = 0, 597 598 /// \brief Expression is a Null pointer constant built from a zero integer 599 /// expression that is not a simple, possibly parenthesized, zero literal. 600 /// C++ Core Issue 903 will classify these expressions as "not pointers" 601 /// once it is adopted. 602 /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 603 NPCK_ZeroExpression, 604 605 /// \brief Expression is a Null pointer constant built from a literal zero. 606 NPCK_ZeroLiteral, 607 608 /// \brief Expression is a C++11 nullptr. 609 NPCK_CXX11_nullptr, 610 611 /// \brief Expression is a GNU-style __null constant. 612 NPCK_GNUNull 613 }; 614 615 /// \brief Enumeration used to describe how \c isNullPointerConstant() 616 /// should cope with value-dependent expressions. 617 enum NullPointerConstantValueDependence { 618 /// \brief Specifies that the expression should never be value-dependent. 619 NPC_NeverValueDependent = 0, 620 621 /// \brief Specifies that a value-dependent expression of integral or 622 /// dependent type should be considered a null pointer constant. 623 NPC_ValueDependentIsNull, 624 625 /// \brief Specifies that a value-dependent expression should be considered 626 /// to never be a null pointer constant. 627 NPC_ValueDependentIsNotNull 628 }; 629 630 /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to 631 /// a Null pointer constant. The return value can further distinguish the 632 /// kind of NULL pointer constant that was detected. 633 NullPointerConstantKind isNullPointerConstant( 634 ASTContext &Ctx, 635 NullPointerConstantValueDependence NPC) const; 636 637 /// isOBJCGCCandidate - Return true if this expression may be used in a read/ 638 /// write barrier. 639 bool isOBJCGCCandidate(ASTContext &Ctx) const; 640 641 /// \brief Returns true if this expression is a bound member function. 642 bool isBoundMemberFunction(ASTContext &Ctx) const; 643 644 /// \brief Given an expression of bound-member type, find the type 645 /// of the member. Returns null if this is an *overloaded* bound 646 /// member expression. 647 static QualType findBoundMemberType(const Expr *expr); 648 649 /// IgnoreImpCasts - Skip past any implicit casts which might 650 /// surround this expression. Only skips ImplicitCastExprs. 651 Expr *IgnoreImpCasts() LLVM_READONLY; 652 653 /// IgnoreImplicit - Skip past any implicit AST nodes which might 654 /// surround this expression. 655 Expr *IgnoreImplicit() LLVM_READONLY { 656 return cast<Expr>(Stmt::IgnoreImplicit()); 657 } 658 659 const Expr *IgnoreImplicit() const LLVM_READONLY { 660 return const_cast<Expr*>(this)->IgnoreImplicit(); 661 } 662 663 /// IgnoreParens - Ignore parentheses. If this Expr is a ParenExpr, return 664 /// its subexpression. If that subexpression is also a ParenExpr, 665 /// then this method recursively returns its subexpression, and so forth. 666 /// Otherwise, the method returns the current Expr. 667 Expr *IgnoreParens() LLVM_READONLY; 668 669 /// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr 670 /// or CastExprs, returning their operand. 671 Expr *IgnoreParenCasts() LLVM_READONLY; 672 673 /// IgnoreParenImpCasts - Ignore parentheses and implicit casts. Strip off 674 /// any ParenExpr or ImplicitCastExprs, returning their operand. 675 Expr *IgnoreParenImpCasts() LLVM_READONLY; 676 677 /// IgnoreConversionOperator - Ignore conversion operator. If this Expr is a 678 /// call to a conversion operator, return the argument. 679 Expr *IgnoreConversionOperator() LLVM_READONLY; 680 681 const Expr *IgnoreConversionOperator() const LLVM_READONLY { 682 return const_cast<Expr*>(this)->IgnoreConversionOperator(); 683 } 684 685 const Expr *IgnoreParenImpCasts() const LLVM_READONLY { 686 return const_cast<Expr*>(this)->IgnoreParenImpCasts(); 687 } 688 689 /// Ignore parentheses and lvalue casts. Strip off any ParenExpr and 690 /// CastExprs that represent lvalue casts, returning their operand. 691 Expr *IgnoreParenLValueCasts() LLVM_READONLY; 692 693 const Expr *IgnoreParenLValueCasts() const LLVM_READONLY { 694 return const_cast<Expr*>(this)->IgnoreParenLValueCasts(); 695 } 696 697 /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the 698 /// value (including ptr->int casts of the same size). Strip off any 699 /// ParenExpr or CastExprs, returning their operand. 700 Expr *IgnoreParenNoopCasts(ASTContext &Ctx) LLVM_READONLY; 701 702 /// Ignore parentheses and derived-to-base casts. 703 Expr *ignoreParenBaseCasts() LLVM_READONLY; 704 705 const Expr *ignoreParenBaseCasts() const LLVM_READONLY { 706 return const_cast<Expr*>(this)->ignoreParenBaseCasts(); 707 } 708 709 /// \brief Determine whether this expression is a default function argument. 710 /// 711 /// Default arguments are implicitly generated in the abstract syntax tree 712 /// by semantic analysis for function calls, object constructions, etc. in 713 /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes; 714 /// this routine also looks through any implicit casts to determine whether 715 /// the expression is a default argument. 716 bool isDefaultArgument() const; 717 718 /// \brief Determine whether the result of this expression is a 719 /// temporary object of the given class type. 720 bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const; 721 722 /// \brief Whether this expression is an implicit reference to 'this' in C++. 723 bool isImplicitCXXThis() const; 724 725 const Expr *IgnoreImpCasts() const LLVM_READONLY { 726 return const_cast<Expr*>(this)->IgnoreImpCasts(); 727 } 728 const Expr *IgnoreParens() const LLVM_READONLY { 729 return const_cast<Expr*>(this)->IgnoreParens(); 730 } 731 const Expr *IgnoreParenCasts() const LLVM_READONLY { 732 return const_cast<Expr*>(this)->IgnoreParenCasts(); 733 } 734 const Expr *IgnoreParenNoopCasts(ASTContext &Ctx) const LLVM_READONLY { 735 return const_cast<Expr*>(this)->IgnoreParenNoopCasts(Ctx); 736 } 737 738 static bool hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs); 739 740 /// \brief For an expression of class type or pointer to class type, 741 /// return the most derived class decl the expression is known to refer to. 742 /// 743 /// If this expression is a cast, this method looks through it to find the 744 /// most derived decl that can be inferred from the expression. 745 /// This is valid because derived-to-base conversions have undefined 746 /// behavior if the object isn't dynamically of the derived type. 747 const CXXRecordDecl *getBestDynamicClassType() const; 748 749 /// Walk outwards from an expression we want to bind a reference to and 750 /// find the expression whose lifetime needs to be extended. Record 751 /// the adjustments needed along the path. 752 const Expr * 753 skipRValueSubobjectAdjustments( 754 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const; 755 756 /// Skip irrelevant expressions to find what should be materialize for 757 /// binding with a reference. 758 const Expr * 759 findMaterializedTemporary(const MaterializeTemporaryExpr *&MTE) const; 760 761 static bool classof(const Stmt *T) { 762 return T->getStmtClass() >= firstExprConstant && 763 T->getStmtClass() <= lastExprConstant; 764 } 765 }; 766 767 768 //===----------------------------------------------------------------------===// 769 // Primary Expressions. 770 //===----------------------------------------------------------------------===// 771 772 /// OpaqueValueExpr - An expression referring to an opaque object of a 773 /// fixed type and value class. These don't correspond to concrete 774 /// syntax; instead they're used to express operations (usually copy 775 /// operations) on values whose source is generally obvious from 776 /// context. 777 class OpaqueValueExpr : public Expr { 778 friend class ASTStmtReader; 779 Expr *SourceExpr; 780 SourceLocation Loc; 781 782 public: 783 OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK, 784 ExprObjectKind OK = OK_Ordinary, 785 Expr *SourceExpr = 0) 786 : Expr(OpaqueValueExprClass, T, VK, OK, 787 T->isDependentType(), 788 T->isDependentType() || 789 (SourceExpr && SourceExpr->isValueDependent()), 790 T->isInstantiationDependentType(), 791 false), 792 SourceExpr(SourceExpr), Loc(Loc) { 793 } 794 795 /// Given an expression which invokes a copy constructor --- i.e. a 796 /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups --- 797 /// find the OpaqueValueExpr that's the source of the construction. 798 static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr); 799 800 explicit OpaqueValueExpr(EmptyShell Empty) 801 : Expr(OpaqueValueExprClass, Empty) { } 802 803 /// \brief Retrieve the location of this expression. 804 SourceLocation getLocation() const { return Loc; } 805 806 SourceLocation getLocStart() const LLVM_READONLY { 807 return SourceExpr ? SourceExpr->getLocStart() : Loc; 808 } 809 SourceLocation getLocEnd() const LLVM_READONLY { 810 return SourceExpr ? SourceExpr->getLocEnd() : Loc; 811 } 812 SourceLocation getExprLoc() const LLVM_READONLY { 813 if (SourceExpr) return SourceExpr->getExprLoc(); 814 return Loc; 815 } 816 817 child_range children() { return child_range(); } 818 819 /// The source expression of an opaque value expression is the 820 /// expression which originally generated the value. This is 821 /// provided as a convenience for analyses that don't wish to 822 /// precisely model the execution behavior of the program. 823 /// 824 /// The source expression is typically set when building the 825 /// expression which binds the opaque value expression in the first 826 /// place. 827 Expr *getSourceExpr() const { return SourceExpr; } 828 829 static bool classof(const Stmt *T) { 830 return T->getStmtClass() == OpaqueValueExprClass; 831 } 832 }; 833 834 /// \brief A reference to a declared variable, function, enum, etc. 835 /// [C99 6.5.1p2] 836 /// 837 /// This encodes all the information about how a declaration is referenced 838 /// within an expression. 839 /// 840 /// There are several optional constructs attached to DeclRefExprs only when 841 /// they apply in order to conserve memory. These are laid out past the end of 842 /// the object, and flags in the DeclRefExprBitfield track whether they exist: 843 /// 844 /// DeclRefExprBits.HasQualifier: 845 /// Specifies when this declaration reference expression has a C++ 846 /// nested-name-specifier. 847 /// DeclRefExprBits.HasFoundDecl: 848 /// Specifies when this declaration reference expression has a record of 849 /// a NamedDecl (different from the referenced ValueDecl) which was found 850 /// during name lookup and/or overload resolution. 851 /// DeclRefExprBits.HasTemplateKWAndArgsInfo: 852 /// Specifies when this declaration reference expression has an explicit 853 /// C++ template keyword and/or template argument list. 854 /// DeclRefExprBits.RefersToEnclosingLocal 855 /// Specifies when this declaration reference expression (validly) 856 /// refers to a local variable from a different function. 857 class DeclRefExpr : public Expr { 858 /// \brief The declaration that we are referencing. 859 ValueDecl *D; 860 861 /// \brief The location of the declaration name itself. 862 SourceLocation Loc; 863 864 /// \brief Provides source/type location info for the declaration name 865 /// embedded in D. 866 DeclarationNameLoc DNLoc; 867 868 /// \brief Helper to retrieve the optional NestedNameSpecifierLoc. 869 NestedNameSpecifierLoc &getInternalQualifierLoc() { 870 assert(hasQualifier()); 871 return *reinterpret_cast<NestedNameSpecifierLoc *>(this + 1); 872 } 873 874 /// \brief Helper to retrieve the optional NestedNameSpecifierLoc. 875 const NestedNameSpecifierLoc &getInternalQualifierLoc() const { 876 return const_cast<DeclRefExpr *>(this)->getInternalQualifierLoc(); 877 } 878 879 /// \brief Test whether there is a distinct FoundDecl attached to the end of 880 /// this DRE. 881 bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; } 882 883 /// \brief Helper to retrieve the optional NamedDecl through which this 884 /// reference occured. 885 NamedDecl *&getInternalFoundDecl() { 886 assert(hasFoundDecl()); 887 if (hasQualifier()) 888 return *reinterpret_cast<NamedDecl **>(&getInternalQualifierLoc() + 1); 889 return *reinterpret_cast<NamedDecl **>(this + 1); 890 } 891 892 /// \brief Helper to retrieve the optional NamedDecl through which this 893 /// reference occured. 894 NamedDecl *getInternalFoundDecl() const { 895 return const_cast<DeclRefExpr *>(this)->getInternalFoundDecl(); 896 } 897 898 DeclRefExpr(ASTContext &Ctx, 899 NestedNameSpecifierLoc QualifierLoc, 900 SourceLocation TemplateKWLoc, 901 ValueDecl *D, bool refersToEnclosingLocal, 902 const DeclarationNameInfo &NameInfo, 903 NamedDecl *FoundD, 904 const TemplateArgumentListInfo *TemplateArgs, 905 QualType T, ExprValueKind VK); 906 907 /// \brief Construct an empty declaration reference expression. 908 explicit DeclRefExpr(EmptyShell Empty) 909 : Expr(DeclRefExprClass, Empty) { } 910 911 /// \brief Computes the type- and value-dependence flags for this 912 /// declaration reference expression. 913 void computeDependence(ASTContext &C); 914 915 public: 916 DeclRefExpr(ValueDecl *D, bool refersToEnclosingLocal, QualType T, 917 ExprValueKind VK, SourceLocation L, 918 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) 919 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false), 920 D(D), Loc(L), DNLoc(LocInfo) { 921 DeclRefExprBits.HasQualifier = 0; 922 DeclRefExprBits.HasTemplateKWAndArgsInfo = 0; 923 DeclRefExprBits.HasFoundDecl = 0; 924 DeclRefExprBits.HadMultipleCandidates = 0; 925 DeclRefExprBits.RefersToEnclosingLocal = refersToEnclosingLocal; 926 computeDependence(D->getASTContext()); 927 } 928 929 static DeclRefExpr *Create(ASTContext &Context, 930 NestedNameSpecifierLoc QualifierLoc, 931 SourceLocation TemplateKWLoc, 932 ValueDecl *D, 933 bool isEnclosingLocal, 934 SourceLocation NameLoc, 935 QualType T, ExprValueKind VK, 936 NamedDecl *FoundD = 0, 937 const TemplateArgumentListInfo *TemplateArgs = 0); 938 939 static DeclRefExpr *Create(ASTContext &Context, 940 NestedNameSpecifierLoc QualifierLoc, 941 SourceLocation TemplateKWLoc, 942 ValueDecl *D, 943 bool isEnclosingLocal, 944 const DeclarationNameInfo &NameInfo, 945 QualType T, ExprValueKind VK, 946 NamedDecl *FoundD = 0, 947 const TemplateArgumentListInfo *TemplateArgs = 0); 948 949 /// \brief Construct an empty declaration reference expression. 950 static DeclRefExpr *CreateEmpty(ASTContext &Context, 951 bool HasQualifier, 952 bool HasFoundDecl, 953 bool HasTemplateKWAndArgsInfo, 954 unsigned NumTemplateArgs); 955 956 ValueDecl *getDecl() { return D; } 957 const ValueDecl *getDecl() const { return D; } 958 void setDecl(ValueDecl *NewD) { D = NewD; } 959 960 DeclarationNameInfo getNameInfo() const { 961 return DeclarationNameInfo(getDecl()->getDeclName(), Loc, DNLoc); 962 } 963 964 SourceLocation getLocation() const { return Loc; } 965 void setLocation(SourceLocation L) { Loc = L; } 966 SourceLocation getLocStart() const LLVM_READONLY; 967 SourceLocation getLocEnd() const LLVM_READONLY; 968 969 /// \brief Determine whether this declaration reference was preceded by a 970 /// C++ nested-name-specifier, e.g., \c N::foo. 971 bool hasQualifier() const { return DeclRefExprBits.HasQualifier; } 972 973 /// \brief If the name was qualified, retrieves the nested-name-specifier 974 /// that precedes the name. Otherwise, returns NULL. 975 NestedNameSpecifier *getQualifier() const { 976 if (!hasQualifier()) 977 return 0; 978 979 return getInternalQualifierLoc().getNestedNameSpecifier(); 980 } 981 982 /// \brief If the name was qualified, retrieves the nested-name-specifier 983 /// that precedes the name, with source-location information. 984 NestedNameSpecifierLoc getQualifierLoc() const { 985 if (!hasQualifier()) 986 return NestedNameSpecifierLoc(); 987 988 return getInternalQualifierLoc(); 989 } 990 991 /// \brief Get the NamedDecl through which this reference occured. 992 /// 993 /// This Decl may be different from the ValueDecl actually referred to in the 994 /// presence of using declarations, etc. It always returns non-NULL, and may 995 /// simple return the ValueDecl when appropriate. 996 NamedDecl *getFoundDecl() { 997 return hasFoundDecl() ? getInternalFoundDecl() : D; 998 } 999 1000 /// \brief Get the NamedDecl through which this reference occurred. 1001 /// See non-const variant. 1002 const NamedDecl *getFoundDecl() const { 1003 return hasFoundDecl() ? getInternalFoundDecl() : D; 1004 } 1005 1006 bool hasTemplateKWAndArgsInfo() const { 1007 return DeclRefExprBits.HasTemplateKWAndArgsInfo; 1008 } 1009 1010 /// \brief Return the optional template keyword and arguments info. 1011 ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() { 1012 if (!hasTemplateKWAndArgsInfo()) 1013 return 0; 1014 1015 if (hasFoundDecl()) 1016 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>( 1017 &getInternalFoundDecl() + 1); 1018 1019 if (hasQualifier()) 1020 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>( 1021 &getInternalQualifierLoc() + 1); 1022 1023 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(this + 1); 1024 } 1025 1026 /// \brief Return the optional template keyword and arguments info. 1027 const ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() const { 1028 return const_cast<DeclRefExpr*>(this)->getTemplateKWAndArgsInfo(); 1029 } 1030 1031 /// \brief Retrieve the location of the template keyword preceding 1032 /// this name, if any. 1033 SourceLocation getTemplateKeywordLoc() const { 1034 if (!hasTemplateKWAndArgsInfo()) return SourceLocation(); 1035 return getTemplateKWAndArgsInfo()->getTemplateKeywordLoc(); 1036 } 1037 1038 /// \brief Retrieve the location of the left angle bracket starting the 1039 /// explicit template argument list following the name, if any. 1040 SourceLocation getLAngleLoc() const { 1041 if (!hasTemplateKWAndArgsInfo()) return SourceLocation(); 1042 return getTemplateKWAndArgsInfo()->LAngleLoc; 1043 } 1044 1045 /// \brief Retrieve the location of the right angle bracket ending the 1046 /// explicit template argument list following the name, if any. 1047 SourceLocation getRAngleLoc() const { 1048 if (!hasTemplateKWAndArgsInfo()) return SourceLocation(); 1049 return getTemplateKWAndArgsInfo()->RAngleLoc; 1050 } 1051 1052 /// \brief Determines whether the name in this declaration reference 1053 /// was preceded by the template keyword. 1054 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); } 1055 1056 /// \brief Determines whether this declaration reference was followed by an 1057 /// explicit template argument list. 1058 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); } 1059 1060 /// \brief Retrieve the explicit template argument list that followed the 1061 /// member template name. 1062 ASTTemplateArgumentListInfo &getExplicitTemplateArgs() { 1063 assert(hasExplicitTemplateArgs()); 1064 return *getTemplateKWAndArgsInfo(); 1065 } 1066 1067 /// \brief Retrieve the explicit template argument list that followed the 1068 /// member template name. 1069 const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const { 1070 return const_cast<DeclRefExpr *>(this)->getExplicitTemplateArgs(); 1071 } 1072 1073 /// \brief Retrieves the optional explicit template arguments. 1074 /// This points to the same data as getExplicitTemplateArgs(), but 1075 /// returns null if there are no explicit template arguments. 1076 const ASTTemplateArgumentListInfo *getOptionalExplicitTemplateArgs() const { 1077 if (!hasExplicitTemplateArgs()) return 0; 1078 return &getExplicitTemplateArgs(); 1079 } 1080 1081 /// \brief Copies the template arguments (if present) into the given 1082 /// structure. 1083 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const { 1084 if (hasExplicitTemplateArgs()) 1085 getExplicitTemplateArgs().copyInto(List); 1086 } 1087 1088 /// \brief Retrieve the template arguments provided as part of this 1089 /// template-id. 1090 const TemplateArgumentLoc *getTemplateArgs() const { 1091 if (!hasExplicitTemplateArgs()) 1092 return 0; 1093 1094 return getExplicitTemplateArgs().getTemplateArgs(); 1095 } 1096 1097 /// \brief Retrieve the number of template arguments provided as part of this 1098 /// template-id. 1099 unsigned getNumTemplateArgs() const { 1100 if (!hasExplicitTemplateArgs()) 1101 return 0; 1102 1103 return getExplicitTemplateArgs().NumTemplateArgs; 1104 } 1105 1106 /// \brief Returns true if this expression refers to a function that 1107 /// was resolved from an overloaded set having size greater than 1. 1108 bool hadMultipleCandidates() const { 1109 return DeclRefExprBits.HadMultipleCandidates; 1110 } 1111 /// \brief Sets the flag telling whether this expression refers to 1112 /// a function that was resolved from an overloaded set having size 1113 /// greater than 1. 1114 void setHadMultipleCandidates(bool V = true) { 1115 DeclRefExprBits.HadMultipleCandidates = V; 1116 } 1117 1118 /// Does this DeclRefExpr refer to a local declaration from an 1119 /// enclosing function scope? 1120 bool refersToEnclosingLocal() const { 1121 return DeclRefExprBits.RefersToEnclosingLocal; 1122 } 1123 1124 static bool classof(const Stmt *T) { 1125 return T->getStmtClass() == DeclRefExprClass; 1126 } 1127 1128 // Iterators 1129 child_range children() { return child_range(); } 1130 1131 friend class ASTStmtReader; 1132 friend class ASTStmtWriter; 1133 }; 1134 1135 /// PredefinedExpr - [C99 6.4.2.2] - A predefined identifier such as __func__. 1136 class PredefinedExpr : public Expr { 1137 public: 1138 enum IdentType { 1139 Func, 1140 Function, 1141 LFunction, // Same as Function, but as wide string. 1142 PrettyFunction, 1143 /// PrettyFunctionNoVirtual - The same as PrettyFunction, except that the 1144 /// 'virtual' keyword is omitted for virtual member functions. 1145 PrettyFunctionNoVirtual 1146 }; 1147 1148 private: 1149 SourceLocation Loc; 1150 IdentType Type; 1151 public: 1152 PredefinedExpr(SourceLocation l, QualType type, IdentType IT) 1153 : Expr(PredefinedExprClass, type, VK_LValue, OK_Ordinary, 1154 type->isDependentType(), type->isDependentType(), 1155 type->isInstantiationDependentType(), 1156 /*ContainsUnexpandedParameterPack=*/false), 1157 Loc(l), Type(IT) {} 1158 1159 /// \brief Construct an empty predefined expression. 1160 explicit PredefinedExpr(EmptyShell Empty) 1161 : Expr(PredefinedExprClass, Empty) { } 1162 1163 IdentType getIdentType() const { return Type; } 1164 void setIdentType(IdentType IT) { Type = IT; } 1165 1166 SourceLocation getLocation() const { return Loc; } 1167 void setLocation(SourceLocation L) { Loc = L; } 1168 1169 static std::string ComputeName(IdentType IT, const Decl *CurrentDecl); 1170 1171 SourceLocation getLocStart() const LLVM_READONLY { return Loc; } 1172 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; } 1173 1174 static bool classof(const Stmt *T) { 1175 return T->getStmtClass() == PredefinedExprClass; 1176 } 1177 1178 // Iterators 1179 child_range children() { return child_range(); } 1180 }; 1181 1182 /// \brief Used by IntegerLiteral/FloatingLiteral to store the numeric without 1183 /// leaking memory. 1184 /// 1185 /// For large floats/integers, APFloat/APInt will allocate memory from the heap 1186 /// to represent these numbers. Unfortunately, when we use a BumpPtrAllocator 1187 /// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with 1188 /// the APFloat/APInt values will never get freed. APNumericStorage uses 1189 /// ASTContext's allocator for memory allocation. 1190 class APNumericStorage { 1191 union { 1192 uint64_t VAL; ///< Used to store the <= 64 bits integer value. 1193 uint64_t *pVal; ///< Used to store the >64 bits integer value. 1194 }; 1195 unsigned BitWidth; 1196 1197 bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; } 1198 1199 APNumericStorage(const APNumericStorage &) LLVM_DELETED_FUNCTION; 1200 void operator=(const APNumericStorage &) LLVM_DELETED_FUNCTION; 1201 1202 protected: 1203 APNumericStorage() : VAL(0), BitWidth(0) { } 1204 1205 llvm::APInt getIntValue() const { 1206 unsigned NumWords = llvm::APInt::getNumWords(BitWidth); 1207 if (NumWords > 1) 1208 return llvm::APInt(BitWidth, NumWords, pVal); 1209 else 1210 return llvm::APInt(BitWidth, VAL); 1211 } 1212 void setIntValue(ASTContext &C, const llvm::APInt &Val); 1213 }; 1214 1215 class APIntStorage : private APNumericStorage { 1216 public: 1217 llvm::APInt getValue() const { return getIntValue(); } 1218 void setValue(ASTContext &C, const llvm::APInt &Val) { setIntValue(C, Val); } 1219 }; 1220 1221 class APFloatStorage : private APNumericStorage { 1222 public: 1223 llvm::APFloat getValue(const llvm::fltSemantics &Semantics) const { 1224 return llvm::APFloat(Semantics, getIntValue()); 1225 } 1226 void setValue(ASTContext &C, const llvm::APFloat &Val) { 1227 setIntValue(C, Val.bitcastToAPInt()); 1228 } 1229 }; 1230 1231 class IntegerLiteral : public Expr, public APIntStorage { 1232 SourceLocation Loc; 1233 1234 /// \brief Construct an empty integer literal. 1235 explicit IntegerLiteral(EmptyShell Empty) 1236 : Expr(IntegerLiteralClass, Empty) { } 1237 1238 public: 1239 // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy, 1240 // or UnsignedLongLongTy 1241 IntegerLiteral(ASTContext &C, const llvm::APInt &V, QualType type, 1242 SourceLocation l); 1243 1244 /// \brief Returns a new integer literal with value 'V' and type 'type'. 1245 /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy, 1246 /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V 1247 /// \param V - the value that the returned integer literal contains. 1248 static IntegerLiteral *Create(ASTContext &C, const llvm::APInt &V, 1249 QualType type, SourceLocation l); 1250 /// \brief Returns a new empty integer literal. 1251 static IntegerLiteral *Create(ASTContext &C, EmptyShell Empty); 1252 1253 SourceLocation getLocStart() const LLVM_READONLY { return Loc; } 1254 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; } 1255 1256 /// \brief Retrieve the location of the literal. 1257 SourceLocation getLocation() const { return Loc; } 1258 1259 void setLocation(SourceLocation Location) { Loc = Location; } 1260 1261 static bool classof(const Stmt *T) { 1262 return T->getStmtClass() == IntegerLiteralClass; 1263 } 1264 1265 // Iterators 1266 child_range children() { return child_range(); } 1267 }; 1268 1269 class CharacterLiteral : public Expr { 1270 public: 1271 enum CharacterKind { 1272 Ascii, 1273 Wide, 1274 UTF16, 1275 UTF32 1276 }; 1277 1278 private: 1279 unsigned Value; 1280 SourceLocation Loc; 1281 public: 1282 // type should be IntTy 1283 CharacterLiteral(unsigned value, CharacterKind kind, QualType type, 1284 SourceLocation l) 1285 : Expr(CharacterLiteralClass, type, VK_RValue, OK_Ordinary, false, false, 1286 false, false), 1287 Value(value), Loc(l) { 1288 CharacterLiteralBits.Kind = kind; 1289 } 1290 1291 /// \brief Construct an empty character literal. 1292 CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { } 1293 1294 SourceLocation getLocation() const { return Loc; } 1295 CharacterKind getKind() const { 1296 return static_cast<CharacterKind>(CharacterLiteralBits.Kind); 1297 } 1298 1299 SourceLocation getLocStart() const LLVM_READONLY { return Loc; } 1300 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; } 1301 1302 unsigned getValue() const { return Value; } 1303 1304 void setLocation(SourceLocation Location) { Loc = Location; } 1305 void setKind(CharacterKind kind) { CharacterLiteralBits.Kind = kind; } 1306 void setValue(unsigned Val) { Value = Val; } 1307 1308 static bool classof(const Stmt *T) { 1309 return T->getStmtClass() == CharacterLiteralClass; 1310 } 1311 1312 // Iterators 1313 child_range children() { return child_range(); } 1314 }; 1315 1316 class FloatingLiteral : public Expr, private APFloatStorage { 1317 SourceLocation Loc; 1318 1319 FloatingLiteral(ASTContext &C, const llvm::APFloat &V, bool isexact, 1320 QualType Type, SourceLocation L); 1321 1322 /// \brief Construct an empty floating-point literal. 1323 explicit FloatingLiteral(ASTContext &C, EmptyShell Empty); 1324 1325 public: 1326 static FloatingLiteral *Create(ASTContext &C, const llvm::APFloat &V, 1327 bool isexact, QualType Type, SourceLocation L); 1328 static FloatingLiteral *Create(ASTContext &C, EmptyShell Empty); 1329 1330 llvm::APFloat getValue() const { 1331 return APFloatStorage::getValue(getSemantics()); 1332 } 1333 void setValue(ASTContext &C, const llvm::APFloat &Val) { 1334 assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics"); 1335 APFloatStorage::setValue(C, Val); 1336 } 1337 1338 /// Get a raw enumeration value representing the floating-point semantics of 1339 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation. 1340 APFloatSemantics getRawSemantics() const { 1341 return static_cast<APFloatSemantics>(FloatingLiteralBits.Semantics); 1342 } 1343 1344 /// Set the raw enumeration value representing the floating-point semantics of 1345 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation. 1346 void setRawSemantics(APFloatSemantics Sem) { 1347 FloatingLiteralBits.Semantics = Sem; 1348 } 1349 1350 /// Return the APFloat semantics this literal uses. 1351 const llvm::fltSemantics &getSemantics() const; 1352 1353 /// Set the APFloat semantics this literal uses. 1354 void setSemantics(const llvm::fltSemantics &Sem); 1355 1356 bool isExact() const { return FloatingLiteralBits.IsExact; } 1357 void setExact(bool E) { FloatingLiteralBits.IsExact = E; } 1358 1359 /// getValueAsApproximateDouble - This returns the value as an inaccurate 1360 /// double. Note that this may cause loss of precision, but is useful for 1361 /// debugging dumps, etc. 1362 double getValueAsApproximateDouble() const; 1363 1364 SourceLocation getLocation() const { return Loc; } 1365 void setLocation(SourceLocation L) { Loc = L; } 1366 1367 SourceLocation getLocStart() const LLVM_READONLY { return Loc; } 1368 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; } 1369 1370 static bool classof(const Stmt *T) { 1371 return T->getStmtClass() == FloatingLiteralClass; 1372 } 1373 1374 // Iterators 1375 child_range children() { return child_range(); } 1376 }; 1377 1378 /// ImaginaryLiteral - We support imaginary integer and floating point literals, 1379 /// like "1.0i". We represent these as a wrapper around FloatingLiteral and 1380 /// IntegerLiteral classes. Instances of this class always have a Complex type 1381 /// whose element type matches the subexpression. 1382 /// 1383 class ImaginaryLiteral : public Expr { 1384 Stmt *Val; 1385 public: 1386 ImaginaryLiteral(Expr *val, QualType Ty) 1387 : Expr(ImaginaryLiteralClass, Ty, VK_RValue, OK_Ordinary, false, false, 1388 false, false), 1389 Val(val) {} 1390 1391 /// \brief Build an empty imaginary literal. 1392 explicit ImaginaryLiteral(EmptyShell Empty) 1393 : Expr(ImaginaryLiteralClass, Empty) { } 1394 1395 const Expr *getSubExpr() const { return cast<Expr>(Val); } 1396 Expr *getSubExpr() { return cast<Expr>(Val); } 1397 void setSubExpr(Expr *E) { Val = E; } 1398 1399 SourceLocation getLocStart() const LLVM_READONLY { return Val->getLocStart(); } 1400 SourceLocation getLocEnd() const LLVM_READONLY { return Val->getLocEnd(); } 1401 1402 static bool classof(const Stmt *T) { 1403 return T->getStmtClass() == ImaginaryLiteralClass; 1404 } 1405 1406 // Iterators 1407 child_range children() { return child_range(&Val, &Val+1); } 1408 }; 1409 1410 /// StringLiteral - This represents a string literal expression, e.g. "foo" 1411 /// or L"bar" (wide strings). The actual string is returned by getStrData() 1412 /// is NOT null-terminated, and the length of the string is determined by 1413 /// calling getByteLength(). The C type for a string is always a 1414 /// ConstantArrayType. In C++, the char type is const qualified, in C it is 1415 /// not. 1416 /// 1417 /// Note that strings in C can be formed by concatenation of multiple string 1418 /// literal pptokens in translation phase #6. This keeps track of the locations 1419 /// of each of these pieces. 1420 /// 1421 /// Strings in C can also be truncated and extended by assigning into arrays, 1422 /// e.g. with constructs like: 1423 /// char X[2] = "foobar"; 1424 /// In this case, getByteLength() will return 6, but the string literal will 1425 /// have type "char[2]". 1426 class StringLiteral : public Expr { 1427 public: 1428 enum StringKind { 1429 Ascii, 1430 Wide, 1431 UTF8, 1432 UTF16, 1433 UTF32 1434 }; 1435 1436 private: 1437 friend class ASTStmtReader; 1438 1439 union { 1440 const char *asChar; 1441 const uint16_t *asUInt16; 1442 const uint32_t *asUInt32; 1443 } StrData; 1444 unsigned Length; 1445 unsigned CharByteWidth : 4; 1446 unsigned Kind : 3; 1447 unsigned IsPascal : 1; 1448 unsigned NumConcatenated; 1449 SourceLocation TokLocs[1]; 1450 1451 StringLiteral(QualType Ty) : 1452 Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false, 1453 false) {} 1454 1455 static int mapCharByteWidth(TargetInfo const &target,StringKind k); 1456 1457 public: 1458 /// This is the "fully general" constructor that allows representation of 1459 /// strings formed from multiple concatenated tokens. 1460 static StringLiteral *Create(ASTContext &C, StringRef Str, StringKind Kind, 1461 bool Pascal, QualType Ty, 1462 const SourceLocation *Loc, unsigned NumStrs); 1463 1464 /// Simple constructor for string literals made from one token. 1465 static StringLiteral *Create(ASTContext &C, StringRef Str, StringKind Kind, 1466 bool Pascal, QualType Ty, 1467 SourceLocation Loc) { 1468 return Create(C, Str, Kind, Pascal, Ty, &Loc, 1); 1469 } 1470 1471 /// \brief Construct an empty string literal. 1472 static StringLiteral *CreateEmpty(ASTContext &C, unsigned NumStrs); 1473 1474 StringRef getString() const { 1475 assert(CharByteWidth==1 1476 && "This function is used in places that assume strings use char"); 1477 return StringRef(StrData.asChar, getByteLength()); 1478 } 1479 1480 /// Allow access to clients that need the byte representation, such as 1481 /// ASTWriterStmt::VisitStringLiteral(). 1482 StringRef getBytes() const { 1483 // FIXME: StringRef may not be the right type to use as a result for this. 1484 if (CharByteWidth == 1) 1485 return StringRef(StrData.asChar, getByteLength()); 1486 if (CharByteWidth == 4) 1487 return StringRef(reinterpret_cast<const char*>(StrData.asUInt32), 1488 getByteLength()); 1489 assert(CharByteWidth == 2 && "unsupported CharByteWidth"); 1490 return StringRef(reinterpret_cast<const char*>(StrData.asUInt16), 1491 getByteLength()); 1492 } 1493 1494 void outputString(raw_ostream &OS) const; 1495 1496 uint32_t getCodeUnit(size_t i) const { 1497 assert(i < Length && "out of bounds access"); 1498 if (CharByteWidth == 1) 1499 return static_cast<unsigned char>(StrData.asChar[i]); 1500 if (CharByteWidth == 4) 1501 return StrData.asUInt32[i]; 1502 assert(CharByteWidth == 2 && "unsupported CharByteWidth"); 1503 return StrData.asUInt16[i]; 1504 } 1505 1506 unsigned getByteLength() const { return CharByteWidth*Length; } 1507 unsigned getLength() const { return Length; } 1508 unsigned getCharByteWidth() const { return CharByteWidth; } 1509 1510 /// \brief Sets the string data to the given string data. 1511 void setString(ASTContext &C, StringRef Str, 1512 StringKind Kind, bool IsPascal); 1513 1514 StringKind getKind() const { return static_cast<StringKind>(Kind); } 1515 1516 1517 bool isAscii() const { return Kind == Ascii; } 1518 bool isWide() const { return Kind == Wide; } 1519 bool isUTF8() const { return Kind == UTF8; } 1520 bool isUTF16() const { return Kind == UTF16; } 1521 bool isUTF32() const { return Kind == UTF32; } 1522 bool isPascal() const { return IsPascal; } 1523 1524 bool containsNonAsciiOrNull() const { 1525 StringRef Str = getString(); 1526 for (unsigned i = 0, e = Str.size(); i != e; ++i) 1527 if (!isASCII(Str[i]) || !Str[i]) 1528 return true; 1529 return false; 1530 } 1531 1532 /// getNumConcatenated - Get the number of string literal tokens that were 1533 /// concatenated in translation phase #6 to form this string literal. 1534 unsigned getNumConcatenated() const { return NumConcatenated; } 1535 1536 SourceLocation getStrTokenLoc(unsigned TokNum) const { 1537 assert(TokNum < NumConcatenated && "Invalid tok number"); 1538 return TokLocs[TokNum]; 1539 } 1540 void setStrTokenLoc(unsigned TokNum, SourceLocation L) { 1541 assert(TokNum < NumConcatenated && "Invalid tok number"); 1542 TokLocs[TokNum] = L; 1543 } 1544 1545 /// getLocationOfByte - Return a source location that points to the specified 1546 /// byte of this string literal. 1547 /// 1548 /// Strings are amazingly complex. They can be formed from multiple tokens 1549 /// and can have escape sequences in them in addition to the usual trigraph 1550 /// and escaped newline business. This routine handles this complexity. 1551 /// 1552 SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM, 1553 const LangOptions &Features, 1554 const TargetInfo &Target) const; 1555 1556 typedef const SourceLocation *tokloc_iterator; 1557 tokloc_iterator tokloc_begin() const { return TokLocs; } 1558 tokloc_iterator tokloc_end() const { return TokLocs+NumConcatenated; } 1559 1560 SourceLocation getLocStart() const LLVM_READONLY { return TokLocs[0]; } 1561 SourceLocation getLocEnd() const LLVM_READONLY { 1562 return TokLocs[NumConcatenated - 1]; 1563 } 1564 1565 static bool classof(const Stmt *T) { 1566 return T->getStmtClass() == StringLiteralClass; 1567 } 1568 1569 // Iterators 1570 child_range children() { return child_range(); } 1571 }; 1572 1573 /// ParenExpr - This represents a parethesized expression, e.g. "(1)". This 1574 /// AST node is only formed if full location information is requested. 1575 class ParenExpr : public Expr { 1576 SourceLocation L, R; 1577 Stmt *Val; 1578 public: 1579 ParenExpr(SourceLocation l, SourceLocation r, Expr *val) 1580 : Expr(ParenExprClass, val->getType(), 1581 val->getValueKind(), val->getObjectKind(), 1582 val->isTypeDependent(), val->isValueDependent(), 1583 val->isInstantiationDependent(), 1584 val->containsUnexpandedParameterPack()), 1585 L(l), R(r), Val(val) {} 1586 1587 /// \brief Construct an empty parenthesized expression. 1588 explicit ParenExpr(EmptyShell Empty) 1589 : Expr(ParenExprClass, Empty) { } 1590 1591 const Expr *getSubExpr() const { return cast<Expr>(Val); } 1592 Expr *getSubExpr() { return cast<Expr>(Val); } 1593 void setSubExpr(Expr *E) { Val = E; } 1594 1595 SourceLocation getLocStart() const LLVM_READONLY { return L; } 1596 SourceLocation getLocEnd() const LLVM_READONLY { return R; } 1597 1598 /// \brief Get the location of the left parentheses '('. 1599 SourceLocation getLParen() const { return L; } 1600 void setLParen(SourceLocation Loc) { L = Loc; } 1601 1602 /// \brief Get the location of the right parentheses ')'. 1603 SourceLocation getRParen() const { return R; } 1604 void setRParen(SourceLocation Loc) { R = Loc; } 1605 1606 static bool classof(const Stmt *T) { 1607 return T->getStmtClass() == ParenExprClass; 1608 } 1609 1610 // Iterators 1611 child_range children() { return child_range(&Val, &Val+1); } 1612 }; 1613 1614 1615 /// UnaryOperator - This represents the unary-expression's (except sizeof and 1616 /// alignof), the postinc/postdec operators from postfix-expression, and various 1617 /// extensions. 1618 /// 1619 /// Notes on various nodes: 1620 /// 1621 /// Real/Imag - These return the real/imag part of a complex operand. If 1622 /// applied to a non-complex value, the former returns its operand and the 1623 /// later returns zero in the type of the operand. 1624 /// 1625 class UnaryOperator : public Expr { 1626 public: 1627 typedef UnaryOperatorKind Opcode; 1628 1629 private: 1630 unsigned Opc : 5; 1631 SourceLocation Loc; 1632 Stmt *Val; 1633 public: 1634 1635 UnaryOperator(Expr *input, Opcode opc, QualType type, 1636 ExprValueKind VK, ExprObjectKind OK, SourceLocation l) 1637 : Expr(UnaryOperatorClass, type, VK, OK, 1638 input->isTypeDependent() || type->isDependentType(), 1639 input->isValueDependent(), 1640 (input->isInstantiationDependent() || 1641 type->isInstantiationDependentType()), 1642 input->containsUnexpandedParameterPack()), 1643 Opc(opc), Loc(l), Val(input) {} 1644 1645 /// \brief Build an empty unary operator. 1646 explicit UnaryOperator(EmptyShell Empty) 1647 : Expr(UnaryOperatorClass, Empty), Opc(UO_AddrOf) { } 1648 1649 Opcode getOpcode() const { return static_cast<Opcode>(Opc); } 1650 void setOpcode(Opcode O) { Opc = O; } 1651 1652 Expr *getSubExpr() const { return cast<Expr>(Val); } 1653 void setSubExpr(Expr *E) { Val = E; } 1654 1655 /// getOperatorLoc - Return the location of the operator. 1656 SourceLocation getOperatorLoc() const { return Loc; } 1657 void setOperatorLoc(SourceLocation L) { Loc = L; } 1658 1659 /// isPostfix - Return true if this is a postfix operation, like x++. 1660 static bool isPostfix(Opcode Op) { 1661 return Op == UO_PostInc || Op == UO_PostDec; 1662 } 1663 1664 /// isPrefix - Return true if this is a prefix operation, like --x. 1665 static bool isPrefix(Opcode Op) { 1666 return Op == UO_PreInc || Op == UO_PreDec; 1667 } 1668 1669 bool isPrefix() const { return isPrefix(getOpcode()); } 1670 bool isPostfix() const { return isPostfix(getOpcode()); } 1671 1672 static bool isIncrementOp(Opcode Op) { 1673 return Op == UO_PreInc || Op == UO_PostInc; 1674 } 1675 bool isIncrementOp() const { 1676 return isIncrementOp(getOpcode()); 1677 } 1678 1679 static bool isDecrementOp(Opcode Op) { 1680 return Op == UO_PreDec || Op == UO_PostDec; 1681 } 1682 bool isDecrementOp() const { 1683 return isDecrementOp(getOpcode()); 1684 } 1685 1686 static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; } 1687 bool isIncrementDecrementOp() const { 1688 return isIncrementDecrementOp(getOpcode()); 1689 } 1690 1691 static bool isArithmeticOp(Opcode Op) { 1692 return Op >= UO_Plus && Op <= UO_LNot; 1693 } 1694 bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); } 1695 1696 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it 1697 /// corresponds to, e.g. "sizeof" or "[pre]++" 1698 static StringRef getOpcodeStr(Opcode Op); 1699 1700 /// \brief Retrieve the unary opcode that corresponds to the given 1701 /// overloaded operator. 1702 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix); 1703 1704 /// \brief Retrieve the overloaded operator kind that corresponds to 1705 /// the given unary opcode. 1706 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc); 1707 1708 SourceLocation getLocStart() const LLVM_READONLY { 1709 return isPostfix() ? Val->getLocStart() : Loc; 1710 } 1711 SourceLocation getLocEnd() const LLVM_READONLY { 1712 return isPostfix() ? Loc : Val->getLocEnd(); 1713 } 1714 SourceLocation getExprLoc() const LLVM_READONLY { return Loc; } 1715 1716 static bool classof(const Stmt *T) { 1717 return T->getStmtClass() == UnaryOperatorClass; 1718 } 1719 1720 // Iterators 1721 child_range children() { return child_range(&Val, &Val+1); } 1722 }; 1723 1724 /// OffsetOfExpr - [C99 7.17] - This represents an expression of the form 1725 /// offsetof(record-type, member-designator). For example, given: 1726 /// @code 1727 /// struct S { 1728 /// float f; 1729 /// double d; 1730 /// }; 1731 /// struct T { 1732 /// int i; 1733 /// struct S s[10]; 1734 /// }; 1735 /// @endcode 1736 /// we can represent and evaluate the expression @c offsetof(struct T, s[2].d). 1737 1738 class OffsetOfExpr : public Expr { 1739 public: 1740 // __builtin_offsetof(type, identifier(.identifier|[expr])*) 1741 class OffsetOfNode { 1742 public: 1743 /// \brief The kind of offsetof node we have. 1744 enum Kind { 1745 /// \brief An index into an array. 1746 Array = 0x00, 1747 /// \brief A field. 1748 Field = 0x01, 1749 /// \brief A field in a dependent type, known only by its name. 1750 Identifier = 0x02, 1751 /// \brief An implicit indirection through a C++ base class, when the 1752 /// field found is in a base class. 1753 Base = 0x03 1754 }; 1755 1756 private: 1757 enum { MaskBits = 2, Mask = 0x03 }; 1758 1759 /// \brief The source range that covers this part of the designator. 1760 SourceRange Range; 1761 1762 /// \brief The data describing the designator, which comes in three 1763 /// different forms, depending on the lower two bits. 1764 /// - An unsigned index into the array of Expr*'s stored after this node 1765 /// in memory, for [constant-expression] designators. 1766 /// - A FieldDecl*, for references to a known field. 1767 /// - An IdentifierInfo*, for references to a field with a given name 1768 /// when the class type is dependent. 1769 /// - A CXXBaseSpecifier*, for references that look at a field in a 1770 /// base class. 1771 uintptr_t Data; 1772 1773 public: 1774 /// \brief Create an offsetof node that refers to an array element. 1775 OffsetOfNode(SourceLocation LBracketLoc, unsigned Index, 1776 SourceLocation RBracketLoc) 1777 : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) { } 1778 1779 /// \brief Create an offsetof node that refers to a field. 1780 OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field, 1781 SourceLocation NameLoc) 1782 : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc), 1783 Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) { } 1784 1785 /// \brief Create an offsetof node that refers to an identifier. 1786 OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name, 1787 SourceLocation NameLoc) 1788 : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc), 1789 Data(reinterpret_cast<uintptr_t>(Name) | Identifier) { } 1790 1791 /// \brief Create an offsetof node that refers into a C++ base class. 1792 explicit OffsetOfNode(const CXXBaseSpecifier *Base) 1793 : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {} 1794 1795 /// \brief Determine what kind of offsetof node this is. 1796 Kind getKind() const { 1797 return static_cast<Kind>(Data & Mask); 1798 } 1799 1800 /// \brief For an array element node, returns the index into the array 1801 /// of expressions. 1802 unsigned getArrayExprIndex() const { 1803 assert(getKind() == Array); 1804 return Data >> 2; 1805 } 1806 1807 /// \brief For a field offsetof node, returns the field. 1808 FieldDecl *getField() const { 1809 assert(getKind() == Field); 1810 return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask); 1811 } 1812 1813 /// \brief For a field or identifier offsetof node, returns the name of 1814 /// the field. 1815 IdentifierInfo *getFieldName() const; 1816 1817 /// \brief For a base class node, returns the base specifier. 1818 CXXBaseSpecifier *getBase() const { 1819 assert(getKind() == Base); 1820 return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask); 1821 } 1822 1823 /// \brief Retrieve the source range that covers this offsetof node. 1824 /// 1825 /// For an array element node, the source range contains the locations of 1826 /// the square brackets. For a field or identifier node, the source range 1827 /// contains the location of the period (if there is one) and the 1828 /// identifier. 1829 SourceRange getSourceRange() const LLVM_READONLY { return Range; } 1830 SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); } 1831 SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); } 1832 }; 1833 1834 private: 1835 1836 SourceLocation OperatorLoc, RParenLoc; 1837 // Base type; 1838 TypeSourceInfo *TSInfo; 1839 // Number of sub-components (i.e. instances of OffsetOfNode). 1840 unsigned NumComps; 1841 // Number of sub-expressions (i.e. array subscript expressions). 1842 unsigned NumExprs; 1843 1844 OffsetOfExpr(ASTContext &C, QualType type, 1845 SourceLocation OperatorLoc, TypeSourceInfo *tsi, 1846 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs, 1847 SourceLocation RParenLoc); 1848 1849 explicit OffsetOfExpr(unsigned numComps, unsigned numExprs) 1850 : Expr(OffsetOfExprClass, EmptyShell()), 1851 TSInfo(0), NumComps(numComps), NumExprs(numExprs) {} 1852 1853 public: 1854 1855 static OffsetOfExpr *Create(ASTContext &C, QualType type, 1856 SourceLocation OperatorLoc, TypeSourceInfo *tsi, 1857 ArrayRef<OffsetOfNode> comps, 1858 ArrayRef<Expr*> exprs, SourceLocation RParenLoc); 1859 1860 static OffsetOfExpr *CreateEmpty(ASTContext &C, 1861 unsigned NumComps, unsigned NumExprs); 1862 1863 /// getOperatorLoc - Return the location of the operator. 1864 SourceLocation getOperatorLoc() const { return OperatorLoc; } 1865 void setOperatorLoc(SourceLocation L) { OperatorLoc = L; } 1866 1867 /// \brief Return the location of the right parentheses. 1868 SourceLocation getRParenLoc() const { return RParenLoc; } 1869 void setRParenLoc(SourceLocation R) { RParenLoc = R; } 1870 1871 TypeSourceInfo *getTypeSourceInfo() const { 1872 return TSInfo; 1873 } 1874 void setTypeSourceInfo(TypeSourceInfo *tsi) { 1875 TSInfo = tsi; 1876 } 1877 1878 const OffsetOfNode &getComponent(unsigned Idx) const { 1879 assert(Idx < NumComps && "Subscript out of range"); 1880 return reinterpret_cast<const OffsetOfNode *> (this + 1)[Idx]; 1881 } 1882 1883 void setComponent(unsigned Idx, OffsetOfNode ON) { 1884 assert(Idx < NumComps && "Subscript out of range"); 1885 reinterpret_cast<OffsetOfNode *> (this + 1)[Idx] = ON; 1886 } 1887 1888 unsigned getNumComponents() const { 1889 return NumComps; 1890 } 1891 1892 Expr* getIndexExpr(unsigned Idx) { 1893 assert(Idx < NumExprs && "Subscript out of range"); 1894 return reinterpret_cast<Expr **>( 1895 reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx]; 1896 } 1897 const Expr *getIndexExpr(unsigned Idx) const { 1898 return const_cast<OffsetOfExpr*>(this)->getIndexExpr(Idx); 1899 } 1900 1901 void setIndexExpr(unsigned Idx, Expr* E) { 1902 assert(Idx < NumComps && "Subscript out of range"); 1903 reinterpret_cast<Expr **>( 1904 reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx] = E; 1905 } 1906 1907 unsigned getNumExpressions() const { 1908 return NumExprs; 1909 } 1910 1911 SourceLocation getLocStart() const LLVM_READONLY { return OperatorLoc; } 1912 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } 1913 1914 static bool classof(const Stmt *T) { 1915 return T->getStmtClass() == OffsetOfExprClass; 1916 } 1917 1918 // Iterators 1919 child_range children() { 1920 Stmt **begin = 1921 reinterpret_cast<Stmt**>(reinterpret_cast<OffsetOfNode*>(this + 1) 1922 + NumComps); 1923 return child_range(begin, begin + NumExprs); 1924 } 1925 }; 1926 1927 /// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) 1928 /// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and 1929 /// vec_step (OpenCL 1.1 6.11.12). 1930 class UnaryExprOrTypeTraitExpr : public Expr { 1931 union { 1932 TypeSourceInfo *Ty; 1933 Stmt *Ex; 1934 } Argument; 1935 SourceLocation OpLoc, RParenLoc; 1936 1937 public: 1938 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo, 1939 QualType resultType, SourceLocation op, 1940 SourceLocation rp) : 1941 Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary, 1942 false, // Never type-dependent (C++ [temp.dep.expr]p3). 1943 // Value-dependent if the argument is type-dependent. 1944 TInfo->getType()->isDependentType(), 1945 TInfo->getType()->isInstantiationDependentType(), 1946 TInfo->getType()->containsUnexpandedParameterPack()), 1947 OpLoc(op), RParenLoc(rp) { 1948 UnaryExprOrTypeTraitExprBits.Kind = ExprKind; 1949 UnaryExprOrTypeTraitExprBits.IsType = true; 1950 Argument.Ty = TInfo; 1951 } 1952 1953 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E, 1954 QualType resultType, SourceLocation op, 1955 SourceLocation rp) : 1956 Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary, 1957 false, // Never type-dependent (C++ [temp.dep.expr]p3). 1958 // Value-dependent if the argument is type-dependent. 1959 E->isTypeDependent(), 1960 E->isInstantiationDependent(), 1961 E->containsUnexpandedParameterPack()), 1962 OpLoc(op), RParenLoc(rp) { 1963 UnaryExprOrTypeTraitExprBits.Kind = ExprKind; 1964 UnaryExprOrTypeTraitExprBits.IsType = false; 1965 Argument.Ex = E; 1966 } 1967 1968 /// \brief Construct an empty sizeof/alignof expression. 1969 explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty) 1970 : Expr(UnaryExprOrTypeTraitExprClass, Empty) { } 1971 1972 UnaryExprOrTypeTrait getKind() const { 1973 return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind); 1974 } 1975 void setKind(UnaryExprOrTypeTrait K) { UnaryExprOrTypeTraitExprBits.Kind = K;} 1976 1977 bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; } 1978 QualType getArgumentType() const { 1979 return getArgumentTypeInfo()->getType(); 1980 } 1981 TypeSourceInfo *getArgumentTypeInfo() const { 1982 assert(isArgumentType() && "calling getArgumentType() when arg is expr"); 1983 return Argument.Ty; 1984 } 1985 Expr *getArgumentExpr() { 1986 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type"); 1987 return static_cast<Expr*>(Argument.Ex); 1988 } 1989 const Expr *getArgumentExpr() const { 1990 return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr(); 1991 } 1992 1993 void setArgument(Expr *E) { 1994 Argument.Ex = E; 1995 UnaryExprOrTypeTraitExprBits.IsType = false; 1996 } 1997 void setArgument(TypeSourceInfo *TInfo) { 1998 Argument.Ty = TInfo; 1999 UnaryExprOrTypeTraitExprBits.IsType = true; 2000 } 2001 2002 /// Gets the argument type, or the type of the argument expression, whichever 2003 /// is appropriate. 2004 QualType getTypeOfArgument() const { 2005 return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType(); 2006 } 2007 2008 SourceLocation getOperatorLoc() const { return OpLoc; } 2009 void setOperatorLoc(SourceLocation L) { OpLoc = L; } 2010 2011 SourceLocation getRParenLoc() const { return RParenLoc; } 2012 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 2013 2014 SourceLocation getLocStart() const LLVM_READONLY { return OpLoc; } 2015 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } 2016 2017 static bool classof(const Stmt *T) { 2018 return T->getStmtClass() == UnaryExprOrTypeTraitExprClass; 2019 } 2020 2021 // Iterators 2022 child_range children(); 2023 }; 2024 2025 //===----------------------------------------------------------------------===// 2026 // Postfix Operators. 2027 //===----------------------------------------------------------------------===// 2028 2029 /// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting. 2030 class ArraySubscriptExpr : public Expr { 2031 enum { LHS, RHS, END_EXPR=2 }; 2032 Stmt* SubExprs[END_EXPR]; 2033 SourceLocation RBracketLoc; 2034 public: 2035 ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t, 2036 ExprValueKind VK, ExprObjectKind OK, 2037 SourceLocation rbracketloc) 2038 : Expr(ArraySubscriptExprClass, t, VK, OK, 2039 lhs->isTypeDependent() || rhs->isTypeDependent(), 2040 lhs->isValueDependent() || rhs->isValueDependent(), 2041 (lhs->isInstantiationDependent() || 2042 rhs->isInstantiationDependent()), 2043 (lhs->containsUnexpandedParameterPack() || 2044 rhs->containsUnexpandedParameterPack())), 2045 RBracketLoc(rbracketloc) { 2046 SubExprs[LHS] = lhs; 2047 SubExprs[RHS] = rhs; 2048 } 2049 2050 /// \brief Create an empty array subscript expression. 2051 explicit ArraySubscriptExpr(EmptyShell Shell) 2052 : Expr(ArraySubscriptExprClass, Shell) { } 2053 2054 /// An array access can be written A[4] or 4[A] (both are equivalent). 2055 /// - getBase() and getIdx() always present the normalized view: A[4]. 2056 /// In this case getBase() returns "A" and getIdx() returns "4". 2057 /// - getLHS() and getRHS() present the syntactic view. e.g. for 2058 /// 4[A] getLHS() returns "4". 2059 /// Note: Because vector element access is also written A[4] we must 2060 /// predicate the format conversion in getBase and getIdx only on the 2061 /// the type of the RHS, as it is possible for the LHS to be a vector of 2062 /// integer type 2063 Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); } 2064 const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } 2065 void setLHS(Expr *E) { SubExprs[LHS] = E; } 2066 2067 Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); } 2068 const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } 2069 void setRHS(Expr *E) { SubExprs[RHS] = E; } 2070 2071 Expr *getBase() { 2072 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS()); 2073 } 2074 2075 const Expr *getBase() const { 2076 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS()); 2077 } 2078 2079 Expr *getIdx() { 2080 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS()); 2081 } 2082 2083 const Expr *getIdx() const { 2084 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS()); 2085 } 2086 2087 SourceLocation getLocStart() const LLVM_READONLY { 2088 return getLHS()->getLocStart(); 2089 } 2090 SourceLocation getLocEnd() const LLVM_READONLY { return RBracketLoc; } 2091 2092 SourceLocation getRBracketLoc() const { return RBracketLoc; } 2093 void setRBracketLoc(SourceLocation L) { RBracketLoc = L; } 2094 2095 SourceLocation getExprLoc() const LLVM_READONLY { 2096 return getBase()->getExprLoc(); 2097 } 2098 2099 static bool classof(const Stmt *T) { 2100 return T->getStmtClass() == ArraySubscriptExprClass; 2101 } 2102 2103 // Iterators 2104 child_range children() { 2105 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); 2106 } 2107 }; 2108 2109 2110 /// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]). 2111 /// CallExpr itself represents a normal function call, e.g., "f(x, 2)", 2112 /// while its subclasses may represent alternative syntax that (semantically) 2113 /// results in a function call. For example, CXXOperatorCallExpr is 2114 /// a subclass for overloaded operator calls that use operator syntax, e.g., 2115 /// "str1 + str2" to resolve to a function call. 2116 class CallExpr : public Expr { 2117 enum { FN=0, PREARGS_START=1 }; 2118 Stmt **SubExprs; 2119 unsigned NumArgs; 2120 SourceLocation RParenLoc; 2121 2122 protected: 2123 // These versions of the constructor are for derived classes. 2124 CallExpr(ASTContext& C, StmtClass SC, Expr *fn, unsigned NumPreArgs, 2125 ArrayRef<Expr*> args, QualType t, ExprValueKind VK, 2126 SourceLocation rparenloc); 2127 CallExpr(ASTContext &C, StmtClass SC, unsigned NumPreArgs, EmptyShell Empty); 2128 2129 Stmt *getPreArg(unsigned i) { 2130 assert(i < getNumPreArgs() && "Prearg access out of range!"); 2131 return SubExprs[PREARGS_START+i]; 2132 } 2133 const Stmt *getPreArg(unsigned i) const { 2134 assert(i < getNumPreArgs() && "Prearg access out of range!"); 2135 return SubExprs[PREARGS_START+i]; 2136 } 2137 void setPreArg(unsigned i, Stmt *PreArg) { 2138 assert(i < getNumPreArgs() && "Prearg access out of range!"); 2139 SubExprs[PREARGS_START+i] = PreArg; 2140 } 2141 2142 unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; } 2143 2144 public: 2145 CallExpr(ASTContext& C, Expr *fn, ArrayRef<Expr*> args, QualType t, 2146 ExprValueKind VK, SourceLocation rparenloc); 2147 2148 /// \brief Build an empty call expression. 2149 CallExpr(ASTContext &C, StmtClass SC, EmptyShell Empty); 2150 2151 const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); } 2152 Expr *getCallee() { return cast<Expr>(SubExprs[FN]); } 2153 void setCallee(Expr *F) { SubExprs[FN] = F; } 2154 2155 Decl *getCalleeDecl(); 2156 const Decl *getCalleeDecl() const { 2157 return const_cast<CallExpr*>(this)->getCalleeDecl(); 2158 } 2159 2160 /// \brief If the callee is a FunctionDecl, return it. Otherwise return 0. 2161 FunctionDecl *getDirectCallee(); 2162 const FunctionDecl *getDirectCallee() const { 2163 return const_cast<CallExpr*>(this)->getDirectCallee(); 2164 } 2165 2166 /// getNumArgs - Return the number of actual arguments to this call. 2167 /// 2168 unsigned getNumArgs() const { return NumArgs; } 2169 2170 /// \brief Retrieve the call arguments. 2171 Expr **getArgs() { 2172 return reinterpret_cast<Expr **>(SubExprs+getNumPreArgs()+PREARGS_START); 2173 } 2174 const Expr *const *getArgs() const { 2175 return const_cast<CallExpr*>(this)->getArgs(); 2176 } 2177 2178 /// getArg - Return the specified argument. 2179 Expr *getArg(unsigned Arg) { 2180 assert(Arg < NumArgs && "Arg access out of range!"); 2181 return cast<Expr>(SubExprs[Arg+getNumPreArgs()+PREARGS_START]); 2182 } 2183 const Expr *getArg(unsigned Arg) const { 2184 assert(Arg < NumArgs && "Arg access out of range!"); 2185 return cast<Expr>(SubExprs[Arg+getNumPreArgs()+PREARGS_START]); 2186 } 2187 2188 /// setArg - Set the specified argument. 2189 void setArg(unsigned Arg, Expr *ArgExpr) { 2190 assert(Arg < NumArgs && "Arg access out of range!"); 2191 SubExprs[Arg+getNumPreArgs()+PREARGS_START] = ArgExpr; 2192 } 2193 2194 /// setNumArgs - This changes the number of arguments present in this call. 2195 /// Any orphaned expressions are deleted by this, and any new operands are set 2196 /// to null. 2197 void setNumArgs(ASTContext& C, unsigned NumArgs); 2198 2199 typedef ExprIterator arg_iterator; 2200 typedef ConstExprIterator const_arg_iterator; 2201 2202 arg_iterator arg_begin() { return SubExprs+PREARGS_START+getNumPreArgs(); } 2203 arg_iterator arg_end() { 2204 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs(); 2205 } 2206 const_arg_iterator arg_begin() const { 2207 return SubExprs+PREARGS_START+getNumPreArgs(); 2208 } 2209 const_arg_iterator arg_end() const { 2210 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs(); 2211 } 2212 2213 /// This method provides fast access to all the subexpressions of 2214 /// a CallExpr without going through the slower virtual child_iterator 2215 /// interface. This provides efficient reverse iteration of the 2216 /// subexpressions. This is currently used for CFG construction. 2217 ArrayRef<Stmt*> getRawSubExprs() { 2218 return ArrayRef<Stmt*>(SubExprs, 2219 getNumPreArgs() + PREARGS_START + getNumArgs()); 2220 } 2221 2222 /// getNumCommas - Return the number of commas that must have been present in 2223 /// this function call. 2224 unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; } 2225 2226 /// isBuiltinCall - If this is a call to a builtin, return the builtin ID. If 2227 /// not, return 0. 2228 unsigned isBuiltinCall() const; 2229 2230 /// \brief Returns \c true if this is a call to a builtin which does not 2231 /// evaluate side-effects within its arguments. 2232 bool isUnevaluatedBuiltinCall(ASTContext &Ctx) const; 2233 2234 /// getCallReturnType - Get the return type of the call expr. This is not 2235 /// always the type of the expr itself, if the return type is a reference 2236 /// type. 2237 QualType getCallReturnType() const; 2238 2239 SourceLocation getRParenLoc() const { return RParenLoc; } 2240 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 2241 2242 SourceLocation getLocStart() const LLVM_READONLY; 2243 SourceLocation getLocEnd() const LLVM_READONLY; 2244 2245 static bool classof(const Stmt *T) { 2246 return T->getStmtClass() >= firstCallExprConstant && 2247 T->getStmtClass() <= lastCallExprConstant; 2248 } 2249 2250 // Iterators 2251 child_range children() { 2252 return child_range(&SubExprs[0], 2253 &SubExprs[0]+NumArgs+getNumPreArgs()+PREARGS_START); 2254 } 2255 }; 2256 2257 /// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F. 2258 /// 2259 class MemberExpr : public Expr { 2260 /// Extra data stored in some member expressions. 2261 struct MemberNameQualifier { 2262 /// \brief The nested-name-specifier that qualifies the name, including 2263 /// source-location information. 2264 NestedNameSpecifierLoc QualifierLoc; 2265 2266 /// \brief The DeclAccessPair through which the MemberDecl was found due to 2267 /// name qualifiers. 2268 DeclAccessPair FoundDecl; 2269 }; 2270 2271 /// Base - the expression for the base pointer or structure references. In 2272 /// X.F, this is "X". 2273 Stmt *Base; 2274 2275 /// MemberDecl - This is the decl being referenced by the field/member name. 2276 /// In X.F, this is the decl referenced by F. 2277 ValueDecl *MemberDecl; 2278 2279 /// MemberDNLoc - Provides source/type location info for the 2280 /// declaration name embedded in MemberDecl. 2281 DeclarationNameLoc MemberDNLoc; 2282 2283 /// MemberLoc - This is the location of the member name. 2284 SourceLocation MemberLoc; 2285 2286 /// IsArrow - True if this is "X->F", false if this is "X.F". 2287 bool IsArrow : 1; 2288 2289 /// \brief True if this member expression used a nested-name-specifier to 2290 /// refer to the member, e.g., "x->Base::f", or found its member via a using 2291 /// declaration. When true, a MemberNameQualifier 2292 /// structure is allocated immediately after the MemberExpr. 2293 bool HasQualifierOrFoundDecl : 1; 2294 2295 /// \brief True if this member expression specified a template keyword 2296 /// and/or a template argument list explicitly, e.g., x->f<int>, 2297 /// x->template f, x->template f<int>. 2298 /// When true, an ASTTemplateKWAndArgsInfo structure and its 2299 /// TemplateArguments (if any) are allocated immediately after 2300 /// the MemberExpr or, if the member expression also has a qualifier, 2301 /// after the MemberNameQualifier structure. 2302 bool HasTemplateKWAndArgsInfo : 1; 2303 2304 /// \brief True if this member expression refers to a method that 2305 /// was resolved from an overloaded set having size greater than 1. 2306 bool HadMultipleCandidates : 1; 2307 2308 /// \brief Retrieve the qualifier that preceded the member name, if any. 2309 MemberNameQualifier *getMemberQualifier() { 2310 assert(HasQualifierOrFoundDecl); 2311 return reinterpret_cast<MemberNameQualifier *> (this + 1); 2312 } 2313 2314 /// \brief Retrieve the qualifier that preceded the member name, if any. 2315 const MemberNameQualifier *getMemberQualifier() const { 2316 return const_cast<MemberExpr *>(this)->getMemberQualifier(); 2317 } 2318 2319 public: 2320 MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl, 2321 const DeclarationNameInfo &NameInfo, QualType ty, 2322 ExprValueKind VK, ExprObjectKind OK) 2323 : Expr(MemberExprClass, ty, VK, OK, 2324 base->isTypeDependent(), 2325 base->isValueDependent(), 2326 base->isInstantiationDependent(), 2327 base->containsUnexpandedParameterPack()), 2328 Base(base), MemberDecl(memberdecl), MemberDNLoc(NameInfo.getInfo()), 2329 MemberLoc(NameInfo.getLoc()), IsArrow(isarrow), 2330 HasQualifierOrFoundDecl(false), HasTemplateKWAndArgsInfo(false), 2331 HadMultipleCandidates(false) { 2332 assert(memberdecl->getDeclName() == NameInfo.getName()); 2333 } 2334 2335 // NOTE: this constructor should be used only when it is known that 2336 // the member name can not provide additional syntactic info 2337 // (i.e., source locations for C++ operator names or type source info 2338 // for constructors, destructors and conversion operators). 2339 MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl, 2340 SourceLocation l, QualType ty, 2341 ExprValueKind VK, ExprObjectKind OK) 2342 : Expr(MemberExprClass, ty, VK, OK, 2343 base->isTypeDependent(), base->isValueDependent(), 2344 base->isInstantiationDependent(), 2345 base->containsUnexpandedParameterPack()), 2346 Base(base), MemberDecl(memberdecl), MemberDNLoc(), MemberLoc(l), 2347 IsArrow(isarrow), 2348 HasQualifierOrFoundDecl(false), HasTemplateKWAndArgsInfo(false), 2349 HadMultipleCandidates(false) {} 2350 2351 static MemberExpr *Create(ASTContext &C, Expr *base, bool isarrow, 2352 NestedNameSpecifierLoc QualifierLoc, 2353 SourceLocation TemplateKWLoc, 2354 ValueDecl *memberdecl, DeclAccessPair founddecl, 2355 DeclarationNameInfo MemberNameInfo, 2356 const TemplateArgumentListInfo *targs, 2357 QualType ty, ExprValueKind VK, ExprObjectKind OK); 2358 2359 void setBase(Expr *E) { Base = E; } 2360 Expr *getBase() const { return cast<Expr>(Base); } 2361 2362 /// \brief Retrieve the member declaration to which this expression refers. 2363 /// 2364 /// The returned declaration will either be a FieldDecl or (in C++) 2365 /// a CXXMethodDecl. 2366 ValueDecl *getMemberDecl() const { return MemberDecl; } 2367 void setMemberDecl(ValueDecl *D) { MemberDecl = D; } 2368 2369 /// \brief Retrieves the declaration found by lookup. 2370 DeclAccessPair getFoundDecl() const { 2371 if (!HasQualifierOrFoundDecl) 2372 return DeclAccessPair::make(getMemberDecl(), 2373 getMemberDecl()->getAccess()); 2374 return getMemberQualifier()->FoundDecl; 2375 } 2376 2377 /// \brief Determines whether this member expression actually had 2378 /// a C++ nested-name-specifier prior to the name of the member, e.g., 2379 /// x->Base::foo. 2380 bool hasQualifier() const { return getQualifier() != 0; } 2381 2382 /// \brief If the member name was qualified, retrieves the 2383 /// nested-name-specifier that precedes the member name. Otherwise, returns 2384 /// NULL. 2385 NestedNameSpecifier *getQualifier() const { 2386 if (!HasQualifierOrFoundDecl) 2387 return 0; 2388 2389 return getMemberQualifier()->QualifierLoc.getNestedNameSpecifier(); 2390 } 2391 2392 /// \brief If the member name was qualified, retrieves the 2393 /// nested-name-specifier that precedes the member name, with source-location 2394 /// information. 2395 NestedNameSpecifierLoc getQualifierLoc() const { 2396 if (!hasQualifier()) 2397 return NestedNameSpecifierLoc(); 2398 2399 return getMemberQualifier()->QualifierLoc; 2400 } 2401 2402 /// \brief Return the optional template keyword and arguments info. 2403 ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() { 2404 if (!HasTemplateKWAndArgsInfo) 2405 return 0; 2406 2407 if (!HasQualifierOrFoundDecl) 2408 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(this + 1); 2409 2410 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>( 2411 getMemberQualifier() + 1); 2412 } 2413 2414 /// \brief Return the optional template keyword and arguments info. 2415 const ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() const { 2416 return const_cast<MemberExpr*>(this)->getTemplateKWAndArgsInfo(); 2417 } 2418 2419 /// \brief Retrieve the location of the template keyword preceding 2420 /// the member name, if any. 2421 SourceLocation getTemplateKeywordLoc() const { 2422 if (!HasTemplateKWAndArgsInfo) return SourceLocation(); 2423 return getTemplateKWAndArgsInfo()->getTemplateKeywordLoc(); 2424 } 2425 2426 /// \brief Retrieve the location of the left angle bracket starting the 2427 /// explicit template argument list following the member name, if any. 2428 SourceLocation getLAngleLoc() const { 2429 if (!HasTemplateKWAndArgsInfo) return SourceLocation(); 2430 return getTemplateKWAndArgsInfo()->LAngleLoc; 2431 } 2432 2433 /// \brief Retrieve the location of the right angle bracket ending the 2434 /// explicit template argument list following the member name, if any. 2435 SourceLocation getRAngleLoc() const { 2436 if (!HasTemplateKWAndArgsInfo) return SourceLocation(); 2437 return getTemplateKWAndArgsInfo()->RAngleLoc; 2438 } 2439 2440 /// Determines whether the member name was preceded by the template keyword. 2441 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); } 2442 2443 /// \brief Determines whether the member name was followed by an 2444 /// explicit template argument list. 2445 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); } 2446 2447 /// \brief Copies the template arguments (if present) into the given 2448 /// structure. 2449 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const { 2450 if (hasExplicitTemplateArgs()) 2451 getExplicitTemplateArgs().copyInto(List); 2452 } 2453 2454 /// \brief Retrieve the explicit template argument list that 2455 /// follow the member template name. This must only be called on an 2456 /// expression with explicit template arguments. 2457 ASTTemplateArgumentListInfo &getExplicitTemplateArgs() { 2458 assert(hasExplicitTemplateArgs()); 2459 return *getTemplateKWAndArgsInfo(); 2460 } 2461 2462 /// \brief Retrieve the explicit template argument list that 2463 /// followed the member template name. This must only be called on 2464 /// an expression with explicit template arguments. 2465 const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const { 2466 return const_cast<MemberExpr *>(this)->getExplicitTemplateArgs(); 2467 } 2468 2469 /// \brief Retrieves the optional explicit template arguments. 2470 /// This points to the same data as getExplicitTemplateArgs(), but 2471 /// returns null if there are no explicit template arguments. 2472 const ASTTemplateArgumentListInfo *getOptionalExplicitTemplateArgs() const { 2473 if (!hasExplicitTemplateArgs()) return 0; 2474 return &getExplicitTemplateArgs(); 2475 } 2476 2477 /// \brief Retrieve the template arguments provided as part of this 2478 /// template-id. 2479 const TemplateArgumentLoc *getTemplateArgs() const { 2480 if (!hasExplicitTemplateArgs()) 2481 return 0; 2482 2483 return getExplicitTemplateArgs().getTemplateArgs(); 2484 } 2485 2486 /// \brief Retrieve the number of template arguments provided as part of this 2487 /// template-id. 2488 unsigned getNumTemplateArgs() const { 2489 if (!hasExplicitTemplateArgs()) 2490 return 0; 2491 2492 return getExplicitTemplateArgs().NumTemplateArgs; 2493 } 2494 2495 /// \brief Retrieve the member declaration name info. 2496 DeclarationNameInfo getMemberNameInfo() const { 2497 return DeclarationNameInfo(MemberDecl->getDeclName(), 2498 MemberLoc, MemberDNLoc); 2499 } 2500 2501 bool isArrow() const { return IsArrow; } 2502 void setArrow(bool A) { IsArrow = A; } 2503 2504 /// getMemberLoc - Return the location of the "member", in X->F, it is the 2505 /// location of 'F'. 2506 SourceLocation getMemberLoc() const { return MemberLoc; } 2507 void setMemberLoc(SourceLocation L) { MemberLoc = L; } 2508 2509 SourceLocation getLocStart() const LLVM_READONLY; 2510 SourceLocation getLocEnd() const LLVM_READONLY; 2511 2512 SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; } 2513 2514 /// \brief Determine whether the base of this explicit is implicit. 2515 bool isImplicitAccess() const { 2516 return getBase() && getBase()->isImplicitCXXThis(); 2517 } 2518 2519 /// \brief Returns true if this member expression refers to a method that 2520 /// was resolved from an overloaded set having size greater than 1. 2521 bool hadMultipleCandidates() const { 2522 return HadMultipleCandidates; 2523 } 2524 /// \brief Sets the flag telling whether this expression refers to 2525 /// a method that was resolved from an overloaded set having size 2526 /// greater than 1. 2527 void setHadMultipleCandidates(bool V = true) { 2528 HadMultipleCandidates = V; 2529 } 2530 2531 static bool classof(const Stmt *T) { 2532 return T->getStmtClass() == MemberExprClass; 2533 } 2534 2535 // Iterators 2536 child_range children() { return child_range(&Base, &Base+1); } 2537 2538 friend class ASTReader; 2539 friend class ASTStmtWriter; 2540 }; 2541 2542 /// CompoundLiteralExpr - [C99 6.5.2.5] 2543 /// 2544 class CompoundLiteralExpr : public Expr { 2545 /// LParenLoc - If non-null, this is the location of the left paren in a 2546 /// compound literal like "(int){4}". This can be null if this is a 2547 /// synthesized compound expression. 2548 SourceLocation LParenLoc; 2549 2550 /// The type as written. This can be an incomplete array type, in 2551 /// which case the actual expression type will be different. 2552 /// The int part of the pair stores whether this expr is file scope. 2553 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope; 2554 Stmt *Init; 2555 public: 2556 CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo, 2557 QualType T, ExprValueKind VK, Expr *init, bool fileScope) 2558 : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary, 2559 tinfo->getType()->isDependentType(), 2560 init->isValueDependent(), 2561 (init->isInstantiationDependent() || 2562 tinfo->getType()->isInstantiationDependentType()), 2563 init->containsUnexpandedParameterPack()), 2564 LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {} 2565 2566 /// \brief Construct an empty compound literal. 2567 explicit CompoundLiteralExpr(EmptyShell Empty) 2568 : Expr(CompoundLiteralExprClass, Empty) { } 2569 2570 const Expr *getInitializer() const { return cast<Expr>(Init); } 2571 Expr *getInitializer() { return cast<Expr>(Init); } 2572 void setInitializer(Expr *E) { Init = E; } 2573 2574 bool isFileScope() const { return TInfoAndScope.getInt(); } 2575 void setFileScope(bool FS) { TInfoAndScope.setInt(FS); } 2576 2577 SourceLocation getLParenLoc() const { return LParenLoc; } 2578 void setLParenLoc(SourceLocation L) { LParenLoc = L; } 2579 2580 TypeSourceInfo *getTypeSourceInfo() const { 2581 return TInfoAndScope.getPointer(); 2582 } 2583 void setTypeSourceInfo(TypeSourceInfo *tinfo) { 2584 TInfoAndScope.setPointer(tinfo); 2585 } 2586 2587 SourceLocation getLocStart() const LLVM_READONLY { 2588 // FIXME: Init should never be null. 2589 if (!Init) 2590 return SourceLocation(); 2591 if (LParenLoc.isInvalid()) 2592 return Init->getLocStart(); 2593 return LParenLoc; 2594 } 2595 SourceLocation getLocEnd() const LLVM_READONLY { 2596 // FIXME: Init should never be null. 2597 if (!Init) 2598 return SourceLocation(); 2599 return Init->getLocEnd(); 2600 } 2601 2602 static bool classof(const Stmt *T) { 2603 return T->getStmtClass() == CompoundLiteralExprClass; 2604 } 2605 2606 // Iterators 2607 child_range children() { return child_range(&Init, &Init+1); } 2608 }; 2609 2610 /// CastExpr - Base class for type casts, including both implicit 2611 /// casts (ImplicitCastExpr) and explicit casts that have some 2612 /// representation in the source code (ExplicitCastExpr's derived 2613 /// classes). 2614 class CastExpr : public Expr { 2615 public: 2616 typedef clang::CastKind CastKind; 2617 2618 private: 2619 Stmt *Op; 2620 2621 void CheckCastConsistency() const; 2622 2623 const CXXBaseSpecifier * const *path_buffer() const { 2624 return const_cast<CastExpr*>(this)->path_buffer(); 2625 } 2626 CXXBaseSpecifier **path_buffer(); 2627 2628 void setBasePathSize(unsigned basePathSize) { 2629 CastExprBits.BasePathSize = basePathSize; 2630 assert(CastExprBits.BasePathSize == basePathSize && 2631 "basePathSize doesn't fit in bits of CastExprBits.BasePathSize!"); 2632 } 2633 2634 protected: 2635 CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, 2636 const CastKind kind, Expr *op, unsigned BasePathSize) : 2637 Expr(SC, ty, VK, OK_Ordinary, 2638 // Cast expressions are type-dependent if the type is 2639 // dependent (C++ [temp.dep.expr]p3). 2640 ty->isDependentType(), 2641 // Cast expressions are value-dependent if the type is 2642 // dependent or if the subexpression is value-dependent. 2643 ty->isDependentType() || (op && op->isValueDependent()), 2644 (ty->isInstantiationDependentType() || 2645 (op && op->isInstantiationDependent())), 2646 (ty->containsUnexpandedParameterPack() || 2647 op->containsUnexpandedParameterPack())), 2648 Op(op) { 2649 assert(kind != CK_Invalid && "creating cast with invalid cast kind"); 2650 CastExprBits.Kind = kind; 2651 setBasePathSize(BasePathSize); 2652 #ifndef NDEBUG 2653 CheckCastConsistency(); 2654 #endif 2655 } 2656 2657 /// \brief Construct an empty cast. 2658 CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize) 2659 : Expr(SC, Empty) { 2660 setBasePathSize(BasePathSize); 2661 } 2662 2663 public: 2664 CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; } 2665 void setCastKind(CastKind K) { CastExprBits.Kind = K; } 2666 const char *getCastKindName() const; 2667 2668 Expr *getSubExpr() { return cast<Expr>(Op); } 2669 const Expr *getSubExpr() const { return cast<Expr>(Op); } 2670 void setSubExpr(Expr *E) { Op = E; } 2671 2672 /// \brief Retrieve the cast subexpression as it was written in the source 2673 /// code, looking through any implicit casts or other intermediate nodes 2674 /// introduced by semantic analysis. 2675 Expr *getSubExprAsWritten(); 2676 const Expr *getSubExprAsWritten() const { 2677 return const_cast<CastExpr *>(this)->getSubExprAsWritten(); 2678 } 2679 2680 typedef CXXBaseSpecifier **path_iterator; 2681 typedef const CXXBaseSpecifier * const *path_const_iterator; 2682 bool path_empty() const { return CastExprBits.BasePathSize == 0; } 2683 unsigned path_size() const { return CastExprBits.BasePathSize; } 2684 path_iterator path_begin() { return path_buffer(); } 2685 path_iterator path_end() { return path_buffer() + path_size(); } 2686 path_const_iterator path_begin() const { return path_buffer(); } 2687 path_const_iterator path_end() const { return path_buffer() + path_size(); } 2688 2689 void setCastPath(const CXXCastPath &Path); 2690 2691 static bool classof(const Stmt *T) { 2692 return T->getStmtClass() >= firstCastExprConstant && 2693 T->getStmtClass() <= lastCastExprConstant; 2694 } 2695 2696 // Iterators 2697 child_range children() { return child_range(&Op, &Op+1); } 2698 }; 2699 2700 /// ImplicitCastExpr - Allows us to explicitly represent implicit type 2701 /// conversions, which have no direct representation in the original 2702 /// source code. For example: converting T[]->T*, void f()->void 2703 /// (*f)(), float->double, short->int, etc. 2704 /// 2705 /// In C, implicit casts always produce rvalues. However, in C++, an 2706 /// implicit cast whose result is being bound to a reference will be 2707 /// an lvalue or xvalue. For example: 2708 /// 2709 /// @code 2710 /// class Base { }; 2711 /// class Derived : public Base { }; 2712 /// Derived &&ref(); 2713 /// void f(Derived d) { 2714 /// Base& b = d; // initializer is an ImplicitCastExpr 2715 /// // to an lvalue of type Base 2716 /// Base&& r = ref(); // initializer is an ImplicitCastExpr 2717 /// // to an xvalue of type Base 2718 /// } 2719 /// @endcode 2720 class ImplicitCastExpr : public CastExpr { 2721 private: 2722 ImplicitCastExpr(QualType ty, CastKind kind, Expr *op, 2723 unsigned BasePathLength, ExprValueKind VK) 2724 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) { 2725 } 2726 2727 /// \brief Construct an empty implicit cast. 2728 explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize) 2729 : CastExpr(ImplicitCastExprClass, Shell, PathSize) { } 2730 2731 public: 2732 enum OnStack_t { OnStack }; 2733 ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op, 2734 ExprValueKind VK) 2735 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) { 2736 } 2737 2738 static ImplicitCastExpr *Create(ASTContext &Context, QualType T, 2739 CastKind Kind, Expr *Operand, 2740 const CXXCastPath *BasePath, 2741 ExprValueKind Cat); 2742 2743 static ImplicitCastExpr *CreateEmpty(ASTContext &Context, unsigned PathSize); 2744 2745 SourceLocation getLocStart() const LLVM_READONLY { 2746 return getSubExpr()->getLocStart(); 2747 } 2748 SourceLocation getLocEnd() const LLVM_READONLY { 2749 return getSubExpr()->getLocEnd(); 2750 } 2751 2752 static bool classof(const Stmt *T) { 2753 return T->getStmtClass() == ImplicitCastExprClass; 2754 } 2755 }; 2756 2757 inline Expr *Expr::IgnoreImpCasts() { 2758 Expr *e = this; 2759 while (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e)) 2760 e = ice->getSubExpr(); 2761 return e; 2762 } 2763 2764 /// ExplicitCastExpr - An explicit cast written in the source 2765 /// code. 2766 /// 2767 /// This class is effectively an abstract class, because it provides 2768 /// the basic representation of an explicitly-written cast without 2769 /// specifying which kind of cast (C cast, functional cast, static 2770 /// cast, etc.) was written; specific derived classes represent the 2771 /// particular style of cast and its location information. 2772 /// 2773 /// Unlike implicit casts, explicit cast nodes have two different 2774 /// types: the type that was written into the source code, and the 2775 /// actual type of the expression as determined by semantic 2776 /// analysis. These types may differ slightly. For example, in C++ one 2777 /// can cast to a reference type, which indicates that the resulting 2778 /// expression will be an lvalue or xvalue. The reference type, however, 2779 /// will not be used as the type of the expression. 2780 class ExplicitCastExpr : public CastExpr { 2781 /// TInfo - Source type info for the (written) type 2782 /// this expression is casting to. 2783 TypeSourceInfo *TInfo; 2784 2785 protected: 2786 ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK, 2787 CastKind kind, Expr *op, unsigned PathSize, 2788 TypeSourceInfo *writtenTy) 2789 : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {} 2790 2791 /// \brief Construct an empty explicit cast. 2792 ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize) 2793 : CastExpr(SC, Shell, PathSize) { } 2794 2795 public: 2796 /// getTypeInfoAsWritten - Returns the type source info for the type 2797 /// that this expression is casting to. 2798 TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; } 2799 void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; } 2800 2801 /// getTypeAsWritten - Returns the type that this expression is 2802 /// casting to, as written in the source code. 2803 QualType getTypeAsWritten() const { return TInfo->getType(); } 2804 2805 static bool classof(const Stmt *T) { 2806 return T->getStmtClass() >= firstExplicitCastExprConstant && 2807 T->getStmtClass() <= lastExplicitCastExprConstant; 2808 } 2809 }; 2810 2811 /// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style 2812 /// cast in C++ (C++ [expr.cast]), which uses the syntax 2813 /// (Type)expr. For example: @c (int)f. 2814 class CStyleCastExpr : public ExplicitCastExpr { 2815 SourceLocation LPLoc; // the location of the left paren 2816 SourceLocation RPLoc; // the location of the right paren 2817 2818 CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op, 2819 unsigned PathSize, TypeSourceInfo *writtenTy, 2820 SourceLocation l, SourceLocation r) 2821 : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize, 2822 writtenTy), LPLoc(l), RPLoc(r) {} 2823 2824 /// \brief Construct an empty C-style explicit cast. 2825 explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize) 2826 : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { } 2827 2828 public: 2829 static CStyleCastExpr *Create(ASTContext &Context, QualType T, 2830 ExprValueKind VK, CastKind K, 2831 Expr *Op, const CXXCastPath *BasePath, 2832 TypeSourceInfo *WrittenTy, SourceLocation L, 2833 SourceLocation R); 2834 2835 static CStyleCastExpr *CreateEmpty(ASTContext &Context, unsigned PathSize); 2836 2837 SourceLocation getLParenLoc() const { return LPLoc; } 2838 void setLParenLoc(SourceLocation L) { LPLoc = L; } 2839 2840 SourceLocation getRParenLoc() const { return RPLoc; } 2841 void setRParenLoc(SourceLocation L) { RPLoc = L; } 2842 2843 SourceLocation getLocStart() const LLVM_READONLY { return LPLoc; } 2844 SourceLocation getLocEnd() const LLVM_READONLY { 2845 return getSubExpr()->getLocEnd(); 2846 } 2847 2848 static bool classof(const Stmt *T) { 2849 return T->getStmtClass() == CStyleCastExprClass; 2850 } 2851 }; 2852 2853 /// \brief A builtin binary operation expression such as "x + y" or "x <= y". 2854 /// 2855 /// This expression node kind describes a builtin binary operation, 2856 /// such as "x + y" for integer values "x" and "y". The operands will 2857 /// already have been converted to appropriate types (e.g., by 2858 /// performing promotions or conversions). 2859 /// 2860 /// In C++, where operators may be overloaded, a different kind of 2861 /// expression node (CXXOperatorCallExpr) is used to express the 2862 /// invocation of an overloaded operator with operator syntax. Within 2863 /// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is 2864 /// used to store an expression "x + y" depends on the subexpressions 2865 /// for x and y. If neither x or y is type-dependent, and the "+" 2866 /// operator resolves to a built-in operation, BinaryOperator will be 2867 /// used to express the computation (x and y may still be 2868 /// value-dependent). If either x or y is type-dependent, or if the 2869 /// "+" resolves to an overloaded operator, CXXOperatorCallExpr will 2870 /// be used to express the computation. 2871 class BinaryOperator : public Expr { 2872 public: 2873 typedef BinaryOperatorKind Opcode; 2874 2875 private: 2876 unsigned Opc : 6; 2877 2878 // Records the FP_CONTRACT pragma status at the point that this binary 2879 // operator was parsed. This bit is only meaningful for operations on 2880 // floating point types. For all other types it should default to 2881 // false. 2882 unsigned FPContractable : 1; 2883 SourceLocation OpLoc; 2884 2885 enum { LHS, RHS, END_EXPR }; 2886 Stmt* SubExprs[END_EXPR]; 2887 public: 2888 2889 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, 2890 ExprValueKind VK, ExprObjectKind OK, 2891 SourceLocation opLoc, bool fpContractable) 2892 : Expr(BinaryOperatorClass, ResTy, VK, OK, 2893 lhs->isTypeDependent() || rhs->isTypeDependent(), 2894 lhs->isValueDependent() || rhs->isValueDependent(), 2895 (lhs->isInstantiationDependent() || 2896 rhs->isInstantiationDependent()), 2897 (lhs->containsUnexpandedParameterPack() || 2898 rhs->containsUnexpandedParameterPack())), 2899 Opc(opc), FPContractable(fpContractable), OpLoc(opLoc) { 2900 SubExprs[LHS] = lhs; 2901 SubExprs[RHS] = rhs; 2902 assert(!isCompoundAssignmentOp() && 2903 "Use ArithAssignBinaryOperator for compound assignments"); 2904 } 2905 2906 /// \brief Construct an empty binary operator. 2907 explicit BinaryOperator(EmptyShell Empty) 2908 : Expr(BinaryOperatorClass, Empty), Opc(BO_Comma) { } 2909 2910 SourceLocation getExprLoc() const LLVM_READONLY { return OpLoc; } 2911 SourceLocation getOperatorLoc() const { return OpLoc; } 2912 void setOperatorLoc(SourceLocation L) { OpLoc = L; } 2913 2914 Opcode getOpcode() const { return static_cast<Opcode>(Opc); } 2915 void setOpcode(Opcode O) { Opc = O; } 2916 2917 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } 2918 void setLHS(Expr *E) { SubExprs[LHS] = E; } 2919 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } 2920 void setRHS(Expr *E) { SubExprs[RHS] = E; } 2921 2922 SourceLocation getLocStart() const LLVM_READONLY { 2923 return getLHS()->getLocStart(); 2924 } 2925 SourceLocation getLocEnd() const LLVM_READONLY { 2926 return getRHS()->getLocEnd(); 2927 } 2928 2929 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it 2930 /// corresponds to, e.g. "<<=". 2931 static StringRef getOpcodeStr(Opcode Op); 2932 2933 StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); } 2934 2935 /// \brief Retrieve the binary opcode that corresponds to the given 2936 /// overloaded operator. 2937 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO); 2938 2939 /// \brief Retrieve the overloaded operator kind that corresponds to 2940 /// the given binary opcode. 2941 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc); 2942 2943 /// predicates to categorize the respective opcodes. 2944 bool isPtrMemOp() const { return Opc == BO_PtrMemD || Opc == BO_PtrMemI; } 2945 bool isMultiplicativeOp() const { return Opc >= BO_Mul && Opc <= BO_Rem; } 2946 static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; } 2947 bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); } 2948 static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; } 2949 bool isShiftOp() const { return isShiftOp(getOpcode()); } 2950 2951 static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; } 2952 bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); } 2953 2954 static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; } 2955 bool isRelationalOp() const { return isRelationalOp(getOpcode()); } 2956 2957 static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; } 2958 bool isEqualityOp() const { return isEqualityOp(getOpcode()); } 2959 2960 static bool isComparisonOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_NE; } 2961 bool isComparisonOp() const { return isComparisonOp(getOpcode()); } 2962 2963 static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; } 2964 bool isLogicalOp() const { return isLogicalOp(getOpcode()); } 2965 2966 static bool isAssignmentOp(Opcode Opc) { 2967 return Opc >= BO_Assign && Opc <= BO_OrAssign; 2968 } 2969 bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); } 2970 2971 static bool isCompoundAssignmentOp(Opcode Opc) { 2972 return Opc > BO_Assign && Opc <= BO_OrAssign; 2973 } 2974 bool isCompoundAssignmentOp() const { 2975 return isCompoundAssignmentOp(getOpcode()); 2976 } 2977 static Opcode getOpForCompoundAssignment(Opcode Opc) { 2978 assert(isCompoundAssignmentOp(Opc)); 2979 if (Opc >= BO_AndAssign) 2980 return Opcode(unsigned(Opc) - BO_AndAssign + BO_And); 2981 else 2982 return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul); 2983 } 2984 2985 static bool isShiftAssignOp(Opcode Opc) { 2986 return Opc == BO_ShlAssign || Opc == BO_ShrAssign; 2987 } 2988 bool isShiftAssignOp() const { 2989 return isShiftAssignOp(getOpcode()); 2990 } 2991 2992 static bool classof(const Stmt *S) { 2993 return S->getStmtClass() >= firstBinaryOperatorConstant && 2994 S->getStmtClass() <= lastBinaryOperatorConstant; 2995 } 2996 2997 // Iterators 2998 child_range children() { 2999 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); 3000 } 3001 3002 // Set the FP contractability status of this operator. Only meaningful for 3003 // operations on floating point types. 3004 void setFPContractable(bool FPC) { FPContractable = FPC; } 3005 3006 // Get the FP contractability status of this operator. Only meaningful for 3007 // operations on floating point types. 3008 bool isFPContractable() const { return FPContractable; } 3009 3010 protected: 3011 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, 3012 ExprValueKind VK, ExprObjectKind OK, 3013 SourceLocation opLoc, bool fpContractable, bool dead2) 3014 : Expr(CompoundAssignOperatorClass, ResTy, VK, OK, 3015 lhs->isTypeDependent() || rhs->isTypeDependent(), 3016 lhs->isValueDependent() || rhs->isValueDependent(), 3017 (lhs->isInstantiationDependent() || 3018 rhs->isInstantiationDependent()), 3019 (lhs->containsUnexpandedParameterPack() || 3020 rhs->containsUnexpandedParameterPack())), 3021 Opc(opc), FPContractable(fpContractable), OpLoc(opLoc) { 3022 SubExprs[LHS] = lhs; 3023 SubExprs[RHS] = rhs; 3024 } 3025 3026 BinaryOperator(StmtClass SC, EmptyShell Empty) 3027 : Expr(SC, Empty), Opc(BO_MulAssign) { } 3028 }; 3029 3030 /// CompoundAssignOperator - For compound assignments (e.g. +=), we keep 3031 /// track of the type the operation is performed in. Due to the semantics of 3032 /// these operators, the operands are promoted, the arithmetic performed, an 3033 /// implicit conversion back to the result type done, then the assignment takes 3034 /// place. This captures the intermediate type which the computation is done 3035 /// in. 3036 class CompoundAssignOperator : public BinaryOperator { 3037 QualType ComputationLHSType; 3038 QualType ComputationResultType; 3039 public: 3040 CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResType, 3041 ExprValueKind VK, ExprObjectKind OK, 3042 QualType CompLHSType, QualType CompResultType, 3043 SourceLocation OpLoc, bool fpContractable) 3044 : BinaryOperator(lhs, rhs, opc, ResType, VK, OK, OpLoc, fpContractable, 3045 true), 3046 ComputationLHSType(CompLHSType), 3047 ComputationResultType(CompResultType) { 3048 assert(isCompoundAssignmentOp() && 3049 "Only should be used for compound assignments"); 3050 } 3051 3052 /// \brief Build an empty compound assignment operator expression. 3053 explicit CompoundAssignOperator(EmptyShell Empty) 3054 : BinaryOperator(CompoundAssignOperatorClass, Empty) { } 3055 3056 // The two computation types are the type the LHS is converted 3057 // to for the computation and the type of the result; the two are 3058 // distinct in a few cases (specifically, int+=ptr and ptr-=ptr). 3059 QualType getComputationLHSType() const { return ComputationLHSType; } 3060 void setComputationLHSType(QualType T) { ComputationLHSType = T; } 3061 3062 QualType getComputationResultType() const { return ComputationResultType; } 3063 void setComputationResultType(QualType T) { ComputationResultType = T; } 3064 3065 static bool classof(const Stmt *S) { 3066 return S->getStmtClass() == CompoundAssignOperatorClass; 3067 } 3068 }; 3069 3070 /// AbstractConditionalOperator - An abstract base class for 3071 /// ConditionalOperator and BinaryConditionalOperator. 3072 class AbstractConditionalOperator : public Expr { 3073 SourceLocation QuestionLoc, ColonLoc; 3074 friend class ASTStmtReader; 3075 3076 protected: 3077 AbstractConditionalOperator(StmtClass SC, QualType T, 3078 ExprValueKind VK, ExprObjectKind OK, 3079 bool TD, bool VD, bool ID, 3080 bool ContainsUnexpandedParameterPack, 3081 SourceLocation qloc, 3082 SourceLocation cloc) 3083 : Expr(SC, T, VK, OK, TD, VD, ID, ContainsUnexpandedParameterPack), 3084 QuestionLoc(qloc), ColonLoc(cloc) {} 3085 3086 AbstractConditionalOperator(StmtClass SC, EmptyShell Empty) 3087 : Expr(SC, Empty) { } 3088 3089 public: 3090 // getCond - Return the expression representing the condition for 3091 // the ?: operator. 3092 Expr *getCond() const; 3093 3094 // getTrueExpr - Return the subexpression representing the value of 3095 // the expression if the condition evaluates to true. 3096 Expr *getTrueExpr() const; 3097 3098 // getFalseExpr - Return the subexpression representing the value of 3099 // the expression if the condition evaluates to false. This is 3100 // the same as getRHS. 3101 Expr *getFalseExpr() const; 3102 3103 SourceLocation getQuestionLoc() const { return QuestionLoc; } 3104 SourceLocation getColonLoc() const { return ColonLoc; } 3105 3106 static bool classof(const Stmt *T) { 3107 return T->getStmtClass() == ConditionalOperatorClass || 3108 T->getStmtClass() == BinaryConditionalOperatorClass; 3109 } 3110 }; 3111 3112 /// ConditionalOperator - The ?: ternary operator. The GNU "missing 3113 /// middle" extension is a BinaryConditionalOperator. 3114 class ConditionalOperator : public AbstractConditionalOperator { 3115 enum { COND, LHS, RHS, END_EXPR }; 3116 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides. 3117 3118 friend class ASTStmtReader; 3119 public: 3120 ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs, 3121 SourceLocation CLoc, Expr *rhs, 3122 QualType t, ExprValueKind VK, ExprObjectKind OK) 3123 : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK, 3124 // FIXME: the type of the conditional operator doesn't 3125 // depend on the type of the conditional, but the standard 3126 // seems to imply that it could. File a bug! 3127 (lhs->isTypeDependent() || rhs->isTypeDependent()), 3128 (cond->isValueDependent() || lhs->isValueDependent() || 3129 rhs->isValueDependent()), 3130 (cond->isInstantiationDependent() || 3131 lhs->isInstantiationDependent() || 3132 rhs->isInstantiationDependent()), 3133 (cond->containsUnexpandedParameterPack() || 3134 lhs->containsUnexpandedParameterPack() || 3135 rhs->containsUnexpandedParameterPack()), 3136 QLoc, CLoc) { 3137 SubExprs[COND] = cond; 3138 SubExprs[LHS] = lhs; 3139 SubExprs[RHS] = rhs; 3140 } 3141 3142 /// \brief Build an empty conditional operator. 3143 explicit ConditionalOperator(EmptyShell Empty) 3144 : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { } 3145 3146 // getCond - Return the expression representing the condition for 3147 // the ?: operator. 3148 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); } 3149 3150 // getTrueExpr - Return the subexpression representing the value of 3151 // the expression if the condition evaluates to true. 3152 Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); } 3153 3154 // getFalseExpr - Return the subexpression representing the value of 3155 // the expression if the condition evaluates to false. This is 3156 // the same as getRHS. 3157 Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); } 3158 3159 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } 3160 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } 3161 3162 SourceLocation getLocStart() const LLVM_READONLY { 3163 return getCond()->getLocStart(); 3164 } 3165 SourceLocation getLocEnd() const LLVM_READONLY { 3166 return getRHS()->getLocEnd(); 3167 } 3168 3169 static bool classof(const Stmt *T) { 3170 return T->getStmtClass() == ConditionalOperatorClass; 3171 } 3172 3173 // Iterators 3174 child_range children() { 3175 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); 3176 } 3177 }; 3178 3179 /// BinaryConditionalOperator - The GNU extension to the conditional 3180 /// operator which allows the middle operand to be omitted. 3181 /// 3182 /// This is a different expression kind on the assumption that almost 3183 /// every client ends up needing to know that these are different. 3184 class BinaryConditionalOperator : public AbstractConditionalOperator { 3185 enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS }; 3186 3187 /// - the common condition/left-hand-side expression, which will be 3188 /// evaluated as the opaque value 3189 /// - the condition, expressed in terms of the opaque value 3190 /// - the left-hand-side, expressed in terms of the opaque value 3191 /// - the right-hand-side 3192 Stmt *SubExprs[NUM_SUBEXPRS]; 3193 OpaqueValueExpr *OpaqueValue; 3194 3195 friend class ASTStmtReader; 3196 public: 3197 BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue, 3198 Expr *cond, Expr *lhs, Expr *rhs, 3199 SourceLocation qloc, SourceLocation cloc, 3200 QualType t, ExprValueKind VK, ExprObjectKind OK) 3201 : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK, 3202 (common->isTypeDependent() || rhs->isTypeDependent()), 3203 (common->isValueDependent() || rhs->isValueDependent()), 3204 (common->isInstantiationDependent() || 3205 rhs->isInstantiationDependent()), 3206 (common->containsUnexpandedParameterPack() || 3207 rhs->containsUnexpandedParameterPack()), 3208 qloc, cloc), 3209 OpaqueValue(opaqueValue) { 3210 SubExprs[COMMON] = common; 3211 SubExprs[COND] = cond; 3212 SubExprs[LHS] = lhs; 3213 SubExprs[RHS] = rhs; 3214 assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value"); 3215 } 3216 3217 /// \brief Build an empty conditional operator. 3218 explicit BinaryConditionalOperator(EmptyShell Empty) 3219 : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { } 3220 3221 /// \brief getCommon - Return the common expression, written to the 3222 /// left of the condition. The opaque value will be bound to the 3223 /// result of this expression. 3224 Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); } 3225 3226 /// \brief getOpaqueValue - Return the opaque value placeholder. 3227 OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; } 3228 3229 /// \brief getCond - Return the condition expression; this is defined 3230 /// in terms of the opaque value. 3231 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); } 3232 3233 /// \brief getTrueExpr - Return the subexpression which will be 3234 /// evaluated if the condition evaluates to true; this is defined 3235 /// in terms of the opaque value. 3236 Expr *getTrueExpr() const { 3237 return cast<Expr>(SubExprs[LHS]); 3238 } 3239 3240 /// \brief getFalseExpr - Return the subexpression which will be 3241 /// evaluated if the condnition evaluates to false; this is 3242 /// defined in terms of the opaque value. 3243 Expr *getFalseExpr() const { 3244 return cast<Expr>(SubExprs[RHS]); 3245 } 3246 3247 SourceLocation getLocStart() const LLVM_READONLY { 3248 return getCommon()->getLocStart(); 3249 } 3250 SourceLocation getLocEnd() const LLVM_READONLY { 3251 return getFalseExpr()->getLocEnd(); 3252 } 3253 3254 static bool classof(const Stmt *T) { 3255 return T->getStmtClass() == BinaryConditionalOperatorClass; 3256 } 3257 3258 // Iterators 3259 child_range children() { 3260 return child_range(SubExprs, SubExprs + NUM_SUBEXPRS); 3261 } 3262 }; 3263 3264 inline Expr *AbstractConditionalOperator::getCond() const { 3265 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this)) 3266 return co->getCond(); 3267 return cast<BinaryConditionalOperator>(this)->getCond(); 3268 } 3269 3270 inline Expr *AbstractConditionalOperator::getTrueExpr() const { 3271 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this)) 3272 return co->getTrueExpr(); 3273 return cast<BinaryConditionalOperator>(this)->getTrueExpr(); 3274 } 3275 3276 inline Expr *AbstractConditionalOperator::getFalseExpr() const { 3277 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this)) 3278 return co->getFalseExpr(); 3279 return cast<BinaryConditionalOperator>(this)->getFalseExpr(); 3280 } 3281 3282 /// AddrLabelExpr - The GNU address of label extension, representing &&label. 3283 class AddrLabelExpr : public Expr { 3284 SourceLocation AmpAmpLoc, LabelLoc; 3285 LabelDecl *Label; 3286 public: 3287 AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L, 3288 QualType t) 3289 : Expr(AddrLabelExprClass, t, VK_RValue, OK_Ordinary, false, false, false, 3290 false), 3291 AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {} 3292 3293 /// \brief Build an empty address of a label expression. 3294 explicit AddrLabelExpr(EmptyShell Empty) 3295 : Expr(AddrLabelExprClass, Empty) { } 3296 3297 SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; } 3298 void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; } 3299 SourceLocation getLabelLoc() const { return LabelLoc; } 3300 void setLabelLoc(SourceLocation L) { LabelLoc = L; } 3301 3302 SourceLocation getLocStart() const LLVM_READONLY { return AmpAmpLoc; } 3303 SourceLocation getLocEnd() const LLVM_READONLY { return LabelLoc; } 3304 3305 LabelDecl *getLabel() const { return Label; } 3306 void setLabel(LabelDecl *L) { Label = L; } 3307 3308 static bool classof(const Stmt *T) { 3309 return T->getStmtClass() == AddrLabelExprClass; 3310 } 3311 3312 // Iterators 3313 child_range children() { return child_range(); } 3314 }; 3315 3316 /// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}). 3317 /// The StmtExpr contains a single CompoundStmt node, which it evaluates and 3318 /// takes the value of the last subexpression. 3319 /// 3320 /// A StmtExpr is always an r-value; values "returned" out of a 3321 /// StmtExpr will be copied. 3322 class StmtExpr : public Expr { 3323 Stmt *SubStmt; 3324 SourceLocation LParenLoc, RParenLoc; 3325 public: 3326 // FIXME: Does type-dependence need to be computed differently? 3327 // FIXME: Do we need to compute instantiation instantiation-dependence for 3328 // statements? (ugh!) 3329 StmtExpr(CompoundStmt *substmt, QualType T, 3330 SourceLocation lp, SourceLocation rp) : 3331 Expr(StmtExprClass, T, VK_RValue, OK_Ordinary, 3332 T->isDependentType(), false, false, false), 3333 SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { } 3334 3335 /// \brief Build an empty statement expression. 3336 explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { } 3337 3338 CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); } 3339 const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); } 3340 void setSubStmt(CompoundStmt *S) { SubStmt = S; } 3341 3342 SourceLocation getLocStart() const LLVM_READONLY { return LParenLoc; } 3343 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } 3344 3345 SourceLocation getLParenLoc() const { return LParenLoc; } 3346 void setLParenLoc(SourceLocation L) { LParenLoc = L; } 3347 SourceLocation getRParenLoc() const { return RParenLoc; } 3348 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 3349 3350 static bool classof(const Stmt *T) { 3351 return T->getStmtClass() == StmtExprClass; 3352 } 3353 3354 // Iterators 3355 child_range children() { return child_range(&SubStmt, &SubStmt+1); } 3356 }; 3357 3358 3359 /// ShuffleVectorExpr - clang-specific builtin-in function 3360 /// __builtin_shufflevector. 3361 /// This AST node represents a operator that does a constant 3362 /// shuffle, similar to LLVM's shufflevector instruction. It takes 3363 /// two vectors and a variable number of constant indices, 3364 /// and returns the appropriately shuffled vector. 3365 class ShuffleVectorExpr : public Expr { 3366 SourceLocation BuiltinLoc, RParenLoc; 3367 3368 // SubExprs - the list of values passed to the __builtin_shufflevector 3369 // function. The first two are vectors, and the rest are constant 3370 // indices. The number of values in this list is always 3371 // 2+the number of indices in the vector type. 3372 Stmt **SubExprs; 3373 unsigned NumExprs; 3374 3375 public: 3376 ShuffleVectorExpr(ASTContext &C, ArrayRef<Expr*> args, QualType Type, 3377 SourceLocation BLoc, SourceLocation RP); 3378 3379 /// \brief Build an empty vector-shuffle expression. 3380 explicit ShuffleVectorExpr(EmptyShell Empty) 3381 : Expr(ShuffleVectorExprClass, Empty), SubExprs(0) { } 3382 3383 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 3384 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; } 3385 3386 SourceLocation getRParenLoc() const { return RParenLoc; } 3387 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 3388 3389 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; } 3390 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } 3391 3392 static bool classof(const Stmt *T) { 3393 return T->getStmtClass() == ShuffleVectorExprClass; 3394 } 3395 3396 /// getNumSubExprs - Return the size of the SubExprs array. This includes the 3397 /// constant expression, the actual arguments passed in, and the function 3398 /// pointers. 3399 unsigned getNumSubExprs() const { return NumExprs; } 3400 3401 /// \brief Retrieve the array of expressions. 3402 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); } 3403 3404 /// getExpr - Return the Expr at the specified index. 3405 Expr *getExpr(unsigned Index) { 3406 assert((Index < NumExprs) && "Arg access out of range!"); 3407 return cast<Expr>(SubExprs[Index]); 3408 } 3409 const Expr *getExpr(unsigned Index) const { 3410 assert((Index < NumExprs) && "Arg access out of range!"); 3411 return cast<Expr>(SubExprs[Index]); 3412 } 3413 3414 void setExprs(ASTContext &C, Expr ** Exprs, unsigned NumExprs); 3415 3416 unsigned getShuffleMaskIdx(ASTContext &Ctx, unsigned N) const { 3417 assert((N < NumExprs - 2) && "Shuffle idx out of range!"); 3418 return getExpr(N+2)->EvaluateKnownConstInt(Ctx).getZExtValue(); 3419 } 3420 3421 // Iterators 3422 child_range children() { 3423 return child_range(&SubExprs[0], &SubExprs[0]+NumExprs); 3424 } 3425 }; 3426 3427 /// ChooseExpr - GNU builtin-in function __builtin_choose_expr. 3428 /// This AST node is similar to the conditional operator (?:) in C, with 3429 /// the following exceptions: 3430 /// - the test expression must be a integer constant expression. 3431 /// - the expression returned acts like the chosen subexpression in every 3432 /// visible way: the type is the same as that of the chosen subexpression, 3433 /// and all predicates (whether it's an l-value, whether it's an integer 3434 /// constant expression, etc.) return the same result as for the chosen 3435 /// sub-expression. 3436 class ChooseExpr : public Expr { 3437 enum { COND, LHS, RHS, END_EXPR }; 3438 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides. 3439 SourceLocation BuiltinLoc, RParenLoc; 3440 public: 3441 ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs, 3442 QualType t, ExprValueKind VK, ExprObjectKind OK, 3443 SourceLocation RP, bool TypeDependent, bool ValueDependent) 3444 : Expr(ChooseExprClass, t, VK, OK, TypeDependent, ValueDependent, 3445 (cond->isInstantiationDependent() || 3446 lhs->isInstantiationDependent() || 3447 rhs->isInstantiationDependent()), 3448 (cond->containsUnexpandedParameterPack() || 3449 lhs->containsUnexpandedParameterPack() || 3450 rhs->containsUnexpandedParameterPack())), 3451 BuiltinLoc(BLoc), RParenLoc(RP) { 3452 SubExprs[COND] = cond; 3453 SubExprs[LHS] = lhs; 3454 SubExprs[RHS] = rhs; 3455 } 3456 3457 /// \brief Build an empty __builtin_choose_expr. 3458 explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { } 3459 3460 /// isConditionTrue - Return whether the condition is true (i.e. not 3461 /// equal to zero). 3462 bool isConditionTrue(const ASTContext &C) const; 3463 3464 /// getChosenSubExpr - Return the subexpression chosen according to the 3465 /// condition. 3466 Expr *getChosenSubExpr(const ASTContext &C) const { 3467 return isConditionTrue(C) ? getLHS() : getRHS(); 3468 } 3469 3470 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); } 3471 void setCond(Expr *E) { SubExprs[COND] = E; } 3472 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } 3473 void setLHS(Expr *E) { SubExprs[LHS] = E; } 3474 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } 3475 void setRHS(Expr *E) { SubExprs[RHS] = E; } 3476 3477 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 3478 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; } 3479 3480 SourceLocation getRParenLoc() const { return RParenLoc; } 3481 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 3482 3483 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; } 3484 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } 3485 3486 static bool classof(const Stmt *T) { 3487 return T->getStmtClass() == ChooseExprClass; 3488 } 3489 3490 // Iterators 3491 child_range children() { 3492 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); 3493 } 3494 }; 3495 3496 /// GNUNullExpr - Implements the GNU __null extension, which is a name 3497 /// for a null pointer constant that has integral type (e.g., int or 3498 /// long) and is the same size and alignment as a pointer. The __null 3499 /// extension is typically only used by system headers, which define 3500 /// NULL as __null in C++ rather than using 0 (which is an integer 3501 /// that may not match the size of a pointer). 3502 class GNUNullExpr : public Expr { 3503 /// TokenLoc - The location of the __null keyword. 3504 SourceLocation TokenLoc; 3505 3506 public: 3507 GNUNullExpr(QualType Ty, SourceLocation Loc) 3508 : Expr(GNUNullExprClass, Ty, VK_RValue, OK_Ordinary, false, false, false, 3509 false), 3510 TokenLoc(Loc) { } 3511 3512 /// \brief Build an empty GNU __null expression. 3513 explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { } 3514 3515 /// getTokenLocation - The location of the __null token. 3516 SourceLocation getTokenLocation() const { return TokenLoc; } 3517 void setTokenLocation(SourceLocation L) { TokenLoc = L; } 3518 3519 SourceLocation getLocStart() const LLVM_READONLY { return TokenLoc; } 3520 SourceLocation getLocEnd() const LLVM_READONLY { return TokenLoc; } 3521 3522 static bool classof(const Stmt *T) { 3523 return T->getStmtClass() == GNUNullExprClass; 3524 } 3525 3526 // Iterators 3527 child_range children() { return child_range(); } 3528 }; 3529 3530 /// VAArgExpr, used for the builtin function __builtin_va_arg. 3531 class VAArgExpr : public Expr { 3532 Stmt *Val; 3533 TypeSourceInfo *TInfo; 3534 SourceLocation BuiltinLoc, RParenLoc; 3535 public: 3536 VAArgExpr(SourceLocation BLoc, Expr* e, TypeSourceInfo *TInfo, 3537 SourceLocation RPLoc, QualType t) 3538 : Expr(VAArgExprClass, t, VK_RValue, OK_Ordinary, 3539 t->isDependentType(), false, 3540 (TInfo->getType()->isInstantiationDependentType() || 3541 e->isInstantiationDependent()), 3542 (TInfo->getType()->containsUnexpandedParameterPack() || 3543 e->containsUnexpandedParameterPack())), 3544 Val(e), TInfo(TInfo), 3545 BuiltinLoc(BLoc), 3546 RParenLoc(RPLoc) { } 3547 3548 /// \brief Create an empty __builtin_va_arg expression. 3549 explicit VAArgExpr(EmptyShell Empty) : Expr(VAArgExprClass, Empty) { } 3550 3551 const Expr *getSubExpr() const { return cast<Expr>(Val); } 3552 Expr *getSubExpr() { return cast<Expr>(Val); } 3553 void setSubExpr(Expr *E) { Val = E; } 3554 3555 TypeSourceInfo *getWrittenTypeInfo() const { return TInfo; } 3556 void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo = TI; } 3557 3558 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 3559 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; } 3560 3561 SourceLocation getRParenLoc() const { return RParenLoc; } 3562 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 3563 3564 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; } 3565 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } 3566 3567 static bool classof(const Stmt *T) { 3568 return T->getStmtClass() == VAArgExprClass; 3569 } 3570 3571 // Iterators 3572 child_range children() { return child_range(&Val, &Val+1); } 3573 }; 3574 3575 /// @brief Describes an C or C++ initializer list. 3576 /// 3577 /// InitListExpr describes an initializer list, which can be used to 3578 /// initialize objects of different types, including 3579 /// struct/class/union types, arrays, and vectors. For example: 3580 /// 3581 /// @code 3582 /// struct foo x = { 1, { 2, 3 } }; 3583 /// @endcode 3584 /// 3585 /// Prior to semantic analysis, an initializer list will represent the 3586 /// initializer list as written by the user, but will have the 3587 /// placeholder type "void". This initializer list is called the 3588 /// syntactic form of the initializer, and may contain C99 designated 3589 /// initializers (represented as DesignatedInitExprs), initializations 3590 /// of subobject members without explicit braces, and so on. Clients 3591 /// interested in the original syntax of the initializer list should 3592 /// use the syntactic form of the initializer list. 3593 /// 3594 /// After semantic analysis, the initializer list will represent the 3595 /// semantic form of the initializer, where the initializations of all 3596 /// subobjects are made explicit with nested InitListExpr nodes and 3597 /// C99 designators have been eliminated by placing the designated 3598 /// initializations into the subobject they initialize. Additionally, 3599 /// any "holes" in the initialization, where no initializer has been 3600 /// specified for a particular subobject, will be replaced with 3601 /// implicitly-generated ImplicitValueInitExpr expressions that 3602 /// value-initialize the subobjects. Note, however, that the 3603 /// initializer lists may still have fewer initializers than there are 3604 /// elements to initialize within the object. 3605 /// 3606 /// After semantic analysis has completed, given an initializer list, 3607 /// method isSemanticForm() returns true if and only if this is the 3608 /// semantic form of the initializer list (note: the same AST node 3609 /// may at the same time be the syntactic form). 3610 /// Given the semantic form of the initializer list, one can retrieve 3611 /// the syntactic form of that initializer list (when different) 3612 /// using method getSyntacticForm(); the method returns null if applied 3613 /// to a initializer list which is already in syntactic form. 3614 /// Similarly, given the syntactic form (i.e., an initializer list such 3615 /// that isSemanticForm() returns false), one can retrieve the semantic 3616 /// form using method getSemanticForm(). 3617 /// Since many initializer lists have the same syntactic and semantic forms, 3618 /// getSyntacticForm() may return NULL, indicating that the current 3619 /// semantic initializer list also serves as its syntactic form. 3620 class InitListExpr : public Expr { 3621 // FIXME: Eliminate this vector in favor of ASTContext allocation 3622 typedef ASTVector<Stmt *> InitExprsTy; 3623 InitExprsTy InitExprs; 3624 SourceLocation LBraceLoc, RBraceLoc; 3625 3626 /// The alternative form of the initializer list (if it exists). 3627 /// The int part of the pair stores whether this initalizer list is 3628 /// in semantic form. If not null, the pointer points to: 3629 /// - the syntactic form, if this is in semantic form; 3630 /// - the semantic form, if this is in syntactic form. 3631 llvm::PointerIntPair<InitListExpr *, 1, bool> AltForm; 3632 3633 /// \brief Either: 3634 /// If this initializer list initializes an array with more elements than 3635 /// there are initializers in the list, specifies an expression to be used 3636 /// for value initialization of the rest of the elements. 3637 /// Or 3638 /// If this initializer list initializes a union, specifies which 3639 /// field within the union will be initialized. 3640 llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit; 3641 3642 public: 3643 InitListExpr(ASTContext &C, SourceLocation lbraceloc, 3644 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc); 3645 3646 /// \brief Build an empty initializer list. 3647 explicit InitListExpr(EmptyShell Empty) 3648 : Expr(InitListExprClass, Empty) { } 3649 3650 unsigned getNumInits() const { return InitExprs.size(); } 3651 3652 /// \brief Retrieve the set of initializers. 3653 Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); } 3654 3655 const Expr *getInit(unsigned Init) const { 3656 assert(Init < getNumInits() && "Initializer access out of range!"); 3657 return cast_or_null<Expr>(InitExprs[Init]); 3658 } 3659 3660 Expr *getInit(unsigned Init) { 3661 assert(Init < getNumInits() && "Initializer access out of range!"); 3662 return cast_or_null<Expr>(InitExprs[Init]); 3663 } 3664 3665 void setInit(unsigned Init, Expr *expr) { 3666 assert(Init < getNumInits() && "Initializer access out of range!"); 3667 InitExprs[Init] = expr; 3668 } 3669 3670 /// \brief Reserve space for some number of initializers. 3671 void reserveInits(ASTContext &C, unsigned NumInits); 3672 3673 /// @brief Specify the number of initializers 3674 /// 3675 /// If there are more than @p NumInits initializers, the remaining 3676 /// initializers will be destroyed. If there are fewer than @p 3677 /// NumInits initializers, NULL expressions will be added for the 3678 /// unknown initializers. 3679 void resizeInits(ASTContext &Context, unsigned NumInits); 3680 3681 /// @brief Updates the initializer at index @p Init with the new 3682 /// expression @p expr, and returns the old expression at that 3683 /// location. 3684 /// 3685 /// When @p Init is out of range for this initializer list, the 3686 /// initializer list will be extended with NULL expressions to 3687 /// accommodate the new entry. 3688 Expr *updateInit(ASTContext &C, unsigned Init, Expr *expr); 3689 3690 /// \brief If this initializer list initializes an array with more elements 3691 /// than there are initializers in the list, specifies an expression to be 3692 /// used for value initialization of the rest of the elements. 3693 Expr *getArrayFiller() { 3694 return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>(); 3695 } 3696 const Expr *getArrayFiller() const { 3697 return const_cast<InitListExpr *>(this)->getArrayFiller(); 3698 } 3699 void setArrayFiller(Expr *filler); 3700 3701 /// \brief Return true if this is an array initializer and its array "filler" 3702 /// has been set. 3703 bool hasArrayFiller() const { return getArrayFiller(); } 3704 3705 /// \brief If this initializes a union, specifies which field in the 3706 /// union to initialize. 3707 /// 3708 /// Typically, this field is the first named field within the 3709 /// union. However, a designated initializer can specify the 3710 /// initialization of a different field within the union. 3711 FieldDecl *getInitializedFieldInUnion() { 3712 return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>(); 3713 } 3714 const FieldDecl *getInitializedFieldInUnion() const { 3715 return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion(); 3716 } 3717 void setInitializedFieldInUnion(FieldDecl *FD) { 3718 ArrayFillerOrUnionFieldInit = FD; 3719 } 3720 3721 // Explicit InitListExpr's originate from source code (and have valid source 3722 // locations). Implicit InitListExpr's are created by the semantic analyzer. 3723 bool isExplicit() { 3724 return LBraceLoc.isValid() && RBraceLoc.isValid(); 3725 } 3726 3727 // Is this an initializer for an array of characters, initialized by a string 3728 // literal or an @encode? 3729 bool isStringLiteralInit() const; 3730 3731 SourceLocation getLBraceLoc() const { return LBraceLoc; } 3732 void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; } 3733 SourceLocation getRBraceLoc() const { return RBraceLoc; } 3734 void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; } 3735 3736 bool isSemanticForm() const { return AltForm.getInt(); } 3737 InitListExpr *getSemanticForm() const { 3738 return isSemanticForm() ? 0 : AltForm.getPointer(); 3739 } 3740 InitListExpr *getSyntacticForm() const { 3741 return isSemanticForm() ? AltForm.getPointer() : 0; 3742 } 3743 3744 void setSyntacticForm(InitListExpr *Init) { 3745 AltForm.setPointer(Init); 3746 AltForm.setInt(true); 3747 Init->AltForm.setPointer(this); 3748 Init->AltForm.setInt(false); 3749 } 3750 3751 bool hadArrayRangeDesignator() const { 3752 return InitListExprBits.HadArrayRangeDesignator != 0; 3753 } 3754 void sawArrayRangeDesignator(bool ARD = true) { 3755 InitListExprBits.HadArrayRangeDesignator = ARD; 3756 } 3757 3758 bool initializesStdInitializerList() const { 3759 return InitListExprBits.InitializesStdInitializerList != 0; 3760 } 3761 void setInitializesStdInitializerList(bool ISIL = true) { 3762 InitListExprBits.InitializesStdInitializerList = ISIL; 3763 } 3764 3765 SourceLocation getLocStart() const LLVM_READONLY; 3766 SourceLocation getLocEnd() const LLVM_READONLY; 3767 3768 static bool classof(const Stmt *T) { 3769 return T->getStmtClass() == InitListExprClass; 3770 } 3771 3772 // Iterators 3773 child_range children() { 3774 if (InitExprs.empty()) return child_range(); 3775 return child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size()); 3776 } 3777 3778 typedef InitExprsTy::iterator iterator; 3779 typedef InitExprsTy::const_iterator const_iterator; 3780 typedef InitExprsTy::reverse_iterator reverse_iterator; 3781 typedef InitExprsTy::const_reverse_iterator const_reverse_iterator; 3782 3783 iterator begin() { return InitExprs.begin(); } 3784 const_iterator begin() const { return InitExprs.begin(); } 3785 iterator end() { return InitExprs.end(); } 3786 const_iterator end() const { return InitExprs.end(); } 3787 reverse_iterator rbegin() { return InitExprs.rbegin(); } 3788 const_reverse_iterator rbegin() const { return InitExprs.rbegin(); } 3789 reverse_iterator rend() { return InitExprs.rend(); } 3790 const_reverse_iterator rend() const { return InitExprs.rend(); } 3791 3792 friend class ASTStmtReader; 3793 friend class ASTStmtWriter; 3794 }; 3795 3796 /// @brief Represents a C99 designated initializer expression. 3797 /// 3798 /// A designated initializer expression (C99 6.7.8) contains one or 3799 /// more designators (which can be field designators, array 3800 /// designators, or GNU array-range designators) followed by an 3801 /// expression that initializes the field or element(s) that the 3802 /// designators refer to. For example, given: 3803 /// 3804 /// @code 3805 /// struct point { 3806 /// double x; 3807 /// double y; 3808 /// }; 3809 /// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 }; 3810 /// @endcode 3811 /// 3812 /// The InitListExpr contains three DesignatedInitExprs, the first of 3813 /// which covers @c [2].y=1.0. This DesignatedInitExpr will have two 3814 /// designators, one array designator for @c [2] followed by one field 3815 /// designator for @c .y. The initalization expression will be 1.0. 3816 class DesignatedInitExpr : public Expr { 3817 public: 3818 /// \brief Forward declaration of the Designator class. 3819 class Designator; 3820 3821 private: 3822 /// The location of the '=' or ':' prior to the actual initializer 3823 /// expression. 3824 SourceLocation EqualOrColonLoc; 3825 3826 /// Whether this designated initializer used the GNU deprecated 3827 /// syntax rather than the C99 '=' syntax. 3828 bool GNUSyntax : 1; 3829 3830 /// The number of designators in this initializer expression. 3831 unsigned NumDesignators : 15; 3832 3833 /// The number of subexpressions of this initializer expression, 3834 /// which contains both the initializer and any additional 3835 /// expressions used by array and array-range designators. 3836 unsigned NumSubExprs : 16; 3837 3838 /// \brief The designators in this designated initialization 3839 /// expression. 3840 Designator *Designators; 3841 3842 3843 DesignatedInitExpr(ASTContext &C, QualType Ty, unsigned NumDesignators, 3844 const Designator *Designators, 3845 SourceLocation EqualOrColonLoc, bool GNUSyntax, 3846 ArrayRef<Expr*> IndexExprs, Expr *Init); 3847 3848 explicit DesignatedInitExpr(unsigned NumSubExprs) 3849 : Expr(DesignatedInitExprClass, EmptyShell()), 3850 NumDesignators(0), NumSubExprs(NumSubExprs), Designators(0) { } 3851 3852 public: 3853 /// A field designator, e.g., ".x". 3854 struct FieldDesignator { 3855 /// Refers to the field that is being initialized. The low bit 3856 /// of this field determines whether this is actually a pointer 3857 /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When 3858 /// initially constructed, a field designator will store an 3859 /// IdentifierInfo*. After semantic analysis has resolved that 3860 /// name, the field designator will instead store a FieldDecl*. 3861 uintptr_t NameOrField; 3862 3863 /// The location of the '.' in the designated initializer. 3864 unsigned DotLoc; 3865 3866 /// The location of the field name in the designated initializer. 3867 unsigned FieldLoc; 3868 }; 3869 3870 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]". 3871 struct ArrayOrRangeDesignator { 3872 /// Location of the first index expression within the designated 3873 /// initializer expression's list of subexpressions. 3874 unsigned Index; 3875 /// The location of the '[' starting the array range designator. 3876 unsigned LBracketLoc; 3877 /// The location of the ellipsis separating the start and end 3878 /// indices. Only valid for GNU array-range designators. 3879 unsigned EllipsisLoc; 3880 /// The location of the ']' terminating the array range designator. 3881 unsigned RBracketLoc; 3882 }; 3883 3884 /// @brief Represents a single C99 designator. 3885 /// 3886 /// @todo This class is infuriatingly similar to clang::Designator, 3887 /// but minor differences (storing indices vs. storing pointers) 3888 /// keep us from reusing it. Try harder, later, to rectify these 3889 /// differences. 3890 class Designator { 3891 /// @brief The kind of designator this describes. 3892 enum { 3893 FieldDesignator, 3894 ArrayDesignator, 3895 ArrayRangeDesignator 3896 } Kind; 3897 3898 union { 3899 /// A field designator, e.g., ".x". 3900 struct FieldDesignator Field; 3901 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]". 3902 struct ArrayOrRangeDesignator ArrayOrRange; 3903 }; 3904 friend class DesignatedInitExpr; 3905 3906 public: 3907 Designator() {} 3908 3909 /// @brief Initializes a field designator. 3910 Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc, 3911 SourceLocation FieldLoc) 3912 : Kind(FieldDesignator) { 3913 Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01; 3914 Field.DotLoc = DotLoc.getRawEncoding(); 3915 Field.FieldLoc = FieldLoc.getRawEncoding(); 3916 } 3917 3918 /// @brief Initializes an array designator. 3919 Designator(unsigned Index, SourceLocation LBracketLoc, 3920 SourceLocation RBracketLoc) 3921 : Kind(ArrayDesignator) { 3922 ArrayOrRange.Index = Index; 3923 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding(); 3924 ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding(); 3925 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding(); 3926 } 3927 3928 /// @brief Initializes a GNU array-range designator. 3929 Designator(unsigned Index, SourceLocation LBracketLoc, 3930 SourceLocation EllipsisLoc, SourceLocation RBracketLoc) 3931 : Kind(ArrayRangeDesignator) { 3932 ArrayOrRange.Index = Index; 3933 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding(); 3934 ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding(); 3935 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding(); 3936 } 3937 3938 bool isFieldDesignator() const { return Kind == FieldDesignator; } 3939 bool isArrayDesignator() const { return Kind == ArrayDesignator; } 3940 bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; } 3941 3942 IdentifierInfo *getFieldName() const; 3943 3944 FieldDecl *getField() const { 3945 assert(Kind == FieldDesignator && "Only valid on a field designator"); 3946 if (Field.NameOrField & 0x01) 3947 return 0; 3948 else 3949 return reinterpret_cast<FieldDecl *>(Field.NameOrField); 3950 } 3951 3952 void setField(FieldDecl *FD) { 3953 assert(Kind == FieldDesignator && "Only valid on a field designator"); 3954 Field.NameOrField = reinterpret_cast<uintptr_t>(FD); 3955 } 3956 3957 SourceLocation getDotLoc() const { 3958 assert(Kind == FieldDesignator && "Only valid on a field designator"); 3959 return SourceLocation::getFromRawEncoding(Field.DotLoc); 3960 } 3961 3962 SourceLocation getFieldLoc() const { 3963 assert(Kind == FieldDesignator && "Only valid on a field designator"); 3964 return SourceLocation::getFromRawEncoding(Field.FieldLoc); 3965 } 3966 3967 SourceLocation getLBracketLoc() const { 3968 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && 3969 "Only valid on an array or array-range designator"); 3970 return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc); 3971 } 3972 3973 SourceLocation getRBracketLoc() const { 3974 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && 3975 "Only valid on an array or array-range designator"); 3976 return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc); 3977 } 3978 3979 SourceLocation getEllipsisLoc() const { 3980 assert(Kind == ArrayRangeDesignator && 3981 "Only valid on an array-range designator"); 3982 return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc); 3983 } 3984 3985 unsigned getFirstExprIndex() const { 3986 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && 3987 "Only valid on an array or array-range designator"); 3988 return ArrayOrRange.Index; 3989 } 3990 3991 SourceLocation getLocStart() const LLVM_READONLY { 3992 if (Kind == FieldDesignator) 3993 return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc(); 3994 else 3995 return getLBracketLoc(); 3996 } 3997 SourceLocation getLocEnd() const LLVM_READONLY { 3998 return Kind == FieldDesignator ? getFieldLoc() : getRBracketLoc(); 3999 } 4000 SourceRange getSourceRange() const LLVM_READONLY { 4001 return SourceRange(getLocStart(), getLocEnd()); 4002 } 4003 }; 4004 4005 static DesignatedInitExpr *Create(ASTContext &C, Designator *Designators, 4006 unsigned NumDesignators, 4007 ArrayRef<Expr*> IndexExprs, 4008 SourceLocation EqualOrColonLoc, 4009 bool GNUSyntax, Expr *Init); 4010 4011 static DesignatedInitExpr *CreateEmpty(ASTContext &C, unsigned NumIndexExprs); 4012 4013 /// @brief Returns the number of designators in this initializer. 4014 unsigned size() const { return NumDesignators; } 4015 4016 // Iterator access to the designators. 4017 typedef Designator *designators_iterator; 4018 designators_iterator designators_begin() { return Designators; } 4019 designators_iterator designators_end() { 4020 return Designators + NumDesignators; 4021 } 4022 4023 typedef const Designator *const_designators_iterator; 4024 const_designators_iterator designators_begin() const { return Designators; } 4025 const_designators_iterator designators_end() const { 4026 return Designators + NumDesignators; 4027 } 4028 4029 typedef std::reverse_iterator<designators_iterator> 4030 reverse_designators_iterator; 4031 reverse_designators_iterator designators_rbegin() { 4032 return reverse_designators_iterator(designators_end()); 4033 } 4034 reverse_designators_iterator designators_rend() { 4035 return reverse_designators_iterator(designators_begin()); 4036 } 4037 4038 typedef std::reverse_iterator<const_designators_iterator> 4039 const_reverse_designators_iterator; 4040 const_reverse_designators_iterator designators_rbegin() const { 4041 return const_reverse_designators_iterator(designators_end()); 4042 } 4043 const_reverse_designators_iterator designators_rend() const { 4044 return const_reverse_designators_iterator(designators_begin()); 4045 } 4046 4047 Designator *getDesignator(unsigned Idx) { return &designators_begin()[Idx]; } 4048 4049 void setDesignators(ASTContext &C, const Designator *Desigs, 4050 unsigned NumDesigs); 4051 4052 Expr *getArrayIndex(const Designator &D) const; 4053 Expr *getArrayRangeStart(const Designator &D) const; 4054 Expr *getArrayRangeEnd(const Designator &D) const; 4055 4056 /// @brief Retrieve the location of the '=' that precedes the 4057 /// initializer value itself, if present. 4058 SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; } 4059 void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; } 4060 4061 /// @brief Determines whether this designated initializer used the 4062 /// deprecated GNU syntax for designated initializers. 4063 bool usesGNUSyntax() const { return GNUSyntax; } 4064 void setGNUSyntax(bool GNU) { GNUSyntax = GNU; } 4065 4066 /// @brief Retrieve the initializer value. 4067 Expr *getInit() const { 4068 return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin()); 4069 } 4070 4071 void setInit(Expr *init) { 4072 *child_begin() = init; 4073 } 4074 4075 /// \brief Retrieve the total number of subexpressions in this 4076 /// designated initializer expression, including the actual 4077 /// initialized value and any expressions that occur within array 4078 /// and array-range designators. 4079 unsigned getNumSubExprs() const { return NumSubExprs; } 4080 4081 Expr *getSubExpr(unsigned Idx) { 4082 assert(Idx < NumSubExprs && "Subscript out of range"); 4083 char* Ptr = static_cast<char*>(static_cast<void *>(this)); 4084 Ptr += sizeof(DesignatedInitExpr); 4085 return reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx]; 4086 } 4087 4088 void setSubExpr(unsigned Idx, Expr *E) { 4089 assert(Idx < NumSubExprs && "Subscript out of range"); 4090 char* Ptr = static_cast<char*>(static_cast<void *>(this)); 4091 Ptr += sizeof(DesignatedInitExpr); 4092 reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx] = E; 4093 } 4094 4095 /// \brief Replaces the designator at index @p Idx with the series 4096 /// of designators in [First, Last). 4097 void ExpandDesignator(ASTContext &C, unsigned Idx, const Designator *First, 4098 const Designator *Last); 4099 4100 SourceRange getDesignatorsSourceRange() const; 4101 4102 SourceLocation getLocStart() const LLVM_READONLY; 4103 SourceLocation getLocEnd() const LLVM_READONLY; 4104 4105 static bool classof(const Stmt *T) { 4106 return T->getStmtClass() == DesignatedInitExprClass; 4107 } 4108 4109 // Iterators 4110 child_range children() { 4111 Stmt **begin = reinterpret_cast<Stmt**>(this + 1); 4112 return child_range(begin, begin + NumSubExprs); 4113 } 4114 }; 4115 4116 /// \brief Represents an implicitly-generated value initialization of 4117 /// an object of a given type. 4118 /// 4119 /// Implicit value initializations occur within semantic initializer 4120 /// list expressions (InitListExpr) as placeholders for subobject 4121 /// initializations not explicitly specified by the user. 4122 /// 4123 /// \see InitListExpr 4124 class ImplicitValueInitExpr : public Expr { 4125 public: 4126 explicit ImplicitValueInitExpr(QualType ty) 4127 : Expr(ImplicitValueInitExprClass, ty, VK_RValue, OK_Ordinary, 4128 false, false, ty->isInstantiationDependentType(), false) { } 4129 4130 /// \brief Construct an empty implicit value initialization. 4131 explicit ImplicitValueInitExpr(EmptyShell Empty) 4132 : Expr(ImplicitValueInitExprClass, Empty) { } 4133 4134 static bool classof(const Stmt *T) { 4135 return T->getStmtClass() == ImplicitValueInitExprClass; 4136 } 4137 4138 SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); } 4139 SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); } 4140 4141 // Iterators 4142 child_range children() { return child_range(); } 4143 }; 4144 4145 4146 class ParenListExpr : public Expr { 4147 Stmt **Exprs; 4148 unsigned NumExprs; 4149 SourceLocation LParenLoc, RParenLoc; 4150 4151 public: 4152 ParenListExpr(ASTContext& C, SourceLocation lparenloc, ArrayRef<Expr*> exprs, 4153 SourceLocation rparenloc); 4154 4155 /// \brief Build an empty paren list. 4156 explicit ParenListExpr(EmptyShell Empty) : Expr(ParenListExprClass, Empty) { } 4157 4158 unsigned getNumExprs() const { return NumExprs; } 4159 4160 const Expr* getExpr(unsigned Init) const { 4161 assert(Init < getNumExprs() && "Initializer access out of range!"); 4162 return cast_or_null<Expr>(Exprs[Init]); 4163 } 4164 4165 Expr* getExpr(unsigned Init) { 4166 assert(Init < getNumExprs() && "Initializer access out of range!"); 4167 return cast_or_null<Expr>(Exprs[Init]); 4168 } 4169 4170 Expr **getExprs() { return reinterpret_cast<Expr **>(Exprs); } 4171 4172 SourceLocation getLParenLoc() const { return LParenLoc; } 4173 SourceLocation getRParenLoc() const { return RParenLoc; } 4174 4175 SourceLocation getLocStart() const LLVM_READONLY { return LParenLoc; } 4176 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } 4177 4178 static bool classof(const Stmt *T) { 4179 return T->getStmtClass() == ParenListExprClass; 4180 } 4181 4182 // Iterators 4183 child_range children() { 4184 return child_range(&Exprs[0], &Exprs[0]+NumExprs); 4185 } 4186 4187 friend class ASTStmtReader; 4188 friend class ASTStmtWriter; 4189 }; 4190 4191 4192 /// \brief Represents a C11 generic selection. 4193 /// 4194 /// A generic selection (C11 6.5.1.1) contains an unevaluated controlling 4195 /// expression, followed by one or more generic associations. Each generic 4196 /// association specifies a type name and an expression, or "default" and an 4197 /// expression (in which case it is known as a default generic association). 4198 /// The type and value of the generic selection are identical to those of its 4199 /// result expression, which is defined as the expression in the generic 4200 /// association with a type name that is compatible with the type of the 4201 /// controlling expression, or the expression in the default generic association 4202 /// if no types are compatible. For example: 4203 /// 4204 /// @code 4205 /// _Generic(X, double: 1, float: 2, default: 3) 4206 /// @endcode 4207 /// 4208 /// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f 4209 /// or 3 if "hello". 4210 /// 4211 /// As an extension, generic selections are allowed in C++, where the following 4212 /// additional semantics apply: 4213 /// 4214 /// Any generic selection whose controlling expression is type-dependent or 4215 /// which names a dependent type in its association list is result-dependent, 4216 /// which means that the choice of result expression is dependent. 4217 /// Result-dependent generic associations are both type- and value-dependent. 4218 class GenericSelectionExpr : public Expr { 4219 enum { CONTROLLING, END_EXPR }; 4220 TypeSourceInfo **AssocTypes; 4221 Stmt **SubExprs; 4222 unsigned NumAssocs, ResultIndex; 4223 SourceLocation GenericLoc, DefaultLoc, RParenLoc; 4224 4225 public: 4226 GenericSelectionExpr(ASTContext &Context, 4227 SourceLocation GenericLoc, Expr *ControllingExpr, 4228 ArrayRef<TypeSourceInfo*> AssocTypes, 4229 ArrayRef<Expr*> AssocExprs, 4230 SourceLocation DefaultLoc, SourceLocation RParenLoc, 4231 bool ContainsUnexpandedParameterPack, 4232 unsigned ResultIndex); 4233 4234 /// This constructor is used in the result-dependent case. 4235 GenericSelectionExpr(ASTContext &Context, 4236 SourceLocation GenericLoc, Expr *ControllingExpr, 4237 ArrayRef<TypeSourceInfo*> AssocTypes, 4238 ArrayRef<Expr*> AssocExprs, 4239 SourceLocation DefaultLoc, SourceLocation RParenLoc, 4240 bool ContainsUnexpandedParameterPack); 4241 4242 explicit GenericSelectionExpr(EmptyShell Empty) 4243 : Expr(GenericSelectionExprClass, Empty) { } 4244 4245 unsigned getNumAssocs() const { return NumAssocs; } 4246 4247 SourceLocation getGenericLoc() const { return GenericLoc; } 4248 SourceLocation getDefaultLoc() const { return DefaultLoc; } 4249 SourceLocation getRParenLoc() const { return RParenLoc; } 4250 4251 const Expr *getAssocExpr(unsigned i) const { 4252 return cast<Expr>(SubExprs[END_EXPR+i]); 4253 } 4254 Expr *getAssocExpr(unsigned i) { return cast<Expr>(SubExprs[END_EXPR+i]); } 4255 4256 const TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) const { 4257 return AssocTypes[i]; 4258 } 4259 TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) { return AssocTypes[i]; } 4260 4261 QualType getAssocType(unsigned i) const { 4262 if (const TypeSourceInfo *TS = getAssocTypeSourceInfo(i)) 4263 return TS->getType(); 4264 else 4265 return QualType(); 4266 } 4267 4268 const Expr *getControllingExpr() const { 4269 return cast<Expr>(SubExprs[CONTROLLING]); 4270 } 4271 Expr *getControllingExpr() { return cast<Expr>(SubExprs[CONTROLLING]); } 4272 4273 /// Whether this generic selection is result-dependent. 4274 bool isResultDependent() const { return ResultIndex == -1U; } 4275 4276 /// The zero-based index of the result expression's generic association in 4277 /// the generic selection's association list. Defined only if the 4278 /// generic selection is not result-dependent. 4279 unsigned getResultIndex() const { 4280 assert(!isResultDependent() && "Generic selection is result-dependent"); 4281 return ResultIndex; 4282 } 4283 4284 /// The generic selection's result expression. Defined only if the 4285 /// generic selection is not result-dependent. 4286 const Expr *getResultExpr() const { return getAssocExpr(getResultIndex()); } 4287 Expr *getResultExpr() { return getAssocExpr(getResultIndex()); } 4288 4289 SourceLocation getLocStart() const LLVM_READONLY { return GenericLoc; } 4290 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } 4291 4292 static bool classof(const Stmt *T) { 4293 return T->getStmtClass() == GenericSelectionExprClass; 4294 } 4295 4296 child_range children() { 4297 return child_range(SubExprs, SubExprs+END_EXPR+NumAssocs); 4298 } 4299 4300 friend class ASTStmtReader; 4301 }; 4302 4303 //===----------------------------------------------------------------------===// 4304 // Clang Extensions 4305 //===----------------------------------------------------------------------===// 4306 4307 4308 /// ExtVectorElementExpr - This represents access to specific elements of a 4309 /// vector, and may occur on the left hand side or right hand side. For example 4310 /// the following is legal: "V.xy = V.zw" if V is a 4 element extended vector. 4311 /// 4312 /// Note that the base may have either vector or pointer to vector type, just 4313 /// like a struct field reference. 4314 /// 4315 class ExtVectorElementExpr : public Expr { 4316 Stmt *Base; 4317 IdentifierInfo *Accessor; 4318 SourceLocation AccessorLoc; 4319 public: 4320 ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base, 4321 IdentifierInfo &accessor, SourceLocation loc) 4322 : Expr(ExtVectorElementExprClass, ty, VK, 4323 (VK == VK_RValue ? OK_Ordinary : OK_VectorComponent), 4324 base->isTypeDependent(), base->isValueDependent(), 4325 base->isInstantiationDependent(), 4326 base->containsUnexpandedParameterPack()), 4327 Base(base), Accessor(&accessor), AccessorLoc(loc) {} 4328 4329 /// \brief Build an empty vector element expression. 4330 explicit ExtVectorElementExpr(EmptyShell Empty) 4331 : Expr(ExtVectorElementExprClass, Empty) { } 4332 4333 const Expr *getBase() const { return cast<Expr>(Base); } 4334 Expr *getBase() { return cast<Expr>(Base); } 4335 void setBase(Expr *E) { Base = E; } 4336 4337 IdentifierInfo &getAccessor() const { return *Accessor; } 4338 void setAccessor(IdentifierInfo *II) { Accessor = II; } 4339 4340 SourceLocation getAccessorLoc() const { return AccessorLoc; } 4341 void setAccessorLoc(SourceLocation L) { AccessorLoc = L; } 4342 4343 /// getNumElements - Get the number of components being selected. 4344 unsigned getNumElements() const; 4345 4346 /// containsDuplicateElements - Return true if any element access is 4347 /// repeated. 4348 bool containsDuplicateElements() const; 4349 4350 /// getEncodedElementAccess - Encode the elements accessed into an llvm 4351 /// aggregate Constant of ConstantInt(s). 4352 void getEncodedElementAccess(SmallVectorImpl<unsigned> &Elts) const; 4353 4354 SourceLocation getLocStart() const LLVM_READONLY { 4355 return getBase()->getLocStart(); 4356 } 4357 SourceLocation getLocEnd() const LLVM_READONLY { return AccessorLoc; } 4358 4359 /// isArrow - Return true if the base expression is a pointer to vector, 4360 /// return false if the base expression is a vector. 4361 bool isArrow() const; 4362 4363 static bool classof(const Stmt *T) { 4364 return T->getStmtClass() == ExtVectorElementExprClass; 4365 } 4366 4367 // Iterators 4368 child_range children() { return child_range(&Base, &Base+1); } 4369 }; 4370 4371 4372 /// BlockExpr - Adaptor class for mixing a BlockDecl with expressions. 4373 /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body } 4374 class BlockExpr : public Expr { 4375 protected: 4376 BlockDecl *TheBlock; 4377 public: 4378 BlockExpr(BlockDecl *BD, QualType ty) 4379 : Expr(BlockExprClass, ty, VK_RValue, OK_Ordinary, 4380 ty->isDependentType(), ty->isDependentType(), 4381 ty->isInstantiationDependentType() || BD->isDependentContext(), 4382 false), 4383 TheBlock(BD) {} 4384 4385 /// \brief Build an empty block expression. 4386 explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { } 4387 4388 const BlockDecl *getBlockDecl() const { return TheBlock; } 4389 BlockDecl *getBlockDecl() { return TheBlock; } 4390 void setBlockDecl(BlockDecl *BD) { TheBlock = BD; } 4391 4392 // Convenience functions for probing the underlying BlockDecl. 4393 SourceLocation getCaretLocation() const; 4394 const Stmt *getBody() const; 4395 Stmt *getBody(); 4396 4397 SourceLocation getLocStart() const LLVM_READONLY { return getCaretLocation(); } 4398 SourceLocation getLocEnd() const LLVM_READONLY { return getBody()->getLocEnd(); } 4399 4400 /// getFunctionType - Return the underlying function type for this block. 4401 const FunctionProtoType *getFunctionType() const; 4402 4403 static bool classof(const Stmt *T) { 4404 return T->getStmtClass() == BlockExprClass; 4405 } 4406 4407 // Iterators 4408 child_range children() { return child_range(); } 4409 }; 4410 4411 /// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2] 4412 /// This AST node provides support for reinterpreting a type to another 4413 /// type of the same size. 4414 class AsTypeExpr : public Expr { // Should this be an ExplicitCastExpr? 4415 private: 4416 Stmt *SrcExpr; 4417 SourceLocation BuiltinLoc, RParenLoc; 4418 4419 friend class ASTReader; 4420 friend class ASTStmtReader; 4421 explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {} 4422 4423 public: 4424 AsTypeExpr(Expr* SrcExpr, QualType DstType, 4425 ExprValueKind VK, ExprObjectKind OK, 4426 SourceLocation BuiltinLoc, SourceLocation RParenLoc) 4427 : Expr(AsTypeExprClass, DstType, VK, OK, 4428 DstType->isDependentType(), 4429 DstType->isDependentType() || SrcExpr->isValueDependent(), 4430 (DstType->isInstantiationDependentType() || 4431 SrcExpr->isInstantiationDependent()), 4432 (DstType->containsUnexpandedParameterPack() || 4433 SrcExpr->containsUnexpandedParameterPack())), 4434 SrcExpr(SrcExpr), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {} 4435 4436 /// getSrcExpr - Return the Expr to be converted. 4437 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); } 4438 4439 /// getBuiltinLoc - Return the location of the __builtin_astype token. 4440 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 4441 4442 /// getRParenLoc - Return the location of final right parenthesis. 4443 SourceLocation getRParenLoc() const { return RParenLoc; } 4444 4445 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; } 4446 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } 4447 4448 static bool classof(const Stmt *T) { 4449 return T->getStmtClass() == AsTypeExprClass; 4450 } 4451 4452 // Iterators 4453 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); } 4454 }; 4455 4456 /// PseudoObjectExpr - An expression which accesses a pseudo-object 4457 /// l-value. A pseudo-object is an abstract object, accesses to which 4458 /// are translated to calls. The pseudo-object expression has a 4459 /// syntactic form, which shows how the expression was actually 4460 /// written in the source code, and a semantic form, which is a series 4461 /// of expressions to be executed in order which detail how the 4462 /// operation is actually evaluated. Optionally, one of the semantic 4463 /// forms may also provide a result value for the expression. 4464 /// 4465 /// If any of the semantic-form expressions is an OpaqueValueExpr, 4466 /// that OVE is required to have a source expression, and it is bound 4467 /// to the result of that source expression. Such OVEs may appear 4468 /// only in subsequent semantic-form expressions and as 4469 /// sub-expressions of the syntactic form. 4470 /// 4471 /// PseudoObjectExpr should be used only when an operation can be 4472 /// usefully described in terms of fairly simple rewrite rules on 4473 /// objects and functions that are meant to be used by end-developers. 4474 /// For example, under the Itanium ABI, dynamic casts are implemented 4475 /// as a call to a runtime function called __dynamic_cast; using this 4476 /// class to describe that would be inappropriate because that call is 4477 /// not really part of the user-visible semantics, and instead the 4478 /// cast is properly reflected in the AST and IR-generation has been 4479 /// taught to generate the call as necessary. In contrast, an 4480 /// Objective-C property access is semantically defined to be 4481 /// equivalent to a particular message send, and this is very much 4482 /// part of the user model. The name of this class encourages this 4483 /// modelling design. 4484 class PseudoObjectExpr : public Expr { 4485 // PseudoObjectExprBits.NumSubExprs - The number of sub-expressions. 4486 // Always at least two, because the first sub-expression is the 4487 // syntactic form. 4488 4489 // PseudoObjectExprBits.ResultIndex - The index of the 4490 // sub-expression holding the result. 0 means the result is void, 4491 // which is unambiguous because it's the index of the syntactic 4492 // form. Note that this is therefore 1 higher than the value passed 4493 // in to Create, which is an index within the semantic forms. 4494 // Note also that ASTStmtWriter assumes this encoding. 4495 4496 Expr **getSubExprsBuffer() { return reinterpret_cast<Expr**>(this + 1); } 4497 const Expr * const *getSubExprsBuffer() const { 4498 return reinterpret_cast<const Expr * const *>(this + 1); 4499 } 4500 4501 friend class ASTStmtReader; 4502 4503 PseudoObjectExpr(QualType type, ExprValueKind VK, 4504 Expr *syntactic, ArrayRef<Expr*> semantic, 4505 unsigned resultIndex); 4506 4507 PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs); 4508 4509 unsigned getNumSubExprs() const { 4510 return PseudoObjectExprBits.NumSubExprs; 4511 } 4512 4513 public: 4514 /// NoResult - A value for the result index indicating that there is 4515 /// no semantic result. 4516 enum { NoResult = ~0U }; 4517 4518 static PseudoObjectExpr *Create(ASTContext &Context, Expr *syntactic, 4519 ArrayRef<Expr*> semantic, 4520 unsigned resultIndex); 4521 4522 static PseudoObjectExpr *Create(ASTContext &Context, EmptyShell shell, 4523 unsigned numSemanticExprs); 4524 4525 /// Return the syntactic form of this expression, i.e. the 4526 /// expression it actually looks like. Likely to be expressed in 4527 /// terms of OpaqueValueExprs bound in the semantic form. 4528 Expr *getSyntacticForm() { return getSubExprsBuffer()[0]; } 4529 const Expr *getSyntacticForm() const { return getSubExprsBuffer()[0]; } 4530 4531 /// Return the index of the result-bearing expression into the semantics 4532 /// expressions, or PseudoObjectExpr::NoResult if there is none. 4533 unsigned getResultExprIndex() const { 4534 if (PseudoObjectExprBits.ResultIndex == 0) return NoResult; 4535 return PseudoObjectExprBits.ResultIndex - 1; 4536 } 4537 4538 /// Return the result-bearing expression, or null if there is none. 4539 Expr *getResultExpr() { 4540 if (PseudoObjectExprBits.ResultIndex == 0) 4541 return 0; 4542 return getSubExprsBuffer()[PseudoObjectExprBits.ResultIndex]; 4543 } 4544 const Expr *getResultExpr() const { 4545 return const_cast<PseudoObjectExpr*>(this)->getResultExpr(); 4546 } 4547 4548 unsigned getNumSemanticExprs() const { return getNumSubExprs() - 1; } 4549 4550 typedef Expr * const *semantics_iterator; 4551 typedef const Expr * const *const_semantics_iterator; 4552 semantics_iterator semantics_begin() { 4553 return getSubExprsBuffer() + 1; 4554 } 4555 const_semantics_iterator semantics_begin() const { 4556 return getSubExprsBuffer() + 1; 4557 } 4558 semantics_iterator semantics_end() { 4559 return getSubExprsBuffer() + getNumSubExprs(); 4560 } 4561 const_semantics_iterator semantics_end() const { 4562 return getSubExprsBuffer() + getNumSubExprs(); 4563 } 4564 Expr *getSemanticExpr(unsigned index) { 4565 assert(index + 1 < getNumSubExprs()); 4566 return getSubExprsBuffer()[index + 1]; 4567 } 4568 const Expr *getSemanticExpr(unsigned index) const { 4569 return const_cast<PseudoObjectExpr*>(this)->getSemanticExpr(index); 4570 } 4571 4572 SourceLocation getExprLoc() const LLVM_READONLY { 4573 return getSyntacticForm()->getExprLoc(); 4574 } 4575 4576 SourceLocation getLocStart() const LLVM_READONLY { 4577 return getSyntacticForm()->getLocStart(); 4578 } 4579 SourceLocation getLocEnd() const LLVM_READONLY { 4580 return getSyntacticForm()->getLocEnd(); 4581 } 4582 4583 child_range children() { 4584 Stmt **cs = reinterpret_cast<Stmt**>(getSubExprsBuffer()); 4585 return child_range(cs, cs + getNumSubExprs()); 4586 } 4587 4588 static bool classof(const Stmt *T) { 4589 return T->getStmtClass() == PseudoObjectExprClass; 4590 } 4591 }; 4592 4593 /// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, 4594 /// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the 4595 /// similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>. 4596 /// All of these instructions take one primary pointer and at least one memory 4597 /// order. 4598 class AtomicExpr : public Expr { 4599 public: 4600 enum AtomicOp { 4601 #define BUILTIN(ID, TYPE, ATTRS) 4602 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) AO ## ID, 4603 #include "clang/Basic/Builtins.def" 4604 // Avoid trailing comma 4605 BI_First = 0 4606 }; 4607 4608 private: 4609 enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, WEAK, END_EXPR }; 4610 Stmt* SubExprs[END_EXPR]; 4611 unsigned NumSubExprs; 4612 SourceLocation BuiltinLoc, RParenLoc; 4613 AtomicOp Op; 4614 4615 friend class ASTStmtReader; 4616 4617 public: 4618 AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args, QualType t, 4619 AtomicOp op, SourceLocation RP); 4620 4621 /// \brief Determine the number of arguments the specified atomic builtin 4622 /// should have. 4623 static unsigned getNumSubExprs(AtomicOp Op); 4624 4625 /// \brief Build an empty AtomicExpr. 4626 explicit AtomicExpr(EmptyShell Empty) : Expr(AtomicExprClass, Empty) { } 4627 4628 Expr *getPtr() const { 4629 return cast<Expr>(SubExprs[PTR]); 4630 } 4631 Expr *getOrder() const { 4632 return cast<Expr>(SubExprs[ORDER]); 4633 } 4634 Expr *getVal1() const { 4635 if (Op == AO__c11_atomic_init) 4636 return cast<Expr>(SubExprs[ORDER]); 4637 assert(NumSubExprs > VAL1); 4638 return cast<Expr>(SubExprs[VAL1]); 4639 } 4640 Expr *getOrderFail() const { 4641 assert(NumSubExprs > ORDER_FAIL); 4642 return cast<Expr>(SubExprs[ORDER_FAIL]); 4643 } 4644 Expr *getVal2() const { 4645 if (Op == AO__atomic_exchange) 4646 return cast<Expr>(SubExprs[ORDER_FAIL]); 4647 assert(NumSubExprs > VAL2); 4648 return cast<Expr>(SubExprs[VAL2]); 4649 } 4650 Expr *getWeak() const { 4651 assert(NumSubExprs > WEAK); 4652 return cast<Expr>(SubExprs[WEAK]); 4653 } 4654 4655 AtomicOp getOp() const { return Op; } 4656 unsigned getNumSubExprs() { return NumSubExprs; } 4657 4658 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); } 4659 4660 bool isVolatile() const { 4661 return getPtr()->getType()->getPointeeType().isVolatileQualified(); 4662 } 4663 4664 bool isCmpXChg() const { 4665 return getOp() == AO__c11_atomic_compare_exchange_strong || 4666 getOp() == AO__c11_atomic_compare_exchange_weak || 4667 getOp() == AO__atomic_compare_exchange || 4668 getOp() == AO__atomic_compare_exchange_n; 4669 } 4670 4671 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 4672 SourceLocation getRParenLoc() const { return RParenLoc; } 4673 4674 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; } 4675 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } 4676 4677 static bool classof(const Stmt *T) { 4678 return T->getStmtClass() == AtomicExprClass; 4679 } 4680 4681 // Iterators 4682 child_range children() { 4683 return child_range(SubExprs, SubExprs+NumSubExprs); 4684 } 4685 }; 4686 } // end namespace clang 4687 4688 #endif 4689