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