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