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 FuncDName, 1154 PrettyFunction, 1155 /// PrettyFunctionNoVirtual - The same as PrettyFunction, except that the 1156 /// 'virtual' keyword is omitted for virtual member functions. 1157 PrettyFunctionNoVirtual 1158 }; 1159 1160private: 1161 SourceLocation Loc; 1162 IdentType Type; 1163public: 1164 PredefinedExpr(SourceLocation l, QualType type, IdentType IT) 1165 : Expr(PredefinedExprClass, type, VK_LValue, OK_Ordinary, 1166 type->isDependentType(), type->isDependentType(), 1167 type->isInstantiationDependentType(), 1168 /*ContainsUnexpandedParameterPack=*/false), 1169 Loc(l), Type(IT) {} 1170 1171 /// \brief Construct an empty predefined expression. 1172 explicit PredefinedExpr(EmptyShell Empty) 1173 : Expr(PredefinedExprClass, Empty) { } 1174 1175 IdentType getIdentType() const { return Type; } 1176 void setIdentType(IdentType IT) { Type = IT; } 1177 1178 SourceLocation getLocation() const { return Loc; } 1179 void setLocation(SourceLocation L) { Loc = L; } 1180 1181 static std::string ComputeName(IdentType IT, const Decl *CurrentDecl); 1182 1183 SourceLocation getLocStart() const LLVM_READONLY { return Loc; } 1184 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; } 1185 1186 static bool classof(const Stmt *T) { 1187 return T->getStmtClass() == PredefinedExprClass; 1188 } 1189 1190 // Iterators 1191 child_range children() { return child_range(); } 1192}; 1193 1194/// \brief Used by IntegerLiteral/FloatingLiteral to store the numeric without 1195/// leaking memory. 1196/// 1197/// For large floats/integers, APFloat/APInt will allocate memory from the heap 1198/// to represent these numbers. Unfortunately, when we use a BumpPtrAllocator 1199/// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with 1200/// the APFloat/APInt values will never get freed. APNumericStorage uses 1201/// ASTContext's allocator for memory allocation. 1202class APNumericStorage { 1203 union { 1204 uint64_t VAL; ///< Used to store the <= 64 bits integer value. 1205 uint64_t *pVal; ///< Used to store the >64 bits integer value. 1206 }; 1207 unsigned BitWidth; 1208 1209 bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; } 1210 1211 APNumericStorage(const APNumericStorage &) LLVM_DELETED_FUNCTION; 1212 void operator=(const APNumericStorage &) LLVM_DELETED_FUNCTION; 1213 1214protected: 1215 APNumericStorage() : VAL(0), BitWidth(0) { } 1216 1217 llvm::APInt getIntValue() const { 1218 unsigned NumWords = llvm::APInt::getNumWords(BitWidth); 1219 if (NumWords > 1) 1220 return llvm::APInt(BitWidth, NumWords, pVal); 1221 else 1222 return llvm::APInt(BitWidth, VAL); 1223 } 1224 void setIntValue(const ASTContext &C, const llvm::APInt &Val); 1225}; 1226 1227class APIntStorage : private APNumericStorage { 1228public: 1229 llvm::APInt getValue() const { return getIntValue(); } 1230 void setValue(const ASTContext &C, const llvm::APInt &Val) { 1231 setIntValue(C, Val); 1232 } 1233}; 1234 1235class APFloatStorage : private APNumericStorage { 1236public: 1237 llvm::APFloat getValue(const llvm::fltSemantics &Semantics) const { 1238 return llvm::APFloat(Semantics, getIntValue()); 1239 } 1240 void setValue(const ASTContext &C, const llvm::APFloat &Val) { 1241 setIntValue(C, Val.bitcastToAPInt()); 1242 } 1243}; 1244 1245class IntegerLiteral : public Expr, public APIntStorage { 1246 SourceLocation Loc; 1247 1248 /// \brief Construct an empty integer literal. 1249 explicit IntegerLiteral(EmptyShell Empty) 1250 : Expr(IntegerLiteralClass, Empty) { } 1251 1252public: 1253 // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy, 1254 // or UnsignedLongLongTy 1255 IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type, 1256 SourceLocation l); 1257 1258 /// \brief Returns a new integer literal with value 'V' and type 'type'. 1259 /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy, 1260 /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V 1261 /// \param V - the value that the returned integer literal contains. 1262 static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V, 1263 QualType type, SourceLocation l); 1264 /// \brief Returns a new empty integer literal. 1265 static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty); 1266 1267 SourceLocation getLocStart() const LLVM_READONLY { return Loc; } 1268 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; } 1269 1270 /// \brief Retrieve the location of the literal. 1271 SourceLocation getLocation() const { return Loc; } 1272 1273 void setLocation(SourceLocation Location) { Loc = Location; } 1274 1275 static bool classof(const Stmt *T) { 1276 return T->getStmtClass() == IntegerLiteralClass; 1277 } 1278 1279 // Iterators 1280 child_range children() { return child_range(); } 1281}; 1282 1283class CharacterLiteral : public Expr { 1284public: 1285 enum CharacterKind { 1286 Ascii, 1287 Wide, 1288 UTF16, 1289 UTF32 1290 }; 1291 1292private: 1293 unsigned Value; 1294 SourceLocation Loc; 1295public: 1296 // type should be IntTy 1297 CharacterLiteral(unsigned value, CharacterKind kind, QualType type, 1298 SourceLocation l) 1299 : Expr(CharacterLiteralClass, type, VK_RValue, OK_Ordinary, false, false, 1300 false, false), 1301 Value(value), Loc(l) { 1302 CharacterLiteralBits.Kind = kind; 1303 } 1304 1305 /// \brief Construct an empty character literal. 1306 CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { } 1307 1308 SourceLocation getLocation() const { return Loc; } 1309 CharacterKind getKind() const { 1310 return static_cast<CharacterKind>(CharacterLiteralBits.Kind); 1311 } 1312 1313 SourceLocation getLocStart() const LLVM_READONLY { return Loc; } 1314 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; } 1315 1316 unsigned getValue() const { return Value; } 1317 1318 void setLocation(SourceLocation Location) { Loc = Location; } 1319 void setKind(CharacterKind kind) { CharacterLiteralBits.Kind = kind; } 1320 void setValue(unsigned Val) { Value = Val; } 1321 1322 static bool classof(const Stmt *T) { 1323 return T->getStmtClass() == CharacterLiteralClass; 1324 } 1325 1326 // Iterators 1327 child_range children() { return child_range(); } 1328}; 1329 1330class FloatingLiteral : public Expr, private APFloatStorage { 1331 SourceLocation Loc; 1332 1333 FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact, 1334 QualType Type, SourceLocation L); 1335 1336 /// \brief Construct an empty floating-point literal. 1337 explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty); 1338 1339public: 1340 static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V, 1341 bool isexact, QualType Type, SourceLocation L); 1342 static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty); 1343 1344 llvm::APFloat getValue() const { 1345 return APFloatStorage::getValue(getSemantics()); 1346 } 1347 void setValue(const ASTContext &C, const llvm::APFloat &Val) { 1348 assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics"); 1349 APFloatStorage::setValue(C, Val); 1350 } 1351 1352 /// Get a raw enumeration value representing the floating-point semantics of 1353 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation. 1354 APFloatSemantics getRawSemantics() const { 1355 return static_cast<APFloatSemantics>(FloatingLiteralBits.Semantics); 1356 } 1357 1358 /// Set the raw enumeration value representing the floating-point semantics of 1359 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation. 1360 void setRawSemantics(APFloatSemantics Sem) { 1361 FloatingLiteralBits.Semantics = Sem; 1362 } 1363 1364 /// Return the APFloat semantics this literal uses. 1365 const llvm::fltSemantics &getSemantics() const; 1366 1367 /// Set the APFloat semantics this literal uses. 1368 void setSemantics(const llvm::fltSemantics &Sem); 1369 1370 bool isExact() const { return FloatingLiteralBits.IsExact; } 1371 void setExact(bool E) { FloatingLiteralBits.IsExact = E; } 1372 1373 /// getValueAsApproximateDouble - This returns the value as an inaccurate 1374 /// double. Note that this may cause loss of precision, but is useful for 1375 /// debugging dumps, etc. 1376 double getValueAsApproximateDouble() const; 1377 1378 SourceLocation getLocation() const { return Loc; } 1379 void setLocation(SourceLocation L) { Loc = L; } 1380 1381 SourceLocation getLocStart() const LLVM_READONLY { return Loc; } 1382 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; } 1383 1384 static bool classof(const Stmt *T) { 1385 return T->getStmtClass() == FloatingLiteralClass; 1386 } 1387 1388 // Iterators 1389 child_range children() { return child_range(); } 1390}; 1391 1392/// ImaginaryLiteral - We support imaginary integer and floating point literals, 1393/// like "1.0i". We represent these as a wrapper around FloatingLiteral and 1394/// IntegerLiteral classes. Instances of this class always have a Complex type 1395/// whose element type matches the subexpression. 1396/// 1397class ImaginaryLiteral : public Expr { 1398 Stmt *Val; 1399public: 1400 ImaginaryLiteral(Expr *val, QualType Ty) 1401 : Expr(ImaginaryLiteralClass, Ty, VK_RValue, OK_Ordinary, false, false, 1402 false, false), 1403 Val(val) {} 1404 1405 /// \brief Build an empty imaginary literal. 1406 explicit ImaginaryLiteral(EmptyShell Empty) 1407 : Expr(ImaginaryLiteralClass, Empty) { } 1408 1409 const Expr *getSubExpr() const { return cast<Expr>(Val); } 1410 Expr *getSubExpr() { return cast<Expr>(Val); } 1411 void setSubExpr(Expr *E) { Val = E; } 1412 1413 SourceLocation getLocStart() const LLVM_READONLY { return Val->getLocStart(); } 1414 SourceLocation getLocEnd() const LLVM_READONLY { return Val->getLocEnd(); } 1415 1416 static bool classof(const Stmt *T) { 1417 return T->getStmtClass() == ImaginaryLiteralClass; 1418 } 1419 1420 // Iterators 1421 child_range children() { return child_range(&Val, &Val+1); } 1422}; 1423 1424/// StringLiteral - This represents a string literal expression, e.g. "foo" 1425/// or L"bar" (wide strings). The actual string is returned by getBytes() 1426/// is NOT null-terminated, and the length of the string is determined by 1427/// calling getByteLength(). The C type for a string is always a 1428/// ConstantArrayType. In C++, the char type is const qualified, in C it is 1429/// not. 1430/// 1431/// Note that strings in C can be formed by concatenation of multiple string 1432/// literal pptokens in translation phase #6. This keeps track of the locations 1433/// of each of these pieces. 1434/// 1435/// Strings in C can also be truncated and extended by assigning into arrays, 1436/// e.g. with constructs like: 1437/// char X[2] = "foobar"; 1438/// In this case, getByteLength() will return 6, but the string literal will 1439/// have type "char[2]". 1440class StringLiteral : public Expr { 1441public: 1442 enum StringKind { 1443 Ascii, 1444 Wide, 1445 UTF8, 1446 UTF16, 1447 UTF32 1448 }; 1449 1450private: 1451 friend class ASTStmtReader; 1452 1453 union { 1454 const char *asChar; 1455 const uint16_t *asUInt16; 1456 const uint32_t *asUInt32; 1457 } StrData; 1458 unsigned Length; 1459 unsigned CharByteWidth : 4; 1460 unsigned Kind : 3; 1461 unsigned IsPascal : 1; 1462 unsigned NumConcatenated; 1463 SourceLocation TokLocs[1]; 1464 1465 StringLiteral(QualType Ty) : 1466 Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false, 1467 false) {} 1468 1469 static int mapCharByteWidth(TargetInfo const &target,StringKind k); 1470 1471public: 1472 /// This is the "fully general" constructor that allows representation of 1473 /// strings formed from multiple concatenated tokens. 1474 static StringLiteral *Create(const ASTContext &C, StringRef Str, 1475 StringKind Kind, bool Pascal, QualType Ty, 1476 const SourceLocation *Loc, unsigned NumStrs); 1477 1478 /// Simple constructor for string literals made from one token. 1479 static StringLiteral *Create(const ASTContext &C, StringRef Str, 1480 StringKind Kind, bool Pascal, QualType Ty, 1481 SourceLocation Loc) { 1482 return Create(C, Str, Kind, Pascal, Ty, &Loc, 1); 1483 } 1484 1485 /// \brief Construct an empty string literal. 1486 static StringLiteral *CreateEmpty(const ASTContext &C, unsigned NumStrs); 1487 1488 StringRef getString() const { 1489 assert(CharByteWidth==1 1490 && "This function is used in places that assume strings use char"); 1491 return StringRef(StrData.asChar, getByteLength()); 1492 } 1493 1494 /// Allow access to clients that need the byte representation, such as 1495 /// ASTWriterStmt::VisitStringLiteral(). 1496 StringRef getBytes() const { 1497 // FIXME: StringRef may not be the right type to use as a result for this. 1498 if (CharByteWidth == 1) 1499 return StringRef(StrData.asChar, getByteLength()); 1500 if (CharByteWidth == 4) 1501 return StringRef(reinterpret_cast<const char*>(StrData.asUInt32), 1502 getByteLength()); 1503 assert(CharByteWidth == 2 && "unsupported CharByteWidth"); 1504 return StringRef(reinterpret_cast<const char*>(StrData.asUInt16), 1505 getByteLength()); 1506 } 1507 1508 void outputString(raw_ostream &OS) const; 1509 1510 uint32_t getCodeUnit(size_t i) const { 1511 assert(i < Length && "out of bounds access"); 1512 if (CharByteWidth == 1) 1513 return static_cast<unsigned char>(StrData.asChar[i]); 1514 if (CharByteWidth == 4) 1515 return StrData.asUInt32[i]; 1516 assert(CharByteWidth == 2 && "unsupported CharByteWidth"); 1517 return StrData.asUInt16[i]; 1518 } 1519 1520 unsigned getByteLength() const { return CharByteWidth*Length; } 1521 unsigned getLength() const { return Length; } 1522 unsigned getCharByteWidth() const { return CharByteWidth; } 1523 1524 /// \brief Sets the string data to the given string data. 1525 void setString(const ASTContext &C, StringRef Str, 1526 StringKind Kind, bool IsPascal); 1527 1528 StringKind getKind() const { return static_cast<StringKind>(Kind); } 1529 1530 1531 bool isAscii() const { return Kind == Ascii; } 1532 bool isWide() const { return Kind == Wide; } 1533 bool isUTF8() const { return Kind == UTF8; } 1534 bool isUTF16() const { return Kind == UTF16; } 1535 bool isUTF32() const { return Kind == UTF32; } 1536 bool isPascal() const { return IsPascal; } 1537 1538 bool containsNonAsciiOrNull() const { 1539 StringRef Str = getString(); 1540 for (unsigned i = 0, e = Str.size(); i != e; ++i) 1541 if (!isASCII(Str[i]) || !Str[i]) 1542 return true; 1543 return false; 1544 } 1545 1546 /// getNumConcatenated - Get the number of string literal tokens that were 1547 /// concatenated in translation phase #6 to form this string literal. 1548 unsigned getNumConcatenated() const { return NumConcatenated; } 1549 1550 SourceLocation getStrTokenLoc(unsigned TokNum) const { 1551 assert(TokNum < NumConcatenated && "Invalid tok number"); 1552 return TokLocs[TokNum]; 1553 } 1554 void setStrTokenLoc(unsigned TokNum, SourceLocation L) { 1555 assert(TokNum < NumConcatenated && "Invalid tok number"); 1556 TokLocs[TokNum] = L; 1557 } 1558 1559 /// getLocationOfByte - Return a source location that points to the specified 1560 /// byte of this string literal. 1561 /// 1562 /// Strings are amazingly complex. They can be formed from multiple tokens 1563 /// and can have escape sequences in them in addition to the usual trigraph 1564 /// and escaped newline business. This routine handles this complexity. 1565 /// 1566 SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM, 1567 const LangOptions &Features, 1568 const TargetInfo &Target) const; 1569 1570 typedef const SourceLocation *tokloc_iterator; 1571 tokloc_iterator tokloc_begin() const { return TokLocs; } 1572 tokloc_iterator tokloc_end() const { return TokLocs+NumConcatenated; } 1573 1574 SourceLocation getLocStart() const LLVM_READONLY { return TokLocs[0]; } 1575 SourceLocation getLocEnd() const LLVM_READONLY { 1576 return TokLocs[NumConcatenated - 1]; 1577 } 1578 1579 static bool classof(const Stmt *T) { 1580 return T->getStmtClass() == StringLiteralClass; 1581 } 1582 1583 // Iterators 1584 child_range children() { return child_range(); } 1585}; 1586 1587/// ParenExpr - This represents a parethesized expression, e.g. "(1)". This 1588/// AST node is only formed if full location information is requested. 1589class ParenExpr : public Expr { 1590 SourceLocation L, R; 1591 Stmt *Val; 1592public: 1593 ParenExpr(SourceLocation l, SourceLocation r, Expr *val) 1594 : Expr(ParenExprClass, val->getType(), 1595 val->getValueKind(), val->getObjectKind(), 1596 val->isTypeDependent(), val->isValueDependent(), 1597 val->isInstantiationDependent(), 1598 val->containsUnexpandedParameterPack()), 1599 L(l), R(r), Val(val) {} 1600 1601 /// \brief Construct an empty parenthesized expression. 1602 explicit ParenExpr(EmptyShell Empty) 1603 : Expr(ParenExprClass, Empty) { } 1604 1605 const Expr *getSubExpr() const { return cast<Expr>(Val); } 1606 Expr *getSubExpr() { return cast<Expr>(Val); } 1607 void setSubExpr(Expr *E) { Val = E; } 1608 1609 SourceLocation getLocStart() const LLVM_READONLY { return L; } 1610 SourceLocation getLocEnd() const LLVM_READONLY { return R; } 1611 1612 /// \brief Get the location of the left parentheses '('. 1613 SourceLocation getLParen() const { return L; } 1614 void setLParen(SourceLocation Loc) { L = Loc; } 1615 1616 /// \brief Get the location of the right parentheses ')'. 1617 SourceLocation getRParen() const { return R; } 1618 void setRParen(SourceLocation Loc) { R = Loc; } 1619 1620 static bool classof(const Stmt *T) { 1621 return T->getStmtClass() == ParenExprClass; 1622 } 1623 1624 // Iterators 1625 child_range children() { return child_range(&Val, &Val+1); } 1626}; 1627 1628 1629/// UnaryOperator - This represents the unary-expression's (except sizeof and 1630/// alignof), the postinc/postdec operators from postfix-expression, and various 1631/// extensions. 1632/// 1633/// Notes on various nodes: 1634/// 1635/// Real/Imag - These return the real/imag part of a complex operand. If 1636/// applied to a non-complex value, the former returns its operand and the 1637/// later returns zero in the type of the operand. 1638/// 1639class UnaryOperator : public Expr { 1640public: 1641 typedef UnaryOperatorKind Opcode; 1642 1643private: 1644 unsigned Opc : 5; 1645 SourceLocation Loc; 1646 Stmt *Val; 1647public: 1648 1649 UnaryOperator(Expr *input, Opcode opc, QualType type, 1650 ExprValueKind VK, ExprObjectKind OK, SourceLocation l) 1651 : Expr(UnaryOperatorClass, type, VK, OK, 1652 input->isTypeDependent() || type->isDependentType(), 1653 input->isValueDependent(), 1654 (input->isInstantiationDependent() || 1655 type->isInstantiationDependentType()), 1656 input->containsUnexpandedParameterPack()), 1657 Opc(opc), Loc(l), Val(input) {} 1658 1659 /// \brief Build an empty unary operator. 1660 explicit UnaryOperator(EmptyShell Empty) 1661 : Expr(UnaryOperatorClass, Empty), Opc(UO_AddrOf) { } 1662 1663 Opcode getOpcode() const { return static_cast<Opcode>(Opc); } 1664 void setOpcode(Opcode O) { Opc = O; } 1665 1666 Expr *getSubExpr() const { return cast<Expr>(Val); } 1667 void setSubExpr(Expr *E) { Val = E; } 1668 1669 /// getOperatorLoc - Return the location of the operator. 1670 SourceLocation getOperatorLoc() const { return Loc; } 1671 void setOperatorLoc(SourceLocation L) { Loc = L; } 1672 1673 /// isPostfix - Return true if this is a postfix operation, like x++. 1674 static bool isPostfix(Opcode Op) { 1675 return Op == UO_PostInc || Op == UO_PostDec; 1676 } 1677 1678 /// isPrefix - Return true if this is a prefix operation, like --x. 1679 static bool isPrefix(Opcode Op) { 1680 return Op == UO_PreInc || Op == UO_PreDec; 1681 } 1682 1683 bool isPrefix() const { return isPrefix(getOpcode()); } 1684 bool isPostfix() const { return isPostfix(getOpcode()); } 1685 1686 static bool isIncrementOp(Opcode Op) { 1687 return Op == UO_PreInc || Op == UO_PostInc; 1688 } 1689 bool isIncrementOp() const { 1690 return isIncrementOp(getOpcode()); 1691 } 1692 1693 static bool isDecrementOp(Opcode Op) { 1694 return Op == UO_PreDec || Op == UO_PostDec; 1695 } 1696 bool isDecrementOp() const { 1697 return isDecrementOp(getOpcode()); 1698 } 1699 1700 static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; } 1701 bool isIncrementDecrementOp() const { 1702 return isIncrementDecrementOp(getOpcode()); 1703 } 1704 1705 static bool isArithmeticOp(Opcode Op) { 1706 return Op >= UO_Plus && Op <= UO_LNot; 1707 } 1708 bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); } 1709 1710 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it 1711 /// corresponds to, e.g. "sizeof" or "[pre]++" 1712 static StringRef getOpcodeStr(Opcode Op); 1713 1714 /// \brief Retrieve the unary opcode that corresponds to the given 1715 /// overloaded operator. 1716 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix); 1717 1718 /// \brief Retrieve the overloaded operator kind that corresponds to 1719 /// the given unary opcode. 1720 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc); 1721 1722 SourceLocation getLocStart() const LLVM_READONLY { 1723 return isPostfix() ? Val->getLocStart() : Loc; 1724 } 1725 SourceLocation getLocEnd() const LLVM_READONLY { 1726 return isPostfix() ? Loc : Val->getLocEnd(); 1727 } 1728 SourceLocation getExprLoc() const LLVM_READONLY { return Loc; } 1729 1730 static bool classof(const Stmt *T) { 1731 return T->getStmtClass() == UnaryOperatorClass; 1732 } 1733 1734 // Iterators 1735 child_range children() { return child_range(&Val, &Val+1); } 1736}; 1737 1738/// OffsetOfExpr - [C99 7.17] - This represents an expression of the form 1739/// offsetof(record-type, member-designator). For example, given: 1740/// @code 1741/// struct S { 1742/// float f; 1743/// double d; 1744/// }; 1745/// struct T { 1746/// int i; 1747/// struct S s[10]; 1748/// }; 1749/// @endcode 1750/// we can represent and evaluate the expression @c offsetof(struct T, s[2].d). 1751 1752class OffsetOfExpr : public Expr { 1753public: 1754 // __builtin_offsetof(type, identifier(.identifier|[expr])*) 1755 class OffsetOfNode { 1756 public: 1757 /// \brief The kind of offsetof node we have. 1758 enum Kind { 1759 /// \brief An index into an array. 1760 Array = 0x00, 1761 /// \brief A field. 1762 Field = 0x01, 1763 /// \brief A field in a dependent type, known only by its name. 1764 Identifier = 0x02, 1765 /// \brief An implicit indirection through a C++ base class, when the 1766 /// field found is in a base class. 1767 Base = 0x03 1768 }; 1769 1770 private: 1771 enum { MaskBits = 2, Mask = 0x03 }; 1772 1773 /// \brief The source range that covers this part of the designator. 1774 SourceRange Range; 1775 1776 /// \brief The data describing the designator, which comes in three 1777 /// different forms, depending on the lower two bits. 1778 /// - An unsigned index into the array of Expr*'s stored after this node 1779 /// in memory, for [constant-expression] designators. 1780 /// - A FieldDecl*, for references to a known field. 1781 /// - An IdentifierInfo*, for references to a field with a given name 1782 /// when the class type is dependent. 1783 /// - A CXXBaseSpecifier*, for references that look at a field in a 1784 /// base class. 1785 uintptr_t Data; 1786 1787 public: 1788 /// \brief Create an offsetof node that refers to an array element. 1789 OffsetOfNode(SourceLocation LBracketLoc, unsigned Index, 1790 SourceLocation RBracketLoc) 1791 : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) { } 1792 1793 /// \brief Create an offsetof node that refers to a field. 1794 OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field, 1795 SourceLocation NameLoc) 1796 : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc), 1797 Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) { } 1798 1799 /// \brief Create an offsetof node that refers to an identifier. 1800 OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name, 1801 SourceLocation NameLoc) 1802 : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc), 1803 Data(reinterpret_cast<uintptr_t>(Name) | Identifier) { } 1804 1805 /// \brief Create an offsetof node that refers into a C++ base class. 1806 explicit OffsetOfNode(const CXXBaseSpecifier *Base) 1807 : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {} 1808 1809 /// \brief Determine what kind of offsetof node this is. 1810 Kind getKind() const { 1811 return static_cast<Kind>(Data & Mask); 1812 } 1813 1814 /// \brief For an array element node, returns the index into the array 1815 /// of expressions. 1816 unsigned getArrayExprIndex() const { 1817 assert(getKind() == Array); 1818 return Data >> 2; 1819 } 1820 1821 /// \brief For a field offsetof node, returns the field. 1822 FieldDecl *getField() const { 1823 assert(getKind() == Field); 1824 return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask); 1825 } 1826 1827 /// \brief For a field or identifier offsetof node, returns the name of 1828 /// the field. 1829 IdentifierInfo *getFieldName() const; 1830 1831 /// \brief For a base class node, returns the base specifier. 1832 CXXBaseSpecifier *getBase() const { 1833 assert(getKind() == Base); 1834 return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask); 1835 } 1836 1837 /// \brief Retrieve the source range that covers this offsetof node. 1838 /// 1839 /// For an array element node, the source range contains the locations of 1840 /// the square brackets. For a field or identifier node, the source range 1841 /// contains the location of the period (if there is one) and the 1842 /// identifier. 1843 SourceRange getSourceRange() const LLVM_READONLY { return Range; } 1844 SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); } 1845 SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); } 1846 }; 1847 1848private: 1849 1850 SourceLocation OperatorLoc, RParenLoc; 1851 // Base type; 1852 TypeSourceInfo *TSInfo; 1853 // Number of sub-components (i.e. instances of OffsetOfNode). 1854 unsigned NumComps; 1855 // Number of sub-expressions (i.e. array subscript expressions). 1856 unsigned NumExprs; 1857 1858 OffsetOfExpr(const ASTContext &C, QualType type, 1859 SourceLocation OperatorLoc, TypeSourceInfo *tsi, 1860 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs, 1861 SourceLocation RParenLoc); 1862 1863 explicit OffsetOfExpr(unsigned numComps, unsigned numExprs) 1864 : Expr(OffsetOfExprClass, EmptyShell()), 1865 TSInfo(0), NumComps(numComps), NumExprs(numExprs) {} 1866 1867public: 1868 1869 static OffsetOfExpr *Create(const ASTContext &C, QualType type, 1870 SourceLocation OperatorLoc, TypeSourceInfo *tsi, 1871 ArrayRef<OffsetOfNode> comps, 1872 ArrayRef<Expr*> exprs, SourceLocation RParenLoc); 1873 1874 static OffsetOfExpr *CreateEmpty(const ASTContext &C, 1875 unsigned NumComps, unsigned NumExprs); 1876 1877 /// getOperatorLoc - Return the location of the operator. 1878 SourceLocation getOperatorLoc() const { return OperatorLoc; } 1879 void setOperatorLoc(SourceLocation L) { OperatorLoc = L; } 1880 1881 /// \brief Return the location of the right parentheses. 1882 SourceLocation getRParenLoc() const { return RParenLoc; } 1883 void setRParenLoc(SourceLocation R) { RParenLoc = R; } 1884 1885 TypeSourceInfo *getTypeSourceInfo() const { 1886 return TSInfo; 1887 } 1888 void setTypeSourceInfo(TypeSourceInfo *tsi) { 1889 TSInfo = tsi; 1890 } 1891 1892 const OffsetOfNode &getComponent(unsigned Idx) const { 1893 assert(Idx < NumComps && "Subscript out of range"); 1894 return reinterpret_cast<const OffsetOfNode *> (this + 1)[Idx]; 1895 } 1896 1897 void setComponent(unsigned Idx, OffsetOfNode ON) { 1898 assert(Idx < NumComps && "Subscript out of range"); 1899 reinterpret_cast<OffsetOfNode *> (this + 1)[Idx] = ON; 1900 } 1901 1902 unsigned getNumComponents() const { 1903 return NumComps; 1904 } 1905 1906 Expr* getIndexExpr(unsigned Idx) { 1907 assert(Idx < NumExprs && "Subscript out of range"); 1908 return reinterpret_cast<Expr **>( 1909 reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx]; 1910 } 1911 const Expr *getIndexExpr(unsigned Idx) const { 1912 return const_cast<OffsetOfExpr*>(this)->getIndexExpr(Idx); 1913 } 1914 1915 void setIndexExpr(unsigned Idx, Expr* E) { 1916 assert(Idx < NumComps && "Subscript out of range"); 1917 reinterpret_cast<Expr **>( 1918 reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx] = E; 1919 } 1920 1921 unsigned getNumExpressions() const { 1922 return NumExprs; 1923 } 1924 1925 SourceLocation getLocStart() const LLVM_READONLY { return OperatorLoc; } 1926 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } 1927 1928 static bool classof(const Stmt *T) { 1929 return T->getStmtClass() == OffsetOfExprClass; 1930 } 1931 1932 // Iterators 1933 child_range children() { 1934 Stmt **begin = 1935 reinterpret_cast<Stmt**>(reinterpret_cast<OffsetOfNode*>(this + 1) 1936 + NumComps); 1937 return child_range(begin, begin + NumExprs); 1938 } 1939}; 1940 1941/// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) 1942/// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and 1943/// vec_step (OpenCL 1.1 6.11.12). 1944class UnaryExprOrTypeTraitExpr : public Expr { 1945 union { 1946 TypeSourceInfo *Ty; 1947 Stmt *Ex; 1948 } Argument; 1949 SourceLocation OpLoc, RParenLoc; 1950 1951public: 1952 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo, 1953 QualType resultType, SourceLocation op, 1954 SourceLocation rp) : 1955 Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary, 1956 false, // Never type-dependent (C++ [temp.dep.expr]p3). 1957 // Value-dependent if the argument is type-dependent. 1958 TInfo->getType()->isDependentType(), 1959 TInfo->getType()->isInstantiationDependentType(), 1960 TInfo->getType()->containsUnexpandedParameterPack()), 1961 OpLoc(op), RParenLoc(rp) { 1962 UnaryExprOrTypeTraitExprBits.Kind = ExprKind; 1963 UnaryExprOrTypeTraitExprBits.IsType = true; 1964 Argument.Ty = TInfo; 1965 } 1966 1967 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E, 1968 QualType resultType, SourceLocation op, 1969 SourceLocation rp) : 1970 Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary, 1971 false, // Never type-dependent (C++ [temp.dep.expr]p3). 1972 // Value-dependent if the argument is type-dependent. 1973 E->isTypeDependent(), 1974 E->isInstantiationDependent(), 1975 E->containsUnexpandedParameterPack()), 1976 OpLoc(op), RParenLoc(rp) { 1977 UnaryExprOrTypeTraitExprBits.Kind = ExprKind; 1978 UnaryExprOrTypeTraitExprBits.IsType = false; 1979 Argument.Ex = E; 1980 } 1981 1982 /// \brief Construct an empty sizeof/alignof expression. 1983 explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty) 1984 : Expr(UnaryExprOrTypeTraitExprClass, Empty) { } 1985 1986 UnaryExprOrTypeTrait getKind() const { 1987 return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind); 1988 } 1989 void setKind(UnaryExprOrTypeTrait K) { UnaryExprOrTypeTraitExprBits.Kind = K;} 1990 1991 bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; } 1992 QualType getArgumentType() const { 1993 return getArgumentTypeInfo()->getType(); 1994 } 1995 TypeSourceInfo *getArgumentTypeInfo() const { 1996 assert(isArgumentType() && "calling getArgumentType() when arg is expr"); 1997 return Argument.Ty; 1998 } 1999 Expr *getArgumentExpr() { 2000 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type"); 2001 return static_cast<Expr*>(Argument.Ex); 2002 } 2003 const Expr *getArgumentExpr() const { 2004 return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr(); 2005 } 2006 2007 void setArgument(Expr *E) { 2008 Argument.Ex = E; 2009 UnaryExprOrTypeTraitExprBits.IsType = false; 2010 } 2011 void setArgument(TypeSourceInfo *TInfo) { 2012 Argument.Ty = TInfo; 2013 UnaryExprOrTypeTraitExprBits.IsType = true; 2014 } 2015 2016 /// Gets the argument type, or the type of the argument expression, whichever 2017 /// is appropriate. 2018 QualType getTypeOfArgument() const { 2019 return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType(); 2020 } 2021 2022 SourceLocation getOperatorLoc() const { return OpLoc; } 2023 void setOperatorLoc(SourceLocation L) { OpLoc = L; } 2024 2025 SourceLocation getRParenLoc() const { return RParenLoc; } 2026 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 2027 2028 SourceLocation getLocStart() const LLVM_READONLY { return OpLoc; } 2029 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } 2030 2031 static bool classof(const Stmt *T) { 2032 return T->getStmtClass() == UnaryExprOrTypeTraitExprClass; 2033 } 2034 2035 // Iterators 2036 child_range children(); 2037}; 2038 2039//===----------------------------------------------------------------------===// 2040// Postfix Operators. 2041//===----------------------------------------------------------------------===// 2042 2043/// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting. 2044class ArraySubscriptExpr : public Expr { 2045 enum { LHS, RHS, END_EXPR=2 }; 2046 Stmt* SubExprs[END_EXPR]; 2047 SourceLocation RBracketLoc; 2048public: 2049 ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t, 2050 ExprValueKind VK, ExprObjectKind OK, 2051 SourceLocation rbracketloc) 2052 : Expr(ArraySubscriptExprClass, t, VK, OK, 2053 lhs->isTypeDependent() || rhs->isTypeDependent(), 2054 lhs->isValueDependent() || rhs->isValueDependent(), 2055 (lhs->isInstantiationDependent() || 2056 rhs->isInstantiationDependent()), 2057 (lhs->containsUnexpandedParameterPack() || 2058 rhs->containsUnexpandedParameterPack())), 2059 RBracketLoc(rbracketloc) { 2060 SubExprs[LHS] = lhs; 2061 SubExprs[RHS] = rhs; 2062 } 2063 2064 /// \brief Create an empty array subscript expression. 2065 explicit ArraySubscriptExpr(EmptyShell Shell) 2066 : Expr(ArraySubscriptExprClass, Shell) { } 2067 2068 /// An array access can be written A[4] or 4[A] (both are equivalent). 2069 /// - getBase() and getIdx() always present the normalized view: A[4]. 2070 /// In this case getBase() returns "A" and getIdx() returns "4". 2071 /// - getLHS() and getRHS() present the syntactic view. e.g. for 2072 /// 4[A] getLHS() returns "4". 2073 /// Note: Because vector element access is also written A[4] we must 2074 /// predicate the format conversion in getBase and getIdx only on the 2075 /// the type of the RHS, as it is possible for the LHS to be a vector of 2076 /// integer type 2077 Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); } 2078 const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } 2079 void setLHS(Expr *E) { SubExprs[LHS] = E; } 2080 2081 Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); } 2082 const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } 2083 void setRHS(Expr *E) { SubExprs[RHS] = E; } 2084 2085 Expr *getBase() { 2086 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS()); 2087 } 2088 2089 const Expr *getBase() const { 2090 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS()); 2091 } 2092 2093 Expr *getIdx() { 2094 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS()); 2095 } 2096 2097 const Expr *getIdx() const { 2098 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS()); 2099 } 2100 2101 SourceLocation getLocStart() const LLVM_READONLY { 2102 return getLHS()->getLocStart(); 2103 } 2104 SourceLocation getLocEnd() const LLVM_READONLY { return RBracketLoc; } 2105 2106 SourceLocation getRBracketLoc() const { return RBracketLoc; } 2107 void setRBracketLoc(SourceLocation L) { RBracketLoc = L; } 2108 2109 SourceLocation getExprLoc() const LLVM_READONLY { 2110 return getBase()->getExprLoc(); 2111 } 2112 2113 static bool classof(const Stmt *T) { 2114 return T->getStmtClass() == ArraySubscriptExprClass; 2115 } 2116 2117 // Iterators 2118 child_range children() { 2119 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); 2120 } 2121}; 2122 2123 2124/// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]). 2125/// CallExpr itself represents a normal function call, e.g., "f(x, 2)", 2126/// while its subclasses may represent alternative syntax that (semantically) 2127/// results in a function call. For example, CXXOperatorCallExpr is 2128/// a subclass for overloaded operator calls that use operator syntax, e.g., 2129/// "str1 + str2" to resolve to a function call. 2130class CallExpr : public Expr { 2131 enum { FN=0, PREARGS_START=1 }; 2132 Stmt **SubExprs; 2133 unsigned NumArgs; 2134 SourceLocation RParenLoc; 2135 2136protected: 2137 // These versions of the constructor are for derived classes. 2138 CallExpr(const ASTContext& C, StmtClass SC, Expr *fn, unsigned NumPreArgs, 2139 ArrayRef<Expr*> args, QualType t, ExprValueKind VK, 2140 SourceLocation rparenloc); 2141 CallExpr(const ASTContext &C, StmtClass SC, unsigned NumPreArgs, 2142 EmptyShell Empty); 2143 2144 Stmt *getPreArg(unsigned i) { 2145 assert(i < getNumPreArgs() && "Prearg access out of range!"); 2146 return SubExprs[PREARGS_START+i]; 2147 } 2148 const Stmt *getPreArg(unsigned i) const { 2149 assert(i < getNumPreArgs() && "Prearg access out of range!"); 2150 return SubExprs[PREARGS_START+i]; 2151 } 2152 void setPreArg(unsigned i, Stmt *PreArg) { 2153 assert(i < getNumPreArgs() && "Prearg access out of range!"); 2154 SubExprs[PREARGS_START+i] = PreArg; 2155 } 2156 2157 unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; } 2158 2159public: 2160 CallExpr(const ASTContext& C, Expr *fn, ArrayRef<Expr*> args, QualType t, 2161 ExprValueKind VK, SourceLocation rparenloc); 2162 2163 /// \brief Build an empty call expression. 2164 CallExpr(const ASTContext &C, StmtClass SC, EmptyShell Empty); 2165 2166 const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); } 2167 Expr *getCallee() { return cast<Expr>(SubExprs[FN]); } 2168 void setCallee(Expr *F) { SubExprs[FN] = F; } 2169 2170 Decl *getCalleeDecl(); 2171 const Decl *getCalleeDecl() const { 2172 return const_cast<CallExpr*>(this)->getCalleeDecl(); 2173 } 2174 2175 /// \brief If the callee is a FunctionDecl, return it. Otherwise return 0. 2176 FunctionDecl *getDirectCallee(); 2177 const FunctionDecl *getDirectCallee() const { 2178 return const_cast<CallExpr*>(this)->getDirectCallee(); 2179 } 2180 2181 /// getNumArgs - Return the number of actual arguments to this call. 2182 /// 2183 unsigned getNumArgs() const { return NumArgs; } 2184 2185 /// \brief Retrieve the call arguments. 2186 Expr **getArgs() { 2187 return reinterpret_cast<Expr **>(SubExprs+getNumPreArgs()+PREARGS_START); 2188 } 2189 const Expr *const *getArgs() const { 2190 return const_cast<CallExpr*>(this)->getArgs(); 2191 } 2192 2193 /// getArg - Return the specified argument. 2194 Expr *getArg(unsigned Arg) { 2195 assert(Arg < NumArgs && "Arg access out of range!"); 2196 return cast<Expr>(SubExprs[Arg+getNumPreArgs()+PREARGS_START]); 2197 } 2198 const Expr *getArg(unsigned Arg) const { 2199 assert(Arg < NumArgs && "Arg access out of range!"); 2200 return cast<Expr>(SubExprs[Arg+getNumPreArgs()+PREARGS_START]); 2201 } 2202 2203 /// setArg - Set the specified argument. 2204 void setArg(unsigned Arg, Expr *ArgExpr) { 2205 assert(Arg < NumArgs && "Arg access out of range!"); 2206 SubExprs[Arg+getNumPreArgs()+PREARGS_START] = ArgExpr; 2207 } 2208 2209 /// setNumArgs - This changes the number of arguments present in this call. 2210 /// Any orphaned expressions are deleted by this, and any new operands are set 2211 /// to null. 2212 void setNumArgs(const ASTContext& C, unsigned NumArgs); 2213 2214 typedef ExprIterator arg_iterator; 2215 typedef ConstExprIterator const_arg_iterator; 2216 2217 arg_iterator arg_begin() { return SubExprs+PREARGS_START+getNumPreArgs(); } 2218 arg_iterator arg_end() { 2219 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs(); 2220 } 2221 const_arg_iterator arg_begin() const { 2222 return SubExprs+PREARGS_START+getNumPreArgs(); 2223 } 2224 const_arg_iterator arg_end() const { 2225 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs(); 2226 } 2227 2228 /// This method provides fast access to all the subexpressions of 2229 /// a CallExpr without going through the slower virtual child_iterator 2230 /// interface. This provides efficient reverse iteration of the 2231 /// subexpressions. This is currently used for CFG construction. 2232 ArrayRef<Stmt*> getRawSubExprs() { 2233 return ArrayRef<Stmt*>(SubExprs, 2234 getNumPreArgs() + PREARGS_START + getNumArgs()); 2235 } 2236 2237 /// getNumCommas - Return the number of commas that must have been present in 2238 /// this function call. 2239 unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; } 2240 2241 /// isBuiltinCall - If this is a call to a builtin, return the builtin ID. If 2242 /// not, return 0. 2243 unsigned isBuiltinCall() const; 2244 2245 /// \brief Returns \c true if this is a call to a builtin which does not 2246 /// evaluate side-effects within its arguments. 2247 bool isUnevaluatedBuiltinCall(ASTContext &Ctx) const; 2248 2249 /// getCallReturnType - Get the return type of the call expr. This is not 2250 /// always the type of the expr itself, if the return type is a reference 2251 /// type. 2252 QualType getCallReturnType() const; 2253 2254 SourceLocation getRParenLoc() const { return RParenLoc; } 2255 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 2256 2257 SourceLocation getLocStart() const LLVM_READONLY; 2258 SourceLocation getLocEnd() const LLVM_READONLY; 2259 2260 static bool classof(const Stmt *T) { 2261 return T->getStmtClass() >= firstCallExprConstant && 2262 T->getStmtClass() <= lastCallExprConstant; 2263 } 2264 2265 // Iterators 2266 child_range children() { 2267 return child_range(&SubExprs[0], 2268 &SubExprs[0]+NumArgs+getNumPreArgs()+PREARGS_START); 2269 } 2270}; 2271 2272/// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F. 2273/// 2274class MemberExpr : public Expr { 2275 /// Extra data stored in some member expressions. 2276 struct MemberNameQualifier { 2277 /// \brief The nested-name-specifier that qualifies the name, including 2278 /// source-location information. 2279 NestedNameSpecifierLoc QualifierLoc; 2280 2281 /// \brief The DeclAccessPair through which the MemberDecl was found due to 2282 /// name qualifiers. 2283 DeclAccessPair FoundDecl; 2284 }; 2285 2286 /// Base - the expression for the base pointer or structure references. In 2287 /// X.F, this is "X". 2288 Stmt *Base; 2289 2290 /// MemberDecl - This is the decl being referenced by the field/member name. 2291 /// In X.F, this is the decl referenced by F. 2292 ValueDecl *MemberDecl; 2293 2294 /// MemberDNLoc - Provides source/type location info for the 2295 /// declaration name embedded in MemberDecl. 2296 DeclarationNameLoc MemberDNLoc; 2297 2298 /// MemberLoc - This is the location of the member name. 2299 SourceLocation MemberLoc; 2300 2301 /// IsArrow - True if this is "X->F", false if this is "X.F". 2302 bool IsArrow : 1; 2303 2304 /// \brief True if this member expression used a nested-name-specifier to 2305 /// refer to the member, e.g., "x->Base::f", or found its member via a using 2306 /// declaration. When true, a MemberNameQualifier 2307 /// structure is allocated immediately after the MemberExpr. 2308 bool HasQualifierOrFoundDecl : 1; 2309 2310 /// \brief True if this member expression specified a template keyword 2311 /// and/or a template argument list explicitly, e.g., x->f<int>, 2312 /// x->template f, x->template f<int>. 2313 /// When true, an ASTTemplateKWAndArgsInfo structure and its 2314 /// TemplateArguments (if any) are allocated immediately after 2315 /// the MemberExpr or, if the member expression also has a qualifier, 2316 /// after the MemberNameQualifier structure. 2317 bool HasTemplateKWAndArgsInfo : 1; 2318 2319 /// \brief True if this member expression refers to a method that 2320 /// was resolved from an overloaded set having size greater than 1. 2321 bool HadMultipleCandidates : 1; 2322 2323 /// \brief Retrieve the qualifier that preceded the member name, if any. 2324 MemberNameQualifier *getMemberQualifier() { 2325 assert(HasQualifierOrFoundDecl); 2326 return reinterpret_cast<MemberNameQualifier *> (this + 1); 2327 } 2328 2329 /// \brief Retrieve the qualifier that preceded the member name, if any. 2330 const MemberNameQualifier *getMemberQualifier() const { 2331 return const_cast<MemberExpr *>(this)->getMemberQualifier(); 2332 } 2333 2334public: 2335 MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl, 2336 const DeclarationNameInfo &NameInfo, QualType ty, 2337 ExprValueKind VK, ExprObjectKind OK) 2338 : Expr(MemberExprClass, ty, VK, OK, 2339 base->isTypeDependent(), 2340 base->isValueDependent(), 2341 base->isInstantiationDependent(), 2342 base->containsUnexpandedParameterPack()), 2343 Base(base), MemberDecl(memberdecl), MemberDNLoc(NameInfo.getInfo()), 2344 MemberLoc(NameInfo.getLoc()), IsArrow(isarrow), 2345 HasQualifierOrFoundDecl(false), HasTemplateKWAndArgsInfo(false), 2346 HadMultipleCandidates(false) { 2347 assert(memberdecl->getDeclName() == NameInfo.getName()); 2348 } 2349 2350 // NOTE: this constructor should be used only when it is known that 2351 // the member name can not provide additional syntactic info 2352 // (i.e., source locations for C++ operator names or type source info 2353 // for constructors, destructors and conversion operators). 2354 MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl, 2355 SourceLocation l, QualType ty, 2356 ExprValueKind VK, ExprObjectKind OK) 2357 : Expr(MemberExprClass, ty, VK, OK, 2358 base->isTypeDependent(), base->isValueDependent(), 2359 base->isInstantiationDependent(), 2360 base->containsUnexpandedParameterPack()), 2361 Base(base), MemberDecl(memberdecl), MemberDNLoc(), MemberLoc(l), 2362 IsArrow(isarrow), 2363 HasQualifierOrFoundDecl(false), HasTemplateKWAndArgsInfo(false), 2364 HadMultipleCandidates(false) {} 2365 2366 static MemberExpr *Create(const ASTContext &C, Expr *base, bool isarrow, 2367 NestedNameSpecifierLoc QualifierLoc, 2368 SourceLocation TemplateKWLoc, 2369 ValueDecl *memberdecl, DeclAccessPair founddecl, 2370 DeclarationNameInfo MemberNameInfo, 2371 const TemplateArgumentListInfo *targs, 2372 QualType ty, ExprValueKind VK, ExprObjectKind OK); 2373 2374 void setBase(Expr *E) { Base = E; } 2375 Expr *getBase() const { return cast<Expr>(Base); } 2376 2377 /// \brief Retrieve the member declaration to which this expression refers. 2378 /// 2379 /// The returned declaration will either be a FieldDecl or (in C++) 2380 /// a CXXMethodDecl. 2381 ValueDecl *getMemberDecl() const { return MemberDecl; } 2382 void setMemberDecl(ValueDecl *D) { MemberDecl = D; } 2383 2384 /// \brief Retrieves the declaration found by lookup. 2385 DeclAccessPair getFoundDecl() const { 2386 if (!HasQualifierOrFoundDecl) 2387 return DeclAccessPair::make(getMemberDecl(), 2388 getMemberDecl()->getAccess()); 2389 return getMemberQualifier()->FoundDecl; 2390 } 2391 2392 /// \brief Determines whether this member expression actually had 2393 /// a C++ nested-name-specifier prior to the name of the member, e.g., 2394 /// x->Base::foo. 2395 bool hasQualifier() const { return getQualifier() != 0; } 2396 2397 /// \brief If the member name was qualified, retrieves the 2398 /// nested-name-specifier that precedes the member name. Otherwise, returns 2399 /// NULL. 2400 NestedNameSpecifier *getQualifier() const { 2401 if (!HasQualifierOrFoundDecl) 2402 return 0; 2403 2404 return getMemberQualifier()->QualifierLoc.getNestedNameSpecifier(); 2405 } 2406 2407 /// \brief If the member name was qualified, retrieves the 2408 /// nested-name-specifier that precedes the member name, with source-location 2409 /// information. 2410 NestedNameSpecifierLoc getQualifierLoc() const { 2411 if (!hasQualifier()) 2412 return NestedNameSpecifierLoc(); 2413 2414 return getMemberQualifier()->QualifierLoc; 2415 } 2416 2417 /// \brief Return the optional template keyword and arguments info. 2418 ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() { 2419 if (!HasTemplateKWAndArgsInfo) 2420 return 0; 2421 2422 if (!HasQualifierOrFoundDecl) 2423 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(this + 1); 2424 2425 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>( 2426 getMemberQualifier() + 1); 2427 } 2428 2429 /// \brief Return the optional template keyword and arguments info. 2430 const ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() const { 2431 return const_cast<MemberExpr*>(this)->getTemplateKWAndArgsInfo(); 2432 } 2433 2434 /// \brief Retrieve the location of the template keyword preceding 2435 /// the member name, if any. 2436 SourceLocation getTemplateKeywordLoc() const { 2437 if (!HasTemplateKWAndArgsInfo) return SourceLocation(); 2438 return getTemplateKWAndArgsInfo()->getTemplateKeywordLoc(); 2439 } 2440 2441 /// \brief Retrieve the location of the left angle bracket starting the 2442 /// explicit template argument list following the member name, if any. 2443 SourceLocation getLAngleLoc() const { 2444 if (!HasTemplateKWAndArgsInfo) return SourceLocation(); 2445 return getTemplateKWAndArgsInfo()->LAngleLoc; 2446 } 2447 2448 /// \brief Retrieve the location of the right angle bracket ending the 2449 /// explicit template argument list following the member name, if any. 2450 SourceLocation getRAngleLoc() const { 2451 if (!HasTemplateKWAndArgsInfo) return SourceLocation(); 2452 return getTemplateKWAndArgsInfo()->RAngleLoc; 2453 } 2454 2455 /// Determines whether the member name was preceded by the template keyword. 2456 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); } 2457 2458 /// \brief Determines whether the member name was followed by an 2459 /// explicit template argument list. 2460 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); } 2461 2462 /// \brief Copies the template arguments (if present) into the given 2463 /// structure. 2464 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const { 2465 if (hasExplicitTemplateArgs()) 2466 getExplicitTemplateArgs().copyInto(List); 2467 } 2468 2469 /// \brief Retrieve the explicit template argument list that 2470 /// follow the member template name. This must only be called on an 2471 /// expression with explicit template arguments. 2472 ASTTemplateArgumentListInfo &getExplicitTemplateArgs() { 2473 assert(hasExplicitTemplateArgs()); 2474 return *getTemplateKWAndArgsInfo(); 2475 } 2476 2477 /// \brief Retrieve the explicit template argument list that 2478 /// followed the member template name. This must only be called on 2479 /// an expression with explicit template arguments. 2480 const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const { 2481 return const_cast<MemberExpr *>(this)->getExplicitTemplateArgs(); 2482 } 2483 2484 /// \brief Retrieves the optional explicit template arguments. 2485 /// This points to the same data as getExplicitTemplateArgs(), but 2486 /// returns null if there are no explicit template arguments. 2487 const ASTTemplateArgumentListInfo *getOptionalExplicitTemplateArgs() const { 2488 if (!hasExplicitTemplateArgs()) return 0; 2489 return &getExplicitTemplateArgs(); 2490 } 2491 2492 /// \brief Retrieve the template arguments provided as part of this 2493 /// template-id. 2494 const TemplateArgumentLoc *getTemplateArgs() const { 2495 if (!hasExplicitTemplateArgs()) 2496 return 0; 2497 2498 return getExplicitTemplateArgs().getTemplateArgs(); 2499 } 2500 2501 /// \brief Retrieve the number of template arguments provided as part of this 2502 /// template-id. 2503 unsigned getNumTemplateArgs() const { 2504 if (!hasExplicitTemplateArgs()) 2505 return 0; 2506 2507 return getExplicitTemplateArgs().NumTemplateArgs; 2508 } 2509 2510 /// \brief Retrieve the member declaration name info. 2511 DeclarationNameInfo getMemberNameInfo() const { 2512 return DeclarationNameInfo(MemberDecl->getDeclName(), 2513 MemberLoc, MemberDNLoc); 2514 } 2515 2516 bool isArrow() const { return IsArrow; } 2517 void setArrow(bool A) { IsArrow = A; } 2518 2519 /// getMemberLoc - Return the location of the "member", in X->F, it is the 2520 /// location of 'F'. 2521 SourceLocation getMemberLoc() const { return MemberLoc; } 2522 void setMemberLoc(SourceLocation L) { MemberLoc = L; } 2523 2524 SourceLocation getLocStart() const LLVM_READONLY; 2525 SourceLocation getLocEnd() const LLVM_READONLY; 2526 2527 SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; } 2528 2529 /// \brief Determine whether the base of this explicit is implicit. 2530 bool isImplicitAccess() const { 2531 return getBase() && getBase()->isImplicitCXXThis(); 2532 } 2533 2534 /// \brief Returns true if this member expression refers to a method that 2535 /// was resolved from an overloaded set having size greater than 1. 2536 bool hadMultipleCandidates() const { 2537 return HadMultipleCandidates; 2538 } 2539 /// \brief Sets the flag telling whether this expression refers to 2540 /// a method that was resolved from an overloaded set having size 2541 /// greater than 1. 2542 void setHadMultipleCandidates(bool V = true) { 2543 HadMultipleCandidates = V; 2544 } 2545 2546 static bool classof(const Stmt *T) { 2547 return T->getStmtClass() == MemberExprClass; 2548 } 2549 2550 // Iterators 2551 child_range children() { return child_range(&Base, &Base+1); } 2552 2553 friend class ASTReader; 2554 friend class ASTStmtWriter; 2555}; 2556 2557/// CompoundLiteralExpr - [C99 6.5.2.5] 2558/// 2559class CompoundLiteralExpr : public Expr { 2560 /// LParenLoc - If non-null, this is the location of the left paren in a 2561 /// compound literal like "(int){4}". This can be null if this is a 2562 /// synthesized compound expression. 2563 SourceLocation LParenLoc; 2564 2565 /// The type as written. This can be an incomplete array type, in 2566 /// which case the actual expression type will be different. 2567 /// The int part of the pair stores whether this expr is file scope. 2568 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope; 2569 Stmt *Init; 2570public: 2571 CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo, 2572 QualType T, ExprValueKind VK, Expr *init, bool fileScope) 2573 : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary, 2574 tinfo->getType()->isDependentType(), 2575 init->isValueDependent(), 2576 (init->isInstantiationDependent() || 2577 tinfo->getType()->isInstantiationDependentType()), 2578 init->containsUnexpandedParameterPack()), 2579 LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {} 2580 2581 /// \brief Construct an empty compound literal. 2582 explicit CompoundLiteralExpr(EmptyShell Empty) 2583 : Expr(CompoundLiteralExprClass, Empty) { } 2584 2585 const Expr *getInitializer() const { return cast<Expr>(Init); } 2586 Expr *getInitializer() { return cast<Expr>(Init); } 2587 void setInitializer(Expr *E) { Init = E; } 2588 2589 bool isFileScope() const { return TInfoAndScope.getInt(); } 2590 void setFileScope(bool FS) { TInfoAndScope.setInt(FS); } 2591 2592 SourceLocation getLParenLoc() const { return LParenLoc; } 2593 void setLParenLoc(SourceLocation L) { LParenLoc = L; } 2594 2595 TypeSourceInfo *getTypeSourceInfo() const { 2596 return TInfoAndScope.getPointer(); 2597 } 2598 void setTypeSourceInfo(TypeSourceInfo *tinfo) { 2599 TInfoAndScope.setPointer(tinfo); 2600 } 2601 2602 SourceLocation getLocStart() const LLVM_READONLY { 2603 // FIXME: Init should never be null. 2604 if (!Init) 2605 return SourceLocation(); 2606 if (LParenLoc.isInvalid()) 2607 return Init->getLocStart(); 2608 return LParenLoc; 2609 } 2610 SourceLocation getLocEnd() const LLVM_READONLY { 2611 // FIXME: Init should never be null. 2612 if (!Init) 2613 return SourceLocation(); 2614 return Init->getLocEnd(); 2615 } 2616 2617 static bool classof(const Stmt *T) { 2618 return T->getStmtClass() == CompoundLiteralExprClass; 2619 } 2620 2621 // Iterators 2622 child_range children() { return child_range(&Init, &Init+1); } 2623}; 2624 2625/// CastExpr - Base class for type casts, including both implicit 2626/// casts (ImplicitCastExpr) and explicit casts that have some 2627/// representation in the source code (ExplicitCastExpr's derived 2628/// classes). 2629class CastExpr : public Expr { 2630public: 2631 typedef clang::CastKind CastKind; 2632 2633private: 2634 Stmt *Op; 2635 2636 void CheckCastConsistency() const; 2637 2638 const CXXBaseSpecifier * const *path_buffer() const { 2639 return const_cast<CastExpr*>(this)->path_buffer(); 2640 } 2641 CXXBaseSpecifier **path_buffer(); 2642 2643 void setBasePathSize(unsigned basePathSize) { 2644 CastExprBits.BasePathSize = basePathSize; 2645 assert(CastExprBits.BasePathSize == basePathSize && 2646 "basePathSize doesn't fit in bits of CastExprBits.BasePathSize!"); 2647 } 2648 2649protected: 2650 CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, 2651 const CastKind kind, Expr *op, unsigned BasePathSize) : 2652 Expr(SC, ty, VK, OK_Ordinary, 2653 // Cast expressions are type-dependent if the type is 2654 // dependent (C++ [temp.dep.expr]p3). 2655 ty->isDependentType(), 2656 // Cast expressions are value-dependent if the type is 2657 // dependent or if the subexpression is value-dependent. 2658 ty->isDependentType() || (op && op->isValueDependent()), 2659 (ty->isInstantiationDependentType() || 2660 (op && op->isInstantiationDependent())), 2661 (ty->containsUnexpandedParameterPack() || 2662 (op && op->containsUnexpandedParameterPack()))), 2663 Op(op) { 2664 assert(kind != CK_Invalid && "creating cast with invalid cast kind"); 2665 CastExprBits.Kind = kind; 2666 setBasePathSize(BasePathSize); 2667#ifndef NDEBUG 2668 CheckCastConsistency(); 2669#endif 2670 } 2671 2672 /// \brief Construct an empty cast. 2673 CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize) 2674 : Expr(SC, Empty) { 2675 setBasePathSize(BasePathSize); 2676 } 2677 2678public: 2679 CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; } 2680 void setCastKind(CastKind K) { CastExprBits.Kind = K; } 2681 const char *getCastKindName() const; 2682 2683 Expr *getSubExpr() { return cast<Expr>(Op); } 2684 const Expr *getSubExpr() const { return cast<Expr>(Op); } 2685 void setSubExpr(Expr *E) { Op = E; } 2686 2687 /// \brief Retrieve the cast subexpression as it was written in the source 2688 /// code, looking through any implicit casts or other intermediate nodes 2689 /// introduced by semantic analysis. 2690 Expr *getSubExprAsWritten(); 2691 const Expr *getSubExprAsWritten() const { 2692 return const_cast<CastExpr *>(this)->getSubExprAsWritten(); 2693 } 2694 2695 typedef CXXBaseSpecifier **path_iterator; 2696 typedef const CXXBaseSpecifier * const *path_const_iterator; 2697 bool path_empty() const { return CastExprBits.BasePathSize == 0; } 2698 unsigned path_size() const { return CastExprBits.BasePathSize; } 2699 path_iterator path_begin() { return path_buffer(); } 2700 path_iterator path_end() { return path_buffer() + path_size(); } 2701 path_const_iterator path_begin() const { return path_buffer(); } 2702 path_const_iterator path_end() const { return path_buffer() + path_size(); } 2703 2704 void setCastPath(const CXXCastPath &Path); 2705 2706 static bool classof(const Stmt *T) { 2707 return T->getStmtClass() >= firstCastExprConstant && 2708 T->getStmtClass() <= lastCastExprConstant; 2709 } 2710 2711 // Iterators 2712 child_range children() { return child_range(&Op, &Op+1); } 2713}; 2714 2715/// ImplicitCastExpr - Allows us to explicitly represent implicit type 2716/// conversions, which have no direct representation in the original 2717/// source code. For example: converting T[]->T*, void f()->void 2718/// (*f)(), float->double, short->int, etc. 2719/// 2720/// In C, implicit casts always produce rvalues. However, in C++, an 2721/// implicit cast whose result is being bound to a reference will be 2722/// an lvalue or xvalue. For example: 2723/// 2724/// @code 2725/// class Base { }; 2726/// class Derived : public Base { }; 2727/// Derived &&ref(); 2728/// void f(Derived d) { 2729/// Base& b = d; // initializer is an ImplicitCastExpr 2730/// // to an lvalue of type Base 2731/// Base&& r = ref(); // initializer is an ImplicitCastExpr 2732/// // to an xvalue of type Base 2733/// } 2734/// @endcode 2735class ImplicitCastExpr : public CastExpr { 2736private: 2737 ImplicitCastExpr(QualType ty, CastKind kind, Expr *op, 2738 unsigned BasePathLength, ExprValueKind VK) 2739 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) { 2740 } 2741 2742 /// \brief Construct an empty implicit cast. 2743 explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize) 2744 : CastExpr(ImplicitCastExprClass, Shell, PathSize) { } 2745 2746public: 2747 enum OnStack_t { OnStack }; 2748 ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op, 2749 ExprValueKind VK) 2750 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) { 2751 } 2752 2753 static ImplicitCastExpr *Create(const ASTContext &Context, QualType T, 2754 CastKind Kind, Expr *Operand, 2755 const CXXCastPath *BasePath, 2756 ExprValueKind Cat); 2757 2758 static ImplicitCastExpr *CreateEmpty(const ASTContext &Context, 2759 unsigned PathSize); 2760 2761 SourceLocation getLocStart() const LLVM_READONLY { 2762 return getSubExpr()->getLocStart(); 2763 } 2764 SourceLocation getLocEnd() const LLVM_READONLY { 2765 return getSubExpr()->getLocEnd(); 2766 } 2767 2768 static bool classof(const Stmt *T) { 2769 return T->getStmtClass() == ImplicitCastExprClass; 2770 } 2771}; 2772 2773inline Expr *Expr::IgnoreImpCasts() { 2774 Expr *e = this; 2775 while (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e)) 2776 e = ice->getSubExpr(); 2777 return e; 2778} 2779 2780/// ExplicitCastExpr - An explicit cast written in the source 2781/// code. 2782/// 2783/// This class is effectively an abstract class, because it provides 2784/// the basic representation of an explicitly-written cast without 2785/// specifying which kind of cast (C cast, functional cast, static 2786/// cast, etc.) was written; specific derived classes represent the 2787/// particular style of cast and its location information. 2788/// 2789/// Unlike implicit casts, explicit cast nodes have two different 2790/// types: the type that was written into the source code, and the 2791/// actual type of the expression as determined by semantic 2792/// analysis. These types may differ slightly. For example, in C++ one 2793/// can cast to a reference type, which indicates that the resulting 2794/// expression will be an lvalue or xvalue. The reference type, however, 2795/// will not be used as the type of the expression. 2796class ExplicitCastExpr : public CastExpr { 2797 /// TInfo - Source type info for the (written) type 2798 /// this expression is casting to. 2799 TypeSourceInfo *TInfo; 2800 2801protected: 2802 ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK, 2803 CastKind kind, Expr *op, unsigned PathSize, 2804 TypeSourceInfo *writtenTy) 2805 : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {} 2806 2807 /// \brief Construct an empty explicit cast. 2808 ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize) 2809 : CastExpr(SC, Shell, PathSize) { } 2810 2811public: 2812 /// getTypeInfoAsWritten - Returns the type source info for the type 2813 /// that this expression is casting to. 2814 TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; } 2815 void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; } 2816 2817 /// getTypeAsWritten - Returns the type that this expression is 2818 /// casting to, as written in the source code. 2819 QualType getTypeAsWritten() const { return TInfo->getType(); } 2820 2821 static bool classof(const Stmt *T) { 2822 return T->getStmtClass() >= firstExplicitCastExprConstant && 2823 T->getStmtClass() <= lastExplicitCastExprConstant; 2824 } 2825}; 2826 2827/// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style 2828/// cast in C++ (C++ [expr.cast]), which uses the syntax 2829/// (Type)expr. For example: @c (int)f. 2830class CStyleCastExpr : public ExplicitCastExpr { 2831 SourceLocation LPLoc; // the location of the left paren 2832 SourceLocation RPLoc; // the location of the right paren 2833 2834 CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op, 2835 unsigned PathSize, TypeSourceInfo *writtenTy, 2836 SourceLocation l, SourceLocation r) 2837 : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize, 2838 writtenTy), LPLoc(l), RPLoc(r) {} 2839 2840 /// \brief Construct an empty C-style explicit cast. 2841 explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize) 2842 : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { } 2843 2844public: 2845 static CStyleCastExpr *Create(const ASTContext &Context, QualType T, 2846 ExprValueKind VK, CastKind K, 2847 Expr *Op, const CXXCastPath *BasePath, 2848 TypeSourceInfo *WrittenTy, SourceLocation L, 2849 SourceLocation R); 2850 2851 static CStyleCastExpr *CreateEmpty(const ASTContext &Context, 2852 unsigned PathSize); 2853 2854 SourceLocation getLParenLoc() const { return LPLoc; } 2855 void setLParenLoc(SourceLocation L) { LPLoc = L; } 2856 2857 SourceLocation getRParenLoc() const { return RPLoc; } 2858 void setRParenLoc(SourceLocation L) { RPLoc = L; } 2859 2860 SourceLocation getLocStart() const LLVM_READONLY { return LPLoc; } 2861 SourceLocation getLocEnd() const LLVM_READONLY { 2862 return getSubExpr()->getLocEnd(); 2863 } 2864 2865 static bool classof(const Stmt *T) { 2866 return T->getStmtClass() == CStyleCastExprClass; 2867 } 2868}; 2869 2870/// \brief A builtin binary operation expression such as "x + y" or "x <= y". 2871/// 2872/// This expression node kind describes a builtin binary operation, 2873/// such as "x + y" for integer values "x" and "y". The operands will 2874/// already have been converted to appropriate types (e.g., by 2875/// performing promotions or conversions). 2876/// 2877/// In C++, where operators may be overloaded, a different kind of 2878/// expression node (CXXOperatorCallExpr) is used to express the 2879/// invocation of an overloaded operator with operator syntax. Within 2880/// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is 2881/// used to store an expression "x + y" depends on the subexpressions 2882/// for x and y. If neither x or y is type-dependent, and the "+" 2883/// operator resolves to a built-in operation, BinaryOperator will be 2884/// used to express the computation (x and y may still be 2885/// value-dependent). If either x or y is type-dependent, or if the 2886/// "+" resolves to an overloaded operator, CXXOperatorCallExpr will 2887/// be used to express the computation. 2888class BinaryOperator : public Expr { 2889public: 2890 typedef BinaryOperatorKind Opcode; 2891 2892private: 2893 unsigned Opc : 6; 2894 2895 // Records the FP_CONTRACT pragma status at the point that this binary 2896 // operator was parsed. This bit is only meaningful for operations on 2897 // floating point types. For all other types it should default to 2898 // false. 2899 unsigned FPContractable : 1; 2900 SourceLocation OpLoc; 2901 2902 enum { LHS, RHS, END_EXPR }; 2903 Stmt* SubExprs[END_EXPR]; 2904public: 2905 2906 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, 2907 ExprValueKind VK, ExprObjectKind OK, 2908 SourceLocation opLoc, bool fpContractable) 2909 : Expr(BinaryOperatorClass, ResTy, VK, OK, 2910 lhs->isTypeDependent() || rhs->isTypeDependent(), 2911 lhs->isValueDependent() || rhs->isValueDependent(), 2912 (lhs->isInstantiationDependent() || 2913 rhs->isInstantiationDependent()), 2914 (lhs->containsUnexpandedParameterPack() || 2915 rhs->containsUnexpandedParameterPack())), 2916 Opc(opc), FPContractable(fpContractable), OpLoc(opLoc) { 2917 SubExprs[LHS] = lhs; 2918 SubExprs[RHS] = rhs; 2919 assert(!isCompoundAssignmentOp() && 2920 "Use CompoundAssignOperator for compound assignments"); 2921 } 2922 2923 /// \brief Construct an empty binary operator. 2924 explicit BinaryOperator(EmptyShell Empty) 2925 : Expr(BinaryOperatorClass, Empty), Opc(BO_Comma) { } 2926 2927 SourceLocation getExprLoc() const LLVM_READONLY { return OpLoc; } 2928 SourceLocation getOperatorLoc() const { return OpLoc; } 2929 void setOperatorLoc(SourceLocation L) { OpLoc = L; } 2930 2931 Opcode getOpcode() const { return static_cast<Opcode>(Opc); } 2932 void setOpcode(Opcode O) { Opc = O; } 2933 2934 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } 2935 void setLHS(Expr *E) { SubExprs[LHS] = E; } 2936 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } 2937 void setRHS(Expr *E) { SubExprs[RHS] = E; } 2938 2939 SourceLocation getLocStart() const LLVM_READONLY { 2940 return getLHS()->getLocStart(); 2941 } 2942 SourceLocation getLocEnd() const LLVM_READONLY { 2943 return getRHS()->getLocEnd(); 2944 } 2945 2946 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it 2947 /// corresponds to, e.g. "<<=". 2948 static StringRef getOpcodeStr(Opcode Op); 2949 2950 StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); } 2951 2952 /// \brief Retrieve the binary opcode that corresponds to the given 2953 /// overloaded operator. 2954 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO); 2955 2956 /// \brief Retrieve the overloaded operator kind that corresponds to 2957 /// the given binary opcode. 2958 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc); 2959 2960 /// predicates to categorize the respective opcodes. 2961 bool isPtrMemOp() const { return Opc == BO_PtrMemD || Opc == BO_PtrMemI; } 2962 bool isMultiplicativeOp() const { return Opc >= BO_Mul && Opc <= BO_Rem; } 2963 static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; } 2964 bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); } 2965 static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; } 2966 bool isShiftOp() const { return isShiftOp(getOpcode()); } 2967 2968 static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; } 2969 bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); } 2970 2971 static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; } 2972 bool isRelationalOp() const { return isRelationalOp(getOpcode()); } 2973 2974 static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; } 2975 bool isEqualityOp() const { return isEqualityOp(getOpcode()); } 2976 2977 static bool isComparisonOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_NE; } 2978 bool isComparisonOp() const { return isComparisonOp(getOpcode()); } 2979 2980 static Opcode negateComparisonOp(Opcode Opc) { 2981 switch (Opc) { 2982 default: 2983 llvm_unreachable("Not a comparsion operator."); 2984 case BO_LT: return BO_GE; 2985 case BO_GT: return BO_LE; 2986 case BO_LE: return BO_GT; 2987 case BO_GE: return BO_LT; 2988 case BO_EQ: return BO_NE; 2989 case BO_NE: return BO_EQ; 2990 } 2991 } 2992 2993 static Opcode reverseComparisonOp(Opcode Opc) { 2994 switch (Opc) { 2995 default: 2996 llvm_unreachable("Not a comparsion operator."); 2997 case BO_LT: return BO_GT; 2998 case BO_GT: return BO_LT; 2999 case BO_LE: return BO_GE; 3000 case BO_GE: return BO_LE; 3001 case BO_EQ: 3002 case BO_NE: 3003 return Opc; 3004 } 3005 } 3006 3007 static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; } 3008 bool isLogicalOp() const { return isLogicalOp(getOpcode()); } 3009 3010 static bool isAssignmentOp(Opcode Opc) { 3011 return Opc >= BO_Assign && Opc <= BO_OrAssign; 3012 } 3013 bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); } 3014 3015 static bool isCompoundAssignmentOp(Opcode Opc) { 3016 return Opc > BO_Assign && Opc <= BO_OrAssign; 3017 } 3018 bool isCompoundAssignmentOp() const { 3019 return isCompoundAssignmentOp(getOpcode()); 3020 } 3021 static Opcode getOpForCompoundAssignment(Opcode Opc) { 3022 assert(isCompoundAssignmentOp(Opc)); 3023 if (Opc >= BO_AndAssign) 3024 return Opcode(unsigned(Opc) - BO_AndAssign + BO_And); 3025 else 3026 return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul); 3027 } 3028 3029 static bool isShiftAssignOp(Opcode Opc) { 3030 return Opc == BO_ShlAssign || Opc == BO_ShrAssign; 3031 } 3032 bool isShiftAssignOp() const { 3033 return isShiftAssignOp(getOpcode()); 3034 } 3035 3036 static bool classof(const Stmt *S) { 3037 return S->getStmtClass() >= firstBinaryOperatorConstant && 3038 S->getStmtClass() <= lastBinaryOperatorConstant; 3039 } 3040 3041 // Iterators 3042 child_range children() { 3043 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); 3044 } 3045 3046 // Set the FP contractability status of this operator. Only meaningful for 3047 // operations on floating point types. 3048 void setFPContractable(bool FPC) { FPContractable = FPC; } 3049 3050 // Get the FP contractability status of this operator. Only meaningful for 3051 // operations on floating point types. 3052 bool isFPContractable() const { return FPContractable; } 3053 3054protected: 3055 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, 3056 ExprValueKind VK, ExprObjectKind OK, 3057 SourceLocation opLoc, bool fpContractable, bool dead2) 3058 : Expr(CompoundAssignOperatorClass, ResTy, VK, OK, 3059 lhs->isTypeDependent() || rhs->isTypeDependent(), 3060 lhs->isValueDependent() || rhs->isValueDependent(), 3061 (lhs->isInstantiationDependent() || 3062 rhs->isInstantiationDependent()), 3063 (lhs->containsUnexpandedParameterPack() || 3064 rhs->containsUnexpandedParameterPack())), 3065 Opc(opc), FPContractable(fpContractable), OpLoc(opLoc) { 3066 SubExprs[LHS] = lhs; 3067 SubExprs[RHS] = rhs; 3068 } 3069 3070 BinaryOperator(StmtClass SC, EmptyShell Empty) 3071 : Expr(SC, Empty), Opc(BO_MulAssign) { } 3072}; 3073 3074/// CompoundAssignOperator - For compound assignments (e.g. +=), we keep 3075/// track of the type the operation is performed in. Due to the semantics of 3076/// these operators, the operands are promoted, the arithmetic performed, an 3077/// implicit conversion back to the result type done, then the assignment takes 3078/// place. This captures the intermediate type which the computation is done 3079/// in. 3080class CompoundAssignOperator : public BinaryOperator { 3081 QualType ComputationLHSType; 3082 QualType ComputationResultType; 3083public: 3084 CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResType, 3085 ExprValueKind VK, ExprObjectKind OK, 3086 QualType CompLHSType, QualType CompResultType, 3087 SourceLocation OpLoc, bool fpContractable) 3088 : BinaryOperator(lhs, rhs, opc, ResType, VK, OK, OpLoc, fpContractable, 3089 true), 3090 ComputationLHSType(CompLHSType), 3091 ComputationResultType(CompResultType) { 3092 assert(isCompoundAssignmentOp() && 3093 "Only should be used for compound assignments"); 3094 } 3095 3096 /// \brief Build an empty compound assignment operator expression. 3097 explicit CompoundAssignOperator(EmptyShell Empty) 3098 : BinaryOperator(CompoundAssignOperatorClass, Empty) { } 3099 3100 // The two computation types are the type the LHS is converted 3101 // to for the computation and the type of the result; the two are 3102 // distinct in a few cases (specifically, int+=ptr and ptr-=ptr). 3103 QualType getComputationLHSType() const { return ComputationLHSType; } 3104 void setComputationLHSType(QualType T) { ComputationLHSType = T; } 3105 3106 QualType getComputationResultType() const { return ComputationResultType; } 3107 void setComputationResultType(QualType T) { ComputationResultType = T; } 3108 3109 static bool classof(const Stmt *S) { 3110 return S->getStmtClass() == CompoundAssignOperatorClass; 3111 } 3112}; 3113 3114/// AbstractConditionalOperator - An abstract base class for 3115/// ConditionalOperator and BinaryConditionalOperator. 3116class AbstractConditionalOperator : public Expr { 3117 SourceLocation QuestionLoc, ColonLoc; 3118 friend class ASTStmtReader; 3119 3120protected: 3121 AbstractConditionalOperator(StmtClass SC, QualType T, 3122 ExprValueKind VK, ExprObjectKind OK, 3123 bool TD, bool VD, bool ID, 3124 bool ContainsUnexpandedParameterPack, 3125 SourceLocation qloc, 3126 SourceLocation cloc) 3127 : Expr(SC, T, VK, OK, TD, VD, ID, ContainsUnexpandedParameterPack), 3128 QuestionLoc(qloc), ColonLoc(cloc) {} 3129 3130 AbstractConditionalOperator(StmtClass SC, EmptyShell Empty) 3131 : Expr(SC, Empty) { } 3132 3133public: 3134 // getCond - Return the expression representing the condition for 3135 // the ?: operator. 3136 Expr *getCond() const; 3137 3138 // getTrueExpr - Return the subexpression representing the value of 3139 // the expression if the condition evaluates to true. 3140 Expr *getTrueExpr() const; 3141 3142 // getFalseExpr - Return the subexpression representing the value of 3143 // the expression if the condition evaluates to false. This is 3144 // the same as getRHS. 3145 Expr *getFalseExpr() const; 3146 3147 SourceLocation getQuestionLoc() const { return QuestionLoc; } 3148 SourceLocation getColonLoc() const { return ColonLoc; } 3149 3150 static bool classof(const Stmt *T) { 3151 return T->getStmtClass() == ConditionalOperatorClass || 3152 T->getStmtClass() == BinaryConditionalOperatorClass; 3153 } 3154}; 3155 3156/// ConditionalOperator - The ?: ternary operator. The GNU "missing 3157/// middle" extension is a BinaryConditionalOperator. 3158class ConditionalOperator : public AbstractConditionalOperator { 3159 enum { COND, LHS, RHS, END_EXPR }; 3160 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides. 3161 3162 friend class ASTStmtReader; 3163public: 3164 ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs, 3165 SourceLocation CLoc, Expr *rhs, 3166 QualType t, ExprValueKind VK, ExprObjectKind OK) 3167 : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK, 3168 // FIXME: the type of the conditional operator doesn't 3169 // depend on the type of the conditional, but the standard 3170 // seems to imply that it could. File a bug! 3171 (lhs->isTypeDependent() || rhs->isTypeDependent()), 3172 (cond->isValueDependent() || lhs->isValueDependent() || 3173 rhs->isValueDependent()), 3174 (cond->isInstantiationDependent() || 3175 lhs->isInstantiationDependent() || 3176 rhs->isInstantiationDependent()), 3177 (cond->containsUnexpandedParameterPack() || 3178 lhs->containsUnexpandedParameterPack() || 3179 rhs->containsUnexpandedParameterPack()), 3180 QLoc, CLoc) { 3181 SubExprs[COND] = cond; 3182 SubExprs[LHS] = lhs; 3183 SubExprs[RHS] = rhs; 3184 } 3185 3186 /// \brief Build an empty conditional operator. 3187 explicit ConditionalOperator(EmptyShell Empty) 3188 : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { } 3189 3190 // getCond - Return the expression representing the condition for 3191 // the ?: operator. 3192 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); } 3193 3194 // getTrueExpr - Return the subexpression representing the value of 3195 // the expression if the condition evaluates to true. 3196 Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); } 3197 3198 // getFalseExpr - Return the subexpression representing the value of 3199 // the expression if the condition evaluates to false. This is 3200 // the same as getRHS. 3201 Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); } 3202 3203 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } 3204 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } 3205 3206 SourceLocation getLocStart() const LLVM_READONLY { 3207 return getCond()->getLocStart(); 3208 } 3209 SourceLocation getLocEnd() const LLVM_READONLY { 3210 return getRHS()->getLocEnd(); 3211 } 3212 3213 static bool classof(const Stmt *T) { 3214 return T->getStmtClass() == ConditionalOperatorClass; 3215 } 3216 3217 // Iterators 3218 child_range children() { 3219 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); 3220 } 3221}; 3222 3223/// BinaryConditionalOperator - The GNU extension to the conditional 3224/// operator which allows the middle operand to be omitted. 3225/// 3226/// This is a different expression kind on the assumption that almost 3227/// every client ends up needing to know that these are different. 3228class BinaryConditionalOperator : public AbstractConditionalOperator { 3229 enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS }; 3230 3231 /// - the common condition/left-hand-side expression, which will be 3232 /// evaluated as the opaque value 3233 /// - the condition, expressed in terms of the opaque value 3234 /// - the left-hand-side, expressed in terms of the opaque value 3235 /// - the right-hand-side 3236 Stmt *SubExprs[NUM_SUBEXPRS]; 3237 OpaqueValueExpr *OpaqueValue; 3238 3239 friend class ASTStmtReader; 3240public: 3241 BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue, 3242 Expr *cond, Expr *lhs, Expr *rhs, 3243 SourceLocation qloc, SourceLocation cloc, 3244 QualType t, ExprValueKind VK, ExprObjectKind OK) 3245 : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK, 3246 (common->isTypeDependent() || rhs->isTypeDependent()), 3247 (common->isValueDependent() || rhs->isValueDependent()), 3248 (common->isInstantiationDependent() || 3249 rhs->isInstantiationDependent()), 3250 (common->containsUnexpandedParameterPack() || 3251 rhs->containsUnexpandedParameterPack()), 3252 qloc, cloc), 3253 OpaqueValue(opaqueValue) { 3254 SubExprs[COMMON] = common; 3255 SubExprs[COND] = cond; 3256 SubExprs[LHS] = lhs; 3257 SubExprs[RHS] = rhs; 3258 assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value"); 3259 } 3260 3261 /// \brief Build an empty conditional operator. 3262 explicit BinaryConditionalOperator(EmptyShell Empty) 3263 : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { } 3264 3265 /// \brief getCommon - Return the common expression, written to the 3266 /// left of the condition. The opaque value will be bound to the 3267 /// result of this expression. 3268 Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); } 3269 3270 /// \brief getOpaqueValue - Return the opaque value placeholder. 3271 OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; } 3272 3273 /// \brief getCond - Return the condition expression; this is defined 3274 /// in terms of the opaque value. 3275 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); } 3276 3277 /// \brief getTrueExpr - Return the subexpression which will be 3278 /// evaluated if the condition evaluates to true; this is defined 3279 /// in terms of the opaque value. 3280 Expr *getTrueExpr() const { 3281 return cast<Expr>(SubExprs[LHS]); 3282 } 3283 3284 /// \brief getFalseExpr - Return the subexpression which will be 3285 /// evaluated if the condnition evaluates to false; this is 3286 /// defined in terms of the opaque value. 3287 Expr *getFalseExpr() const { 3288 return cast<Expr>(SubExprs[RHS]); 3289 } 3290 3291 SourceLocation getLocStart() const LLVM_READONLY { 3292 return getCommon()->getLocStart(); 3293 } 3294 SourceLocation getLocEnd() const LLVM_READONLY { 3295 return getFalseExpr()->getLocEnd(); 3296 } 3297 3298 static bool classof(const Stmt *T) { 3299 return T->getStmtClass() == BinaryConditionalOperatorClass; 3300 } 3301 3302 // Iterators 3303 child_range children() { 3304 return child_range(SubExprs, SubExprs + NUM_SUBEXPRS); 3305 } 3306}; 3307 3308inline Expr *AbstractConditionalOperator::getCond() const { 3309 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this)) 3310 return co->getCond(); 3311 return cast<BinaryConditionalOperator>(this)->getCond(); 3312} 3313 3314inline Expr *AbstractConditionalOperator::getTrueExpr() const { 3315 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this)) 3316 return co->getTrueExpr(); 3317 return cast<BinaryConditionalOperator>(this)->getTrueExpr(); 3318} 3319 3320inline Expr *AbstractConditionalOperator::getFalseExpr() const { 3321 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this)) 3322 return co->getFalseExpr(); 3323 return cast<BinaryConditionalOperator>(this)->getFalseExpr(); 3324} 3325 3326/// AddrLabelExpr - The GNU address of label extension, representing &&label. 3327class AddrLabelExpr : public Expr { 3328 SourceLocation AmpAmpLoc, LabelLoc; 3329 LabelDecl *Label; 3330public: 3331 AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L, 3332 QualType t) 3333 : Expr(AddrLabelExprClass, t, VK_RValue, OK_Ordinary, false, false, false, 3334 false), 3335 AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {} 3336 3337 /// \brief Build an empty address of a label expression. 3338 explicit AddrLabelExpr(EmptyShell Empty) 3339 : Expr(AddrLabelExprClass, Empty) { } 3340 3341 SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; } 3342 void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; } 3343 SourceLocation getLabelLoc() const { return LabelLoc; } 3344 void setLabelLoc(SourceLocation L) { LabelLoc = L; } 3345 3346 SourceLocation getLocStart() const LLVM_READONLY { return AmpAmpLoc; } 3347 SourceLocation getLocEnd() const LLVM_READONLY { return LabelLoc; } 3348 3349 LabelDecl *getLabel() const { return Label; } 3350 void setLabel(LabelDecl *L) { Label = L; } 3351 3352 static bool classof(const Stmt *T) { 3353 return T->getStmtClass() == AddrLabelExprClass; 3354 } 3355 3356 // Iterators 3357 child_range children() { return child_range(); } 3358}; 3359 3360/// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}). 3361/// The StmtExpr contains a single CompoundStmt node, which it evaluates and 3362/// takes the value of the last subexpression. 3363/// 3364/// A StmtExpr is always an r-value; values "returned" out of a 3365/// StmtExpr will be copied. 3366class StmtExpr : public Expr { 3367 Stmt *SubStmt; 3368 SourceLocation LParenLoc, RParenLoc; 3369public: 3370 // FIXME: Does type-dependence need to be computed differently? 3371 // FIXME: Do we need to compute instantiation instantiation-dependence for 3372 // statements? (ugh!) 3373 StmtExpr(CompoundStmt *substmt, QualType T, 3374 SourceLocation lp, SourceLocation rp) : 3375 Expr(StmtExprClass, T, VK_RValue, OK_Ordinary, 3376 T->isDependentType(), false, false, false), 3377 SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { } 3378 3379 /// \brief Build an empty statement expression. 3380 explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { } 3381 3382 CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); } 3383 const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); } 3384 void setSubStmt(CompoundStmt *S) { SubStmt = S; } 3385 3386 SourceLocation getLocStart() const LLVM_READONLY { return LParenLoc; } 3387 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } 3388 3389 SourceLocation getLParenLoc() const { return LParenLoc; } 3390 void setLParenLoc(SourceLocation L) { LParenLoc = L; } 3391 SourceLocation getRParenLoc() const { return RParenLoc; } 3392 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 3393 3394 static bool classof(const Stmt *T) { 3395 return T->getStmtClass() == StmtExprClass; 3396 } 3397 3398 // Iterators 3399 child_range children() { return child_range(&SubStmt, &SubStmt+1); } 3400}; 3401 3402 3403/// ShuffleVectorExpr - clang-specific builtin-in function 3404/// __builtin_shufflevector. 3405/// This AST node represents a operator that does a constant 3406/// shuffle, similar to LLVM's shufflevector instruction. It takes 3407/// two vectors and a variable number of constant indices, 3408/// and returns the appropriately shuffled vector. 3409class ShuffleVectorExpr : public Expr { 3410 SourceLocation BuiltinLoc, RParenLoc; 3411 3412 // SubExprs - the list of values passed to the __builtin_shufflevector 3413 // function. The first two are vectors, and the rest are constant 3414 // indices. The number of values in this list is always 3415 // 2+the number of indices in the vector type. 3416 Stmt **SubExprs; 3417 unsigned NumExprs; 3418 3419public: 3420 ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args, QualType Type, 3421 SourceLocation BLoc, SourceLocation RP); 3422 3423 /// \brief Build an empty vector-shuffle expression. 3424 explicit ShuffleVectorExpr(EmptyShell Empty) 3425 : Expr(ShuffleVectorExprClass, Empty), SubExprs(0) { } 3426 3427 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 3428 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; } 3429 3430 SourceLocation getRParenLoc() const { return RParenLoc; } 3431 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 3432 3433 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; } 3434 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } 3435 3436 static bool classof(const Stmt *T) { 3437 return T->getStmtClass() == ShuffleVectorExprClass; 3438 } 3439 3440 /// getNumSubExprs - Return the size of the SubExprs array. This includes the 3441 /// constant expression, the actual arguments passed in, and the function 3442 /// pointers. 3443 unsigned getNumSubExprs() const { return NumExprs; } 3444 3445 /// \brief Retrieve the array of expressions. 3446 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); } 3447 3448 /// getExpr - Return the Expr at the specified index. 3449 Expr *getExpr(unsigned Index) { 3450 assert((Index < NumExprs) && "Arg access out of range!"); 3451 return cast<Expr>(SubExprs[Index]); 3452 } 3453 const Expr *getExpr(unsigned Index) const { 3454 assert((Index < NumExprs) && "Arg access out of range!"); 3455 return cast<Expr>(SubExprs[Index]); 3456 } 3457 3458 void setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs); 3459 3460 llvm::APSInt getShuffleMaskIdx(const ASTContext &Ctx, unsigned N) const { 3461 assert((N < NumExprs - 2) && "Shuffle idx out of range!"); 3462 return getExpr(N+2)->EvaluateKnownConstInt(Ctx); 3463 } 3464 3465 // Iterators 3466 child_range children() { 3467 return child_range(&SubExprs[0], &SubExprs[0]+NumExprs); 3468 } 3469}; 3470 3471/// ConvertVectorExpr - Clang builtin function __builtin_convertvector 3472/// This AST node provides support for converting a vector type to another 3473/// vector type of the same arity. 3474class ConvertVectorExpr : public Expr { 3475private: 3476 Stmt *SrcExpr; 3477 TypeSourceInfo *TInfo; 3478 SourceLocation BuiltinLoc, RParenLoc; 3479 3480 friend class ASTReader; 3481 friend class ASTStmtReader; 3482 explicit ConvertVectorExpr(EmptyShell Empty) : Expr(ConvertVectorExprClass, Empty) {} 3483 3484public: 3485 ConvertVectorExpr(Expr* SrcExpr, TypeSourceInfo *TI, QualType DstType, 3486 ExprValueKind VK, ExprObjectKind OK, 3487 SourceLocation BuiltinLoc, SourceLocation RParenLoc) 3488 : Expr(ConvertVectorExprClass, DstType, VK, OK, 3489 DstType->isDependentType(), 3490 DstType->isDependentType() || SrcExpr->isValueDependent(), 3491 (DstType->isInstantiationDependentType() || 3492 SrcExpr->isInstantiationDependent()), 3493 (DstType->containsUnexpandedParameterPack() || 3494 SrcExpr->containsUnexpandedParameterPack())), 3495 SrcExpr(SrcExpr), TInfo(TI), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {} 3496 3497 /// getSrcExpr - Return the Expr to be converted. 3498 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); } 3499 3500 /// getTypeSourceInfo - Return the destination type. 3501 TypeSourceInfo *getTypeSourceInfo() const { 3502 return TInfo; 3503 } 3504 void setTypeSourceInfo(TypeSourceInfo *ti) { 3505 TInfo = ti; 3506 } 3507 3508 /// getBuiltinLoc - Return the location of the __builtin_convertvector token. 3509 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 3510 3511 /// getRParenLoc - Return the location of final right parenthesis. 3512 SourceLocation getRParenLoc() const { return RParenLoc; } 3513 3514 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; } 3515 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } 3516 3517 static bool classof(const Stmt *T) { 3518 return T->getStmtClass() == ConvertVectorExprClass; 3519 } 3520 3521 // Iterators 3522 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); } 3523}; 3524 3525/// ChooseExpr - GNU builtin-in function __builtin_choose_expr. 3526/// This AST node is similar to the conditional operator (?:) in C, with 3527/// the following exceptions: 3528/// - the test expression must be a integer constant expression. 3529/// - the expression returned acts like the chosen subexpression in every 3530/// visible way: the type is the same as that of the chosen subexpression, 3531/// and all predicates (whether it's an l-value, whether it's an integer 3532/// constant expression, etc.) return the same result as for the chosen 3533/// sub-expression. 3534class ChooseExpr : public Expr { 3535 enum { COND, LHS, RHS, END_EXPR }; 3536 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides. 3537 SourceLocation BuiltinLoc, RParenLoc; 3538 bool CondIsTrue; 3539public: 3540 ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs, 3541 QualType t, ExprValueKind VK, ExprObjectKind OK, 3542 SourceLocation RP, bool condIsTrue, 3543 bool TypeDependent, bool ValueDependent) 3544 : Expr(ChooseExprClass, t, VK, OK, TypeDependent, ValueDependent, 3545 (cond->isInstantiationDependent() || 3546 lhs->isInstantiationDependent() || 3547 rhs->isInstantiationDependent()), 3548 (cond->containsUnexpandedParameterPack() || 3549 lhs->containsUnexpandedParameterPack() || 3550 rhs->containsUnexpandedParameterPack())), 3551 BuiltinLoc(BLoc), RParenLoc(RP), CondIsTrue(condIsTrue) { 3552 SubExprs[COND] = cond; 3553 SubExprs[LHS] = lhs; 3554 SubExprs[RHS] = rhs; 3555 } 3556 3557 /// \brief Build an empty __builtin_choose_expr. 3558 explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { } 3559 3560 /// isConditionTrue - Return whether the condition is true (i.e. not 3561 /// equal to zero). 3562 bool isConditionTrue() const { 3563 assert(!isConditionDependent() && 3564 "Dependent condition isn't true or false"); 3565 return CondIsTrue; 3566 } 3567 void setIsConditionTrue(bool isTrue) { CondIsTrue = isTrue; } 3568 3569 bool isConditionDependent() const { 3570 return getCond()->isTypeDependent() || getCond()->isValueDependent(); 3571 } 3572 3573 /// getChosenSubExpr - Return the subexpression chosen according to the 3574 /// condition. 3575 Expr *getChosenSubExpr() const { 3576 return isConditionTrue() ? getLHS() : getRHS(); 3577 } 3578 3579 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); } 3580 void setCond(Expr *E) { SubExprs[COND] = E; } 3581 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } 3582 void setLHS(Expr *E) { SubExprs[LHS] = E; } 3583 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } 3584 void setRHS(Expr *E) { SubExprs[RHS] = E; } 3585 3586 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 3587 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; } 3588 3589 SourceLocation getRParenLoc() const { return RParenLoc; } 3590 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 3591 3592 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; } 3593 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } 3594 3595 static bool classof(const Stmt *T) { 3596 return T->getStmtClass() == ChooseExprClass; 3597 } 3598 3599 // Iterators 3600 child_range children() { 3601 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); 3602 } 3603}; 3604 3605/// GNUNullExpr - Implements the GNU __null extension, which is a name 3606/// for a null pointer constant that has integral type (e.g., int or 3607/// long) and is the same size and alignment as a pointer. The __null 3608/// extension is typically only used by system headers, which define 3609/// NULL as __null in C++ rather than using 0 (which is an integer 3610/// that may not match the size of a pointer). 3611class GNUNullExpr : public Expr { 3612 /// TokenLoc - The location of the __null keyword. 3613 SourceLocation TokenLoc; 3614 3615public: 3616 GNUNullExpr(QualType Ty, SourceLocation Loc) 3617 : Expr(GNUNullExprClass, Ty, VK_RValue, OK_Ordinary, false, false, false, 3618 false), 3619 TokenLoc(Loc) { } 3620 3621 /// \brief Build an empty GNU __null expression. 3622 explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { } 3623 3624 /// getTokenLocation - The location of the __null token. 3625 SourceLocation getTokenLocation() const { return TokenLoc; } 3626 void setTokenLocation(SourceLocation L) { TokenLoc = L; } 3627 3628 SourceLocation getLocStart() const LLVM_READONLY { return TokenLoc; } 3629 SourceLocation getLocEnd() const LLVM_READONLY { return TokenLoc; } 3630 3631 static bool classof(const Stmt *T) { 3632 return T->getStmtClass() == GNUNullExprClass; 3633 } 3634 3635 // Iterators 3636 child_range children() { return child_range(); } 3637}; 3638 3639/// VAArgExpr, used for the builtin function __builtin_va_arg. 3640class VAArgExpr : public Expr { 3641 Stmt *Val; 3642 TypeSourceInfo *TInfo; 3643 SourceLocation BuiltinLoc, RParenLoc; 3644public: 3645 VAArgExpr(SourceLocation BLoc, Expr* e, TypeSourceInfo *TInfo, 3646 SourceLocation RPLoc, QualType t) 3647 : Expr(VAArgExprClass, t, VK_RValue, OK_Ordinary, 3648 t->isDependentType(), false, 3649 (TInfo->getType()->isInstantiationDependentType() || 3650 e->isInstantiationDependent()), 3651 (TInfo->getType()->containsUnexpandedParameterPack() || 3652 e->containsUnexpandedParameterPack())), 3653 Val(e), TInfo(TInfo), 3654 BuiltinLoc(BLoc), 3655 RParenLoc(RPLoc) { } 3656 3657 /// \brief Create an empty __builtin_va_arg expression. 3658 explicit VAArgExpr(EmptyShell Empty) : Expr(VAArgExprClass, Empty) { } 3659 3660 const Expr *getSubExpr() const { return cast<Expr>(Val); } 3661 Expr *getSubExpr() { return cast<Expr>(Val); } 3662 void setSubExpr(Expr *E) { Val = E; } 3663 3664 TypeSourceInfo *getWrittenTypeInfo() const { return TInfo; } 3665 void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo = TI; } 3666 3667 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 3668 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; } 3669 3670 SourceLocation getRParenLoc() const { return RParenLoc; } 3671 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 3672 3673 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; } 3674 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } 3675 3676 static bool classof(const Stmt *T) { 3677 return T->getStmtClass() == VAArgExprClass; 3678 } 3679 3680 // Iterators 3681 child_range children() { return child_range(&Val, &Val+1); } 3682}; 3683 3684/// @brief Describes an C or C++ initializer list. 3685/// 3686/// InitListExpr describes an initializer list, which can be used to 3687/// initialize objects of different types, including 3688/// struct/class/union types, arrays, and vectors. For example: 3689/// 3690/// @code 3691/// struct foo x = { 1, { 2, 3 } }; 3692/// @endcode 3693/// 3694/// Prior to semantic analysis, an initializer list will represent the 3695/// initializer list as written by the user, but will have the 3696/// placeholder type "void". This initializer list is called the 3697/// syntactic form of the initializer, and may contain C99 designated 3698/// initializers (represented as DesignatedInitExprs), initializations 3699/// of subobject members without explicit braces, and so on. Clients 3700/// interested in the original syntax of the initializer list should 3701/// use the syntactic form of the initializer list. 3702/// 3703/// After semantic analysis, the initializer list will represent the 3704/// semantic form of the initializer, where the initializations of all 3705/// subobjects are made explicit with nested InitListExpr nodes and 3706/// C99 designators have been eliminated by placing the designated 3707/// initializations into the subobject they initialize. Additionally, 3708/// any "holes" in the initialization, where no initializer has been 3709/// specified for a particular subobject, will be replaced with 3710/// implicitly-generated ImplicitValueInitExpr expressions that 3711/// value-initialize the subobjects. Note, however, that the 3712/// initializer lists may still have fewer initializers than there are 3713/// elements to initialize within the object. 3714/// 3715/// After semantic analysis has completed, given an initializer list, 3716/// method isSemanticForm() returns true if and only if this is the 3717/// semantic form of the initializer list (note: the same AST node 3718/// may at the same time be the syntactic form). 3719/// Given the semantic form of the initializer list, one can retrieve 3720/// the syntactic form of that initializer list (when different) 3721/// using method getSyntacticForm(); the method returns null if applied 3722/// to a initializer list which is already in syntactic form. 3723/// Similarly, given the syntactic form (i.e., an initializer list such 3724/// that isSemanticForm() returns false), one can retrieve the semantic 3725/// form using method getSemanticForm(). 3726/// Since many initializer lists have the same syntactic and semantic forms, 3727/// getSyntacticForm() may return NULL, indicating that the current 3728/// semantic initializer list also serves as its syntactic form. 3729class InitListExpr : public Expr { 3730 // FIXME: Eliminate this vector in favor of ASTContext allocation 3731 typedef ASTVector<Stmt *> InitExprsTy; 3732 InitExprsTy InitExprs; 3733 SourceLocation LBraceLoc, RBraceLoc; 3734 3735 /// The alternative form of the initializer list (if it exists). 3736 /// The int part of the pair stores whether this initializer list is 3737 /// in semantic form. If not null, the pointer points to: 3738 /// - the syntactic form, if this is in semantic form; 3739 /// - the semantic form, if this is in syntactic form. 3740 llvm::PointerIntPair<InitListExpr *, 1, bool> AltForm; 3741 3742 /// \brief Either: 3743 /// If this initializer list initializes an array with more elements than 3744 /// there are initializers in the list, specifies an expression to be used 3745 /// for value initialization of the rest of the elements. 3746 /// Or 3747 /// If this initializer list initializes a union, specifies which 3748 /// field within the union will be initialized. 3749 llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit; 3750 3751public: 3752 InitListExpr(const ASTContext &C, SourceLocation lbraceloc, 3753 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc); 3754 3755 /// \brief Build an empty initializer list. 3756 explicit InitListExpr(EmptyShell Empty) 3757 : Expr(InitListExprClass, Empty) { } 3758 3759 unsigned getNumInits() const { return InitExprs.size(); } 3760 3761 /// \brief Retrieve the set of initializers. 3762 Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); } 3763 3764 const Expr *getInit(unsigned Init) const { 3765 assert(Init < getNumInits() && "Initializer access out of range!"); 3766 return cast_or_null<Expr>(InitExprs[Init]); 3767 } 3768 3769 Expr *getInit(unsigned Init) { 3770 assert(Init < getNumInits() && "Initializer access out of range!"); 3771 return cast_or_null<Expr>(InitExprs[Init]); 3772 } 3773 3774 void setInit(unsigned Init, Expr *expr) { 3775 assert(Init < getNumInits() && "Initializer access out of range!"); 3776 InitExprs[Init] = expr; 3777 } 3778 3779 /// \brief Reserve space for some number of initializers. 3780 void reserveInits(const ASTContext &C, unsigned NumInits); 3781 3782 /// @brief Specify the number of initializers 3783 /// 3784 /// If there are more than @p NumInits initializers, the remaining 3785 /// initializers will be destroyed. If there are fewer than @p 3786 /// NumInits initializers, NULL expressions will be added for the 3787 /// unknown initializers. 3788 void resizeInits(const ASTContext &Context, unsigned NumInits); 3789 3790 /// @brief Updates the initializer at index @p Init with the new 3791 /// expression @p expr, and returns the old expression at that 3792 /// location. 3793 /// 3794 /// When @p Init is out of range for this initializer list, the 3795 /// initializer list will be extended with NULL expressions to 3796 /// accommodate the new entry. 3797 Expr *updateInit(const ASTContext &C, unsigned Init, Expr *expr); 3798 3799 /// \brief If this initializer list initializes an array with more elements 3800 /// than there are initializers in the list, specifies an expression to be 3801 /// used for value initialization of the rest of the elements. 3802 Expr *getArrayFiller() { 3803 return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>(); 3804 } 3805 const Expr *getArrayFiller() const { 3806 return const_cast<InitListExpr *>(this)->getArrayFiller(); 3807 } 3808 void setArrayFiller(Expr *filler); 3809 3810 /// \brief Return true if this is an array initializer and its array "filler" 3811 /// has been set. 3812 bool hasArrayFiller() const { return getArrayFiller(); } 3813 3814 /// \brief If this initializes a union, specifies which field in the 3815 /// union to initialize. 3816 /// 3817 /// Typically, this field is the first named field within the 3818 /// union. However, a designated initializer can specify the 3819 /// initialization of a different field within the union. 3820 FieldDecl *getInitializedFieldInUnion() { 3821 return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>(); 3822 } 3823 const FieldDecl *getInitializedFieldInUnion() const { 3824 return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion(); 3825 } 3826 void setInitializedFieldInUnion(FieldDecl *FD) { 3827 assert((FD == 0 3828 || getInitializedFieldInUnion() == 0 3829 || getInitializedFieldInUnion() == FD) 3830 && "Only one field of a union may be initialized at a time!"); 3831 ArrayFillerOrUnionFieldInit = FD; 3832 } 3833 3834 // Explicit InitListExpr's originate from source code (and have valid source 3835 // locations). Implicit InitListExpr's are created by the semantic analyzer. 3836 bool isExplicit() { 3837 return LBraceLoc.isValid() && RBraceLoc.isValid(); 3838 } 3839 3840 // Is this an initializer for an array of characters, initialized by a string 3841 // literal or an @encode? 3842 bool isStringLiteralInit() const; 3843 3844 SourceLocation getLBraceLoc() const { return LBraceLoc; } 3845 void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; } 3846 SourceLocation getRBraceLoc() const { return RBraceLoc; } 3847 void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; } 3848 3849 bool isSemanticForm() const { return AltForm.getInt(); } 3850 InitListExpr *getSemanticForm() const { 3851 return isSemanticForm() ? 0 : AltForm.getPointer(); 3852 } 3853 InitListExpr *getSyntacticForm() const { 3854 return isSemanticForm() ? AltForm.getPointer() : 0; 3855 } 3856 3857 void setSyntacticForm(InitListExpr *Init) { 3858 AltForm.setPointer(Init); 3859 AltForm.setInt(true); 3860 Init->AltForm.setPointer(this); 3861 Init->AltForm.setInt(false); 3862 } 3863 3864 bool hadArrayRangeDesignator() const { 3865 return InitListExprBits.HadArrayRangeDesignator != 0; 3866 } 3867 void sawArrayRangeDesignator(bool ARD = true) { 3868 InitListExprBits.HadArrayRangeDesignator = ARD; 3869 } 3870 3871 SourceLocation getLocStart() const LLVM_READONLY; 3872 SourceLocation getLocEnd() const LLVM_READONLY; 3873 3874 static bool classof(const Stmt *T) { 3875 return T->getStmtClass() == InitListExprClass; 3876 } 3877 3878 // Iterators 3879 child_range children() { 3880 if (InitExprs.empty()) return child_range(); 3881 return child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size()); 3882 } 3883 3884 typedef InitExprsTy::iterator iterator; 3885 typedef InitExprsTy::const_iterator const_iterator; 3886 typedef InitExprsTy::reverse_iterator reverse_iterator; 3887 typedef InitExprsTy::const_reverse_iterator const_reverse_iterator; 3888 3889 iterator begin() { return InitExprs.begin(); } 3890 const_iterator begin() const { return InitExprs.begin(); } 3891 iterator end() { return InitExprs.end(); } 3892 const_iterator end() const { return InitExprs.end(); } 3893 reverse_iterator rbegin() { return InitExprs.rbegin(); } 3894 const_reverse_iterator rbegin() const { return InitExprs.rbegin(); } 3895 reverse_iterator rend() { return InitExprs.rend(); } 3896 const_reverse_iterator rend() const { return InitExprs.rend(); } 3897 3898 friend class ASTStmtReader; 3899 friend class ASTStmtWriter; 3900}; 3901 3902/// @brief Represents a C99 designated initializer expression. 3903/// 3904/// A designated initializer expression (C99 6.7.8) contains one or 3905/// more designators (which can be field designators, array 3906/// designators, or GNU array-range designators) followed by an 3907/// expression that initializes the field or element(s) that the 3908/// designators refer to. For example, given: 3909/// 3910/// @code 3911/// struct point { 3912/// double x; 3913/// double y; 3914/// }; 3915/// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 }; 3916/// @endcode 3917/// 3918/// The InitListExpr contains three DesignatedInitExprs, the first of 3919/// which covers @c [2].y=1.0. This DesignatedInitExpr will have two 3920/// designators, one array designator for @c [2] followed by one field 3921/// designator for @c .y. The initialization expression will be 1.0. 3922class DesignatedInitExpr : public Expr { 3923public: 3924 /// \brief Forward declaration of the Designator class. 3925 class Designator; 3926 3927private: 3928 /// The location of the '=' or ':' prior to the actual initializer 3929 /// expression. 3930 SourceLocation EqualOrColonLoc; 3931 3932 /// Whether this designated initializer used the GNU deprecated 3933 /// syntax rather than the C99 '=' syntax. 3934 bool GNUSyntax : 1; 3935 3936 /// The number of designators in this initializer expression. 3937 unsigned NumDesignators : 15; 3938 3939 /// The number of subexpressions of this initializer expression, 3940 /// which contains both the initializer and any additional 3941 /// expressions used by array and array-range designators. 3942 unsigned NumSubExprs : 16; 3943 3944 /// \brief The designators in this designated initialization 3945 /// expression. 3946 Designator *Designators; 3947 3948 3949 DesignatedInitExpr(const ASTContext &C, QualType Ty, unsigned NumDesignators, 3950 const Designator *Designators, 3951 SourceLocation EqualOrColonLoc, bool GNUSyntax, 3952 ArrayRef<Expr*> IndexExprs, Expr *Init); 3953 3954 explicit DesignatedInitExpr(unsigned NumSubExprs) 3955 : Expr(DesignatedInitExprClass, EmptyShell()), 3956 NumDesignators(0), NumSubExprs(NumSubExprs), Designators(0) { } 3957 3958public: 3959 /// A field designator, e.g., ".x". 3960 struct FieldDesignator { 3961 /// Refers to the field that is being initialized. The low bit 3962 /// of this field determines whether this is actually a pointer 3963 /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When 3964 /// initially constructed, a field designator will store an 3965 /// IdentifierInfo*. After semantic analysis has resolved that 3966 /// name, the field designator will instead store a FieldDecl*. 3967 uintptr_t NameOrField; 3968 3969 /// The location of the '.' in the designated initializer. 3970 unsigned DotLoc; 3971 3972 /// The location of the field name in the designated initializer. 3973 unsigned FieldLoc; 3974 }; 3975 3976 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]". 3977 struct ArrayOrRangeDesignator { 3978 /// Location of the first index expression within the designated 3979 /// initializer expression's list of subexpressions. 3980 unsigned Index; 3981 /// The location of the '[' starting the array range designator. 3982 unsigned LBracketLoc; 3983 /// The location of the ellipsis separating the start and end 3984 /// indices. Only valid for GNU array-range designators. 3985 unsigned EllipsisLoc; 3986 /// The location of the ']' terminating the array range designator. 3987 unsigned RBracketLoc; 3988 }; 3989 3990 /// @brief Represents a single C99 designator. 3991 /// 3992 /// @todo This class is infuriatingly similar to clang::Designator, 3993 /// but minor differences (storing indices vs. storing pointers) 3994 /// keep us from reusing it. Try harder, later, to rectify these 3995 /// differences. 3996 class Designator { 3997 /// @brief The kind of designator this describes. 3998 enum { 3999 FieldDesignator, 4000 ArrayDesignator, 4001 ArrayRangeDesignator 4002 } Kind; 4003 4004 union { 4005 /// A field designator, e.g., ".x". 4006 struct FieldDesignator Field; 4007 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]". 4008 struct ArrayOrRangeDesignator ArrayOrRange; 4009 }; 4010 friend class DesignatedInitExpr; 4011 4012 public: 4013 Designator() {} 4014 4015 /// @brief Initializes a field designator. 4016 Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc, 4017 SourceLocation FieldLoc) 4018 : Kind(FieldDesignator) { 4019 Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01; 4020 Field.DotLoc = DotLoc.getRawEncoding(); 4021 Field.FieldLoc = FieldLoc.getRawEncoding(); 4022 } 4023 4024 /// @brief Initializes an array designator. 4025 Designator(unsigned Index, SourceLocation LBracketLoc, 4026 SourceLocation RBracketLoc) 4027 : Kind(ArrayDesignator) { 4028 ArrayOrRange.Index = Index; 4029 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding(); 4030 ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding(); 4031 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding(); 4032 } 4033 4034 /// @brief Initializes a GNU array-range designator. 4035 Designator(unsigned Index, SourceLocation LBracketLoc, 4036 SourceLocation EllipsisLoc, SourceLocation RBracketLoc) 4037 : Kind(ArrayRangeDesignator) { 4038 ArrayOrRange.Index = Index; 4039 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding(); 4040 ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding(); 4041 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding(); 4042 } 4043 4044 bool isFieldDesignator() const { return Kind == FieldDesignator; } 4045 bool isArrayDesignator() const { return Kind == ArrayDesignator; } 4046 bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; } 4047 4048 IdentifierInfo *getFieldName() const; 4049 4050 FieldDecl *getField() const { 4051 assert(Kind == FieldDesignator && "Only valid on a field designator"); 4052 if (Field.NameOrField & 0x01) 4053 return 0; 4054 else 4055 return reinterpret_cast<FieldDecl *>(Field.NameOrField); 4056 } 4057 4058 void setField(FieldDecl *FD) { 4059 assert(Kind == FieldDesignator && "Only valid on a field designator"); 4060 Field.NameOrField = reinterpret_cast<uintptr_t>(FD); 4061 } 4062 4063 SourceLocation getDotLoc() const { 4064 assert(Kind == FieldDesignator && "Only valid on a field designator"); 4065 return SourceLocation::getFromRawEncoding(Field.DotLoc); 4066 } 4067 4068 SourceLocation getFieldLoc() const { 4069 assert(Kind == FieldDesignator && "Only valid on a field designator"); 4070 return SourceLocation::getFromRawEncoding(Field.FieldLoc); 4071 } 4072 4073 SourceLocation getLBracketLoc() const { 4074 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && 4075 "Only valid on an array or array-range designator"); 4076 return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc); 4077 } 4078 4079 SourceLocation getRBracketLoc() const { 4080 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && 4081 "Only valid on an array or array-range designator"); 4082 return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc); 4083 } 4084 4085 SourceLocation getEllipsisLoc() const { 4086 assert(Kind == ArrayRangeDesignator && 4087 "Only valid on an array-range designator"); 4088 return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc); 4089 } 4090 4091 unsigned getFirstExprIndex() const { 4092 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && 4093 "Only valid on an array or array-range designator"); 4094 return ArrayOrRange.Index; 4095 } 4096 4097 SourceLocation getLocStart() const LLVM_READONLY { 4098 if (Kind == FieldDesignator) 4099 return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc(); 4100 else 4101 return getLBracketLoc(); 4102 } 4103 SourceLocation getLocEnd() const LLVM_READONLY { 4104 return Kind == FieldDesignator ? getFieldLoc() : getRBracketLoc(); 4105 } 4106 SourceRange getSourceRange() const LLVM_READONLY { 4107 return SourceRange(getLocStart(), getLocEnd()); 4108 } 4109 }; 4110 4111 static DesignatedInitExpr *Create(const ASTContext &C, 4112 Designator *Designators, 4113 unsigned NumDesignators, 4114 ArrayRef<Expr*> IndexExprs, 4115 SourceLocation EqualOrColonLoc, 4116 bool GNUSyntax, Expr *Init); 4117 4118 static DesignatedInitExpr *CreateEmpty(const ASTContext &C, 4119 unsigned NumIndexExprs); 4120 4121 /// @brief Returns the number of designators in this initializer. 4122 unsigned size() const { return NumDesignators; } 4123 4124 // Iterator access to the designators. 4125 typedef Designator *designators_iterator; 4126 designators_iterator designators_begin() { return Designators; } 4127 designators_iterator designators_end() { 4128 return Designators + NumDesignators; 4129 } 4130 4131 typedef const Designator *const_designators_iterator; 4132 const_designators_iterator designators_begin() const { return Designators; } 4133 const_designators_iterator designators_end() const { 4134 return Designators + NumDesignators; 4135 } 4136 4137 typedef std::reverse_iterator<designators_iterator> 4138 reverse_designators_iterator; 4139 reverse_designators_iterator designators_rbegin() { 4140 return reverse_designators_iterator(designators_end()); 4141 } 4142 reverse_designators_iterator designators_rend() { 4143 return reverse_designators_iterator(designators_begin()); 4144 } 4145 4146 typedef std::reverse_iterator<const_designators_iterator> 4147 const_reverse_designators_iterator; 4148 const_reverse_designators_iterator designators_rbegin() const { 4149 return const_reverse_designators_iterator(designators_end()); 4150 } 4151 const_reverse_designators_iterator designators_rend() const { 4152 return const_reverse_designators_iterator(designators_begin()); 4153 } 4154 4155 Designator *getDesignator(unsigned Idx) { return &designators_begin()[Idx]; } 4156 4157 void setDesignators(const ASTContext &C, const Designator *Desigs, 4158 unsigned NumDesigs); 4159 4160 Expr *getArrayIndex(const Designator &D) const; 4161 Expr *getArrayRangeStart(const Designator &D) const; 4162 Expr *getArrayRangeEnd(const Designator &D) const; 4163 4164 /// @brief Retrieve the location of the '=' that precedes the 4165 /// initializer value itself, if present. 4166 SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; } 4167 void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; } 4168 4169 /// @brief Determines whether this designated initializer used the 4170 /// deprecated GNU syntax for designated initializers. 4171 bool usesGNUSyntax() const { return GNUSyntax; } 4172 void setGNUSyntax(bool GNU) { GNUSyntax = GNU; } 4173 4174 /// @brief Retrieve the initializer value. 4175 Expr *getInit() const { 4176 return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin()); 4177 } 4178 4179 void setInit(Expr *init) { 4180 *child_begin() = init; 4181 } 4182 4183 /// \brief Retrieve the total number of subexpressions in this 4184 /// designated initializer expression, including the actual 4185 /// initialized value and any expressions that occur within array 4186 /// and array-range designators. 4187 unsigned getNumSubExprs() const { return NumSubExprs; } 4188 4189 Expr *getSubExpr(unsigned Idx) { 4190 assert(Idx < NumSubExprs && "Subscript out of range"); 4191 char* Ptr = static_cast<char*>(static_cast<void *>(this)); 4192 Ptr += sizeof(DesignatedInitExpr); 4193 return reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx]; 4194 } 4195 4196 void setSubExpr(unsigned Idx, Expr *E) { 4197 assert(Idx < NumSubExprs && "Subscript out of range"); 4198 char* Ptr = static_cast<char*>(static_cast<void *>(this)); 4199 Ptr += sizeof(DesignatedInitExpr); 4200 reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx] = E; 4201 } 4202 4203 /// \brief Replaces the designator at index @p Idx with the series 4204 /// of designators in [First, Last). 4205 void ExpandDesignator(const ASTContext &C, unsigned Idx, 4206 const Designator *First, const Designator *Last); 4207 4208 SourceRange getDesignatorsSourceRange() const; 4209 4210 SourceLocation getLocStart() const LLVM_READONLY; 4211 SourceLocation getLocEnd() const LLVM_READONLY; 4212 4213 static bool classof(const Stmt *T) { 4214 return T->getStmtClass() == DesignatedInitExprClass; 4215 } 4216 4217 // Iterators 4218 child_range children() { 4219 Stmt **begin = reinterpret_cast<Stmt**>(this + 1); 4220 return child_range(begin, begin + NumSubExprs); 4221 } 4222}; 4223 4224/// \brief Represents an implicitly-generated value initialization of 4225/// an object of a given type. 4226/// 4227/// Implicit value initializations occur within semantic initializer 4228/// list expressions (InitListExpr) as placeholders for subobject 4229/// initializations not explicitly specified by the user. 4230/// 4231/// \see InitListExpr 4232class ImplicitValueInitExpr : public Expr { 4233public: 4234 explicit ImplicitValueInitExpr(QualType ty) 4235 : Expr(ImplicitValueInitExprClass, ty, VK_RValue, OK_Ordinary, 4236 false, false, ty->isInstantiationDependentType(), false) { } 4237 4238 /// \brief Construct an empty implicit value initialization. 4239 explicit ImplicitValueInitExpr(EmptyShell Empty) 4240 : Expr(ImplicitValueInitExprClass, Empty) { } 4241 4242 static bool classof(const Stmt *T) { 4243 return T->getStmtClass() == ImplicitValueInitExprClass; 4244 } 4245 4246 SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); } 4247 SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); } 4248 4249 // Iterators 4250 child_range children() { return child_range(); } 4251}; 4252 4253 4254class ParenListExpr : public Expr { 4255 Stmt **Exprs; 4256 unsigned NumExprs; 4257 SourceLocation LParenLoc, RParenLoc; 4258 4259public: 4260 ParenListExpr(const ASTContext& C, SourceLocation lparenloc, 4261 ArrayRef<Expr*> exprs, SourceLocation rparenloc); 4262 4263 /// \brief Build an empty paren list. 4264 explicit ParenListExpr(EmptyShell Empty) : Expr(ParenListExprClass, Empty) { } 4265 4266 unsigned getNumExprs() const { return NumExprs; } 4267 4268 const Expr* getExpr(unsigned Init) const { 4269 assert(Init < getNumExprs() && "Initializer access out of range!"); 4270 return cast_or_null<Expr>(Exprs[Init]); 4271 } 4272 4273 Expr* getExpr(unsigned Init) { 4274 assert(Init < getNumExprs() && "Initializer access out of range!"); 4275 return cast_or_null<Expr>(Exprs[Init]); 4276 } 4277 4278 Expr **getExprs() { return reinterpret_cast<Expr **>(Exprs); } 4279 4280 SourceLocation getLParenLoc() const { return LParenLoc; } 4281 SourceLocation getRParenLoc() const { return RParenLoc; } 4282 4283 SourceLocation getLocStart() const LLVM_READONLY { return LParenLoc; } 4284 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } 4285 4286 static bool classof(const Stmt *T) { 4287 return T->getStmtClass() == ParenListExprClass; 4288 } 4289 4290 // Iterators 4291 child_range children() { 4292 return child_range(&Exprs[0], &Exprs[0]+NumExprs); 4293 } 4294 4295 friend class ASTStmtReader; 4296 friend class ASTStmtWriter; 4297}; 4298 4299 4300/// \brief Represents a C11 generic selection. 4301/// 4302/// A generic selection (C11 6.5.1.1) contains an unevaluated controlling 4303/// expression, followed by one or more generic associations. Each generic 4304/// association specifies a type name and an expression, or "default" and an 4305/// expression (in which case it is known as a default generic association). 4306/// The type and value of the generic selection are identical to those of its 4307/// result expression, which is defined as the expression in the generic 4308/// association with a type name that is compatible with the type of the 4309/// controlling expression, or the expression in the default generic association 4310/// if no types are compatible. For example: 4311/// 4312/// @code 4313/// _Generic(X, double: 1, float: 2, default: 3) 4314/// @endcode 4315/// 4316/// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f 4317/// or 3 if "hello". 4318/// 4319/// As an extension, generic selections are allowed in C++, where the following 4320/// additional semantics apply: 4321/// 4322/// Any generic selection whose controlling expression is type-dependent or 4323/// which names a dependent type in its association list is result-dependent, 4324/// which means that the choice of result expression is dependent. 4325/// Result-dependent generic associations are both type- and value-dependent. 4326class GenericSelectionExpr : public Expr { 4327 enum { CONTROLLING, END_EXPR }; 4328 TypeSourceInfo **AssocTypes; 4329 Stmt **SubExprs; 4330 unsigned NumAssocs, ResultIndex; 4331 SourceLocation GenericLoc, DefaultLoc, RParenLoc; 4332 4333public: 4334 GenericSelectionExpr(const ASTContext &Context, 4335 SourceLocation GenericLoc, Expr *ControllingExpr, 4336 ArrayRef<TypeSourceInfo*> AssocTypes, 4337 ArrayRef<Expr*> AssocExprs, 4338 SourceLocation DefaultLoc, SourceLocation RParenLoc, 4339 bool ContainsUnexpandedParameterPack, 4340 unsigned ResultIndex); 4341 4342 /// This constructor is used in the result-dependent case. 4343 GenericSelectionExpr(const ASTContext &Context, 4344 SourceLocation GenericLoc, Expr *ControllingExpr, 4345 ArrayRef<TypeSourceInfo*> AssocTypes, 4346 ArrayRef<Expr*> AssocExprs, 4347 SourceLocation DefaultLoc, SourceLocation RParenLoc, 4348 bool ContainsUnexpandedParameterPack); 4349 4350 explicit GenericSelectionExpr(EmptyShell Empty) 4351 : Expr(GenericSelectionExprClass, Empty) { } 4352 4353 unsigned getNumAssocs() const { return NumAssocs; } 4354 4355 SourceLocation getGenericLoc() const { return GenericLoc; } 4356 SourceLocation getDefaultLoc() const { return DefaultLoc; } 4357 SourceLocation getRParenLoc() const { return RParenLoc; } 4358 4359 const Expr *getAssocExpr(unsigned i) const { 4360 return cast<Expr>(SubExprs[END_EXPR+i]); 4361 } 4362 Expr *getAssocExpr(unsigned i) { return cast<Expr>(SubExprs[END_EXPR+i]); } 4363 4364 const TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) const { 4365 return AssocTypes[i]; 4366 } 4367 TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) { return AssocTypes[i]; } 4368 4369 QualType getAssocType(unsigned i) const { 4370 if (const TypeSourceInfo *TS = getAssocTypeSourceInfo(i)) 4371 return TS->getType(); 4372 else 4373 return QualType(); 4374 } 4375 4376 const Expr *getControllingExpr() const { 4377 return cast<Expr>(SubExprs[CONTROLLING]); 4378 } 4379 Expr *getControllingExpr() { return cast<Expr>(SubExprs[CONTROLLING]); } 4380 4381 /// Whether this generic selection is result-dependent. 4382 bool isResultDependent() const { return ResultIndex == -1U; } 4383 4384 /// The zero-based index of the result expression's generic association in 4385 /// the generic selection's association list. Defined only if the 4386 /// generic selection is not result-dependent. 4387 unsigned getResultIndex() const { 4388 assert(!isResultDependent() && "Generic selection is result-dependent"); 4389 return ResultIndex; 4390 } 4391 4392 /// The generic selection's result expression. Defined only if the 4393 /// generic selection is not result-dependent. 4394 const Expr *getResultExpr() const { return getAssocExpr(getResultIndex()); } 4395 Expr *getResultExpr() { return getAssocExpr(getResultIndex()); } 4396 4397 SourceLocation getLocStart() const LLVM_READONLY { return GenericLoc; } 4398 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } 4399 4400 static bool classof(const Stmt *T) { 4401 return T->getStmtClass() == GenericSelectionExprClass; 4402 } 4403 4404 child_range children() { 4405 return child_range(SubExprs, SubExprs+END_EXPR+NumAssocs); 4406 } 4407 4408 friend class ASTStmtReader; 4409}; 4410 4411//===----------------------------------------------------------------------===// 4412// Clang Extensions 4413//===----------------------------------------------------------------------===// 4414 4415 4416/// ExtVectorElementExpr - This represents access to specific elements of a 4417/// vector, and may occur on the left hand side or right hand side. For example 4418/// the following is legal: "V.xy = V.zw" if V is a 4 element extended vector. 4419/// 4420/// Note that the base may have either vector or pointer to vector type, just 4421/// like a struct field reference. 4422/// 4423class ExtVectorElementExpr : public Expr { 4424 Stmt *Base; 4425 IdentifierInfo *Accessor; 4426 SourceLocation AccessorLoc; 4427public: 4428 ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base, 4429 IdentifierInfo &accessor, SourceLocation loc) 4430 : Expr(ExtVectorElementExprClass, ty, VK, 4431 (VK == VK_RValue ? OK_Ordinary : OK_VectorComponent), 4432 base->isTypeDependent(), base->isValueDependent(), 4433 base->isInstantiationDependent(), 4434 base->containsUnexpandedParameterPack()), 4435 Base(base), Accessor(&accessor), AccessorLoc(loc) {} 4436 4437 /// \brief Build an empty vector element expression. 4438 explicit ExtVectorElementExpr(EmptyShell Empty) 4439 : Expr(ExtVectorElementExprClass, Empty) { } 4440 4441 const Expr *getBase() const { return cast<Expr>(Base); } 4442 Expr *getBase() { return cast<Expr>(Base); } 4443 void setBase(Expr *E) { Base = E; } 4444 4445 IdentifierInfo &getAccessor() const { return *Accessor; } 4446 void setAccessor(IdentifierInfo *II) { Accessor = II; } 4447 4448 SourceLocation getAccessorLoc() const { return AccessorLoc; } 4449 void setAccessorLoc(SourceLocation L) { AccessorLoc = L; } 4450 4451 /// getNumElements - Get the number of components being selected. 4452 unsigned getNumElements() const; 4453 4454 /// containsDuplicateElements - Return true if any element access is 4455 /// repeated. 4456 bool containsDuplicateElements() const; 4457 4458 /// getEncodedElementAccess - Encode the elements accessed into an llvm 4459 /// aggregate Constant of ConstantInt(s). 4460 void getEncodedElementAccess(SmallVectorImpl<unsigned> &Elts) const; 4461 4462 SourceLocation getLocStart() const LLVM_READONLY { 4463 return getBase()->getLocStart(); 4464 } 4465 SourceLocation getLocEnd() const LLVM_READONLY { return AccessorLoc; } 4466 4467 /// isArrow - Return true if the base expression is a pointer to vector, 4468 /// return false if the base expression is a vector. 4469 bool isArrow() const; 4470 4471 static bool classof(const Stmt *T) { 4472 return T->getStmtClass() == ExtVectorElementExprClass; 4473 } 4474 4475 // Iterators 4476 child_range children() { return child_range(&Base, &Base+1); } 4477}; 4478 4479 4480/// BlockExpr - Adaptor class for mixing a BlockDecl with expressions. 4481/// ^{ statement-body } or ^(int arg1, float arg2){ statement-body } 4482class BlockExpr : public Expr { 4483protected: 4484 BlockDecl *TheBlock; 4485public: 4486 BlockExpr(BlockDecl *BD, QualType ty) 4487 : Expr(BlockExprClass, ty, VK_RValue, OK_Ordinary, 4488 ty->isDependentType(), ty->isDependentType(), 4489 ty->isInstantiationDependentType() || BD->isDependentContext(), 4490 false), 4491 TheBlock(BD) {} 4492 4493 /// \brief Build an empty block expression. 4494 explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { } 4495 4496 const BlockDecl *getBlockDecl() const { return TheBlock; } 4497 BlockDecl *getBlockDecl() { return TheBlock; } 4498 void setBlockDecl(BlockDecl *BD) { TheBlock = BD; } 4499 4500 // Convenience functions for probing the underlying BlockDecl. 4501 SourceLocation getCaretLocation() const; 4502 const Stmt *getBody() const; 4503 Stmt *getBody(); 4504 4505 SourceLocation getLocStart() const LLVM_READONLY { return getCaretLocation(); } 4506 SourceLocation getLocEnd() const LLVM_READONLY { return getBody()->getLocEnd(); } 4507 4508 /// getFunctionType - Return the underlying function type for this block. 4509 const FunctionProtoType *getFunctionType() const; 4510 4511 static bool classof(const Stmt *T) { 4512 return T->getStmtClass() == BlockExprClass; 4513 } 4514 4515 // Iterators 4516 child_range children() { return child_range(); } 4517}; 4518 4519/// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2] 4520/// This AST node provides support for reinterpreting a type to another 4521/// type of the same size. 4522class AsTypeExpr : public Expr { 4523private: 4524 Stmt *SrcExpr; 4525 SourceLocation BuiltinLoc, RParenLoc; 4526 4527 friend class ASTReader; 4528 friend class ASTStmtReader; 4529 explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {} 4530 4531public: 4532 AsTypeExpr(Expr* SrcExpr, QualType DstType, 4533 ExprValueKind VK, ExprObjectKind OK, 4534 SourceLocation BuiltinLoc, SourceLocation RParenLoc) 4535 : Expr(AsTypeExprClass, DstType, VK, OK, 4536 DstType->isDependentType(), 4537 DstType->isDependentType() || SrcExpr->isValueDependent(), 4538 (DstType->isInstantiationDependentType() || 4539 SrcExpr->isInstantiationDependent()), 4540 (DstType->containsUnexpandedParameterPack() || 4541 SrcExpr->containsUnexpandedParameterPack())), 4542 SrcExpr(SrcExpr), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {} 4543 4544 /// getSrcExpr - Return the Expr to be converted. 4545 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); } 4546 4547 /// getBuiltinLoc - Return the location of the __builtin_astype token. 4548 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 4549 4550 /// getRParenLoc - Return the location of final right parenthesis. 4551 SourceLocation getRParenLoc() const { return RParenLoc; } 4552 4553 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; } 4554 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } 4555 4556 static bool classof(const Stmt *T) { 4557 return T->getStmtClass() == AsTypeExprClass; 4558 } 4559 4560 // Iterators 4561 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); } 4562}; 4563 4564/// PseudoObjectExpr - An expression which accesses a pseudo-object 4565/// l-value. A pseudo-object is an abstract object, accesses to which 4566/// are translated to calls. The pseudo-object expression has a 4567/// syntactic form, which shows how the expression was actually 4568/// written in the source code, and a semantic form, which is a series 4569/// of expressions to be executed in order which detail how the 4570/// operation is actually evaluated. Optionally, one of the semantic 4571/// forms may also provide a result value for the expression. 4572/// 4573/// If any of the semantic-form expressions is an OpaqueValueExpr, 4574/// that OVE is required to have a source expression, and it is bound 4575/// to the result of that source expression. Such OVEs may appear 4576/// only in subsequent semantic-form expressions and as 4577/// sub-expressions of the syntactic form. 4578/// 4579/// PseudoObjectExpr should be used only when an operation can be 4580/// usefully described in terms of fairly simple rewrite rules on 4581/// objects and functions that are meant to be used by end-developers. 4582/// For example, under the Itanium ABI, dynamic casts are implemented 4583/// as a call to a runtime function called __dynamic_cast; using this 4584/// class to describe that would be inappropriate because that call is 4585/// not really part of the user-visible semantics, and instead the 4586/// cast is properly reflected in the AST and IR-generation has been 4587/// taught to generate the call as necessary. In contrast, an 4588/// Objective-C property access is semantically defined to be 4589/// equivalent to a particular message send, and this is very much 4590/// part of the user model. The name of this class encourages this 4591/// modelling design. 4592class PseudoObjectExpr : public Expr { 4593 // PseudoObjectExprBits.NumSubExprs - The number of sub-expressions. 4594 // Always at least two, because the first sub-expression is the 4595 // syntactic form. 4596 4597 // PseudoObjectExprBits.ResultIndex - The index of the 4598 // sub-expression holding the result. 0 means the result is void, 4599 // which is unambiguous because it's the index of the syntactic 4600 // form. Note that this is therefore 1 higher than the value passed 4601 // in to Create, which is an index within the semantic forms. 4602 // Note also that ASTStmtWriter assumes this encoding. 4603 4604 Expr **getSubExprsBuffer() { return reinterpret_cast<Expr**>(this + 1); } 4605 const Expr * const *getSubExprsBuffer() const { 4606 return reinterpret_cast<const Expr * const *>(this + 1); 4607 } 4608 4609 friend class ASTStmtReader; 4610 4611 PseudoObjectExpr(QualType type, ExprValueKind VK, 4612 Expr *syntactic, ArrayRef<Expr*> semantic, 4613 unsigned resultIndex); 4614 4615 PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs); 4616 4617 unsigned getNumSubExprs() const { 4618 return PseudoObjectExprBits.NumSubExprs; 4619 } 4620 4621public: 4622 /// NoResult - A value for the result index indicating that there is 4623 /// no semantic result. 4624 enum LLVM_ENUM_INT_TYPE(unsigned) { NoResult = ~0U }; 4625 4626 static PseudoObjectExpr *Create(const ASTContext &Context, Expr *syntactic, 4627 ArrayRef<Expr*> semantic, 4628 unsigned resultIndex); 4629 4630 static PseudoObjectExpr *Create(const ASTContext &Context, EmptyShell shell, 4631 unsigned numSemanticExprs); 4632 4633 /// Return the syntactic form of this expression, i.e. the 4634 /// expression it actually looks like. Likely to be expressed in 4635 /// terms of OpaqueValueExprs bound in the semantic form. 4636 Expr *getSyntacticForm() { return getSubExprsBuffer()[0]; } 4637 const Expr *getSyntacticForm() const { return getSubExprsBuffer()[0]; } 4638 4639 /// Return the index of the result-bearing expression into the semantics 4640 /// expressions, or PseudoObjectExpr::NoResult if there is none. 4641 unsigned getResultExprIndex() const { 4642 if (PseudoObjectExprBits.ResultIndex == 0) return NoResult; 4643 return PseudoObjectExprBits.ResultIndex - 1; 4644 } 4645 4646 /// Return the result-bearing expression, or null if there is none. 4647 Expr *getResultExpr() { 4648 if (PseudoObjectExprBits.ResultIndex == 0) 4649 return 0; 4650 return getSubExprsBuffer()[PseudoObjectExprBits.ResultIndex]; 4651 } 4652 const Expr *getResultExpr() const { 4653 return const_cast<PseudoObjectExpr*>(this)->getResultExpr(); 4654 } 4655 4656 unsigned getNumSemanticExprs() const { return getNumSubExprs() - 1; } 4657 4658 typedef Expr * const *semantics_iterator; 4659 typedef const Expr * const *const_semantics_iterator; 4660 semantics_iterator semantics_begin() { 4661 return getSubExprsBuffer() + 1; 4662 } 4663 const_semantics_iterator semantics_begin() const { 4664 return getSubExprsBuffer() + 1; 4665 } 4666 semantics_iterator semantics_end() { 4667 return getSubExprsBuffer() + getNumSubExprs(); 4668 } 4669 const_semantics_iterator semantics_end() const { 4670 return getSubExprsBuffer() + getNumSubExprs(); 4671 } 4672 Expr *getSemanticExpr(unsigned index) { 4673 assert(index + 1 < getNumSubExprs()); 4674 return getSubExprsBuffer()[index + 1]; 4675 } 4676 const Expr *getSemanticExpr(unsigned index) const { 4677 return const_cast<PseudoObjectExpr*>(this)->getSemanticExpr(index); 4678 } 4679 4680 SourceLocation getExprLoc() const LLVM_READONLY { 4681 return getSyntacticForm()->getExprLoc(); 4682 } 4683 4684 SourceLocation getLocStart() const LLVM_READONLY { 4685 return getSyntacticForm()->getLocStart(); 4686 } 4687 SourceLocation getLocEnd() const LLVM_READONLY { 4688 return getSyntacticForm()->getLocEnd(); 4689 } 4690 4691 child_range children() { 4692 Stmt **cs = reinterpret_cast<Stmt**>(getSubExprsBuffer()); 4693 return child_range(cs, cs + getNumSubExprs()); 4694 } 4695 4696 static bool classof(const Stmt *T) { 4697 return T->getStmtClass() == PseudoObjectExprClass; 4698 } 4699}; 4700 4701/// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, 4702/// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the 4703/// similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>. 4704/// All of these instructions take one primary pointer and at least one memory 4705/// order. 4706class AtomicExpr : public Expr { 4707public: 4708 enum AtomicOp { 4709#define BUILTIN(ID, TYPE, ATTRS) 4710#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) AO ## ID, 4711#include "clang/Basic/Builtins.def" 4712 // Avoid trailing comma 4713 BI_First = 0 4714 }; 4715 4716private: 4717 enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, WEAK, END_EXPR }; 4718 Stmt* SubExprs[END_EXPR]; 4719 unsigned NumSubExprs; 4720 SourceLocation BuiltinLoc, RParenLoc; 4721 AtomicOp Op; 4722 4723 friend class ASTStmtReader; 4724 4725public: 4726 AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args, QualType t, 4727 AtomicOp op, SourceLocation RP); 4728 4729 /// \brief Determine the number of arguments the specified atomic builtin 4730 /// should have. 4731 static unsigned getNumSubExprs(AtomicOp Op); 4732 4733 /// \brief Build an empty AtomicExpr. 4734 explicit AtomicExpr(EmptyShell Empty) : Expr(AtomicExprClass, Empty) { } 4735 4736 Expr *getPtr() const { 4737 return cast<Expr>(SubExprs[PTR]); 4738 } 4739 Expr *getOrder() const { 4740 return cast<Expr>(SubExprs[ORDER]); 4741 } 4742 Expr *getVal1() const { 4743 if (Op == AO__c11_atomic_init) 4744 return cast<Expr>(SubExprs[ORDER]); 4745 assert(NumSubExprs > VAL1); 4746 return cast<Expr>(SubExprs[VAL1]); 4747 } 4748 Expr *getOrderFail() const { 4749 assert(NumSubExprs > ORDER_FAIL); 4750 return cast<Expr>(SubExprs[ORDER_FAIL]); 4751 } 4752 Expr *getVal2() const { 4753 if (Op == AO__atomic_exchange) 4754 return cast<Expr>(SubExprs[ORDER_FAIL]); 4755 assert(NumSubExprs > VAL2); 4756 return cast<Expr>(SubExprs[VAL2]); 4757 } 4758 Expr *getWeak() const { 4759 assert(NumSubExprs > WEAK); 4760 return cast<Expr>(SubExprs[WEAK]); 4761 } 4762 4763 AtomicOp getOp() const { return Op; } 4764 unsigned getNumSubExprs() { return NumSubExprs; } 4765 4766 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); } 4767 4768 bool isVolatile() const { 4769 return getPtr()->getType()->getPointeeType().isVolatileQualified(); 4770 } 4771 4772 bool isCmpXChg() const { 4773 return getOp() == AO__c11_atomic_compare_exchange_strong || 4774 getOp() == AO__c11_atomic_compare_exchange_weak || 4775 getOp() == AO__atomic_compare_exchange || 4776 getOp() == AO__atomic_compare_exchange_n; 4777 } 4778 4779 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 4780 SourceLocation getRParenLoc() const { return RParenLoc; } 4781 4782 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; } 4783 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } 4784 4785 static bool classof(const Stmt *T) { 4786 return T->getStmtClass() == AtomicExprClass; 4787 } 4788 4789 // Iterators 4790 child_range children() { 4791 return child_range(SubExprs, SubExprs+NumSubExprs); 4792 } 4793}; 4794} // end namespace clang 4795 4796#endif 4797