1 //===--- Expr.h - Classes for representing expressions ----------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines the Expr interface and subclasses. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #ifndef LLVM_CLANG_AST_EXPR_H 15 #define LLVM_CLANG_AST_EXPR_H 16 17 #include "clang/AST/APValue.h" 18 #include "clang/AST/ASTVector.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclAccessPair.h" 21 #include "clang/AST/OperationKinds.h" 22 #include "clang/AST/Stmt.h" 23 #include "clang/AST/TemplateBase.h" 24 #include "clang/AST/Type.h" 25 #include "clang/Basic/CharInfo.h" 26 #include "clang/Basic/TypeTraits.h" 27 #include "llvm/ADT/APFloat.h" 28 #include "llvm/ADT/APSInt.h" 29 #include "llvm/ADT/SmallVector.h" 30 #include "llvm/ADT/StringRef.h" 31 #include "llvm/Support/Compiler.h" 32 33 namespace clang { 34 class APValue; 35 class ASTContext; 36 class BlockDecl; 37 class CXXBaseSpecifier; 38 class CXXMemberCallExpr; 39 class CXXOperatorCallExpr; 40 class CastExpr; 41 class Decl; 42 class IdentifierInfo; 43 class MaterializeTemporaryExpr; 44 class NamedDecl; 45 class ObjCPropertyRefExpr; 46 class OpaqueValueExpr; 47 class ParmVarDecl; 48 class TargetInfo; 49 class ValueDecl; 50 51 /// \brief A simple array of base specifiers. 52 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath; 53 54 /// \brief An adjustment to be made to the temporary created when emitting a 55 /// reference binding, which accesses a particular subobject of that temporary. 56 struct SubobjectAdjustment { 57 enum { 58 DerivedToBaseAdjustment, 59 FieldAdjustment, 60 MemberPointerAdjustment 61 } Kind; 62 63 64 struct DTB { 65 const CastExpr *BasePath; 66 const CXXRecordDecl *DerivedClass; 67 }; 68 69 struct P { 70 const MemberPointerType *MPT; 71 Expr *RHS; 72 }; 73 74 union { 75 struct DTB DerivedToBase; 76 FieldDecl *Field; 77 struct P Ptr; 78 }; 79 80 SubobjectAdjustment(const CastExpr *BasePath, 81 const CXXRecordDecl *DerivedClass) 82 : Kind(DerivedToBaseAdjustment) { 83 DerivedToBase.BasePath = BasePath; 84 DerivedToBase.DerivedClass = DerivedClass; 85 } 86 87 SubobjectAdjustment(FieldDecl *Field) 88 : Kind(FieldAdjustment) { 89 this->Field = Field; 90 } 91 92 SubobjectAdjustment(const MemberPointerType *MPT, Expr *RHS) 93 : Kind(MemberPointerAdjustment) { 94 this->Ptr.MPT = MPT; 95 this->Ptr.RHS = RHS; 96 } 97 }; 98 99 /// Expr - This represents one expression. Note that Expr's are subclasses of 100 /// Stmt. This allows an expression to be transparently used any place a Stmt 101 /// is required. 102 /// 103 class Expr : public Stmt { 104 QualType TR; 105 106 protected: 107 Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK, 108 bool TD, bool VD, bool ID, bool ContainsUnexpandedParameterPack) 109 : Stmt(SC) 110 { 111 ExprBits.TypeDependent = TD; 112 ExprBits.ValueDependent = VD; 113 ExprBits.InstantiationDependent = ID; 114 ExprBits.ValueKind = VK; 115 ExprBits.ObjectKind = OK; 116 ExprBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack; 117 setType(T); 118 } 119 120 /// \brief Construct an empty expression. 121 explicit Expr(StmtClass SC, EmptyShell) : Stmt(SC) { } 122 123 public: 124 QualType getType() const { return TR; } 125 void setType(QualType t) { 126 // In C++, the type of an expression is always adjusted so that it 127 // will not have reference type an expression will never have 128 // reference type (C++ [expr]p6). Use 129 // QualType::getNonReferenceType() to retrieve the non-reference 130 // type. Additionally, inspect Expr::isLvalue to determine whether 131 // an expression that is adjusted in this manner should be 132 // considered an lvalue. 133 assert((t.isNull() || !t->isReferenceType()) && 134 "Expressions can't have reference type"); 135 136 TR = t; 137 } 138 139 /// isValueDependent - Determines whether this expression is 140 /// value-dependent (C++ [temp.dep.constexpr]). For example, the 141 /// array bound of "Chars" in the following example is 142 /// value-dependent. 143 /// @code 144 /// template<int Size, char (&Chars)[Size]> struct meta_string; 145 /// @endcode 146 bool isValueDependent() const { return ExprBits.ValueDependent; } 147 148 /// \brief Set whether this expression is value-dependent or not. 149 void setValueDependent(bool VD) { 150 ExprBits.ValueDependent = VD; 151 if (VD) 152 ExprBits.InstantiationDependent = true; 153 } 154 155 /// isTypeDependent - Determines whether this expression is 156 /// type-dependent (C++ [temp.dep.expr]), which means that its type 157 /// could change from one template instantiation to the next. For 158 /// example, the expressions "x" and "x + y" are type-dependent in 159 /// the following code, but "y" is not type-dependent: 160 /// @code 161 /// template<typename T> 162 /// void add(T x, int y) { 163 /// x + y; 164 /// } 165 /// @endcode 166 bool isTypeDependent() const { return ExprBits.TypeDependent; } 167 168 /// \brief Set whether this expression is type-dependent or not. 169 void setTypeDependent(bool TD) { 170 ExprBits.TypeDependent = TD; 171 if (TD) 172 ExprBits.InstantiationDependent = true; 173 } 174 175 /// \brief Whether this expression is instantiation-dependent, meaning that 176 /// it depends in some way on a template parameter, even if neither its type 177 /// nor (constant) value can change due to the template instantiation. 178 /// 179 /// In the following example, the expression \c sizeof(sizeof(T() + T())) is 180 /// instantiation-dependent (since it involves a template parameter \c T), but 181 /// is neither type- nor value-dependent, since the type of the inner 182 /// \c sizeof is known (\c std::size_t) and therefore the size of the outer 183 /// \c sizeof is known. 184 /// 185 /// \code 186 /// template<typename T> 187 /// void f(T x, T y) { 188 /// sizeof(sizeof(T() + T()); 189 /// } 190 /// \endcode 191 /// 192 bool isInstantiationDependent() const { 193 return ExprBits.InstantiationDependent; 194 } 195 196 /// \brief Set whether this expression is instantiation-dependent or not. 197 void setInstantiationDependent(bool ID) { 198 ExprBits.InstantiationDependent = ID; 199 } 200 201 /// \brief Whether this expression contains an unexpanded parameter 202 /// pack (for C++11 variadic templates). 203 /// 204 /// Given the following function template: 205 /// 206 /// \code 207 /// template<typename F, typename ...Types> 208 /// void forward(const F &f, Types &&...args) { 209 /// f(static_cast<Types&&>(args)...); 210 /// } 211 /// \endcode 212 /// 213 /// The expressions \c args and \c static_cast<Types&&>(args) both 214 /// contain parameter packs. 215 bool containsUnexpandedParameterPack() const { 216 return ExprBits.ContainsUnexpandedParameterPack; 217 } 218 219 /// \brief Set the bit that describes whether this expression 220 /// contains an unexpanded parameter pack. 221 void setContainsUnexpandedParameterPack(bool PP = true) { 222 ExprBits.ContainsUnexpandedParameterPack = PP; 223 } 224 225 /// getExprLoc - Return the preferred location for the arrow when diagnosing 226 /// a problem with a generic expression. 227 SourceLocation getExprLoc() const LLVM_READONLY; 228 229 /// isUnusedResultAWarning - Return true if this immediate expression should 230 /// be warned about if the result is unused. If so, fill in expr, location, 231 /// and ranges with expr to warn on and source locations/ranges appropriate 232 /// for a warning. 233 bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc, 234 SourceRange &R1, SourceRange &R2, 235 ASTContext &Ctx) const; 236 237 /// isLValue - True if this expression is an "l-value" according to 238 /// the rules of the current language. C and C++ give somewhat 239 /// different rules for this concept, but in general, the result of 240 /// an l-value expression identifies a specific object whereas the 241 /// result of an r-value expression is a value detached from any 242 /// specific storage. 243 /// 244 /// C++11 divides the concept of "r-value" into pure r-values 245 /// ("pr-values") and so-called expiring values ("x-values"), which 246 /// identify specific objects that can be safely cannibalized for 247 /// their resources. This is an unfortunate abuse of terminology on 248 /// the part of the C++ committee. In Clang, when we say "r-value", 249 /// we generally mean a pr-value. 250 bool isLValue() const { return getValueKind() == VK_LValue; } 251 bool isRValue() const { return getValueKind() == VK_RValue; } 252 bool isXValue() const { return getValueKind() == VK_XValue; } 253 bool isGLValue() const { return getValueKind() != VK_RValue; } 254 255 enum LValueClassification { 256 LV_Valid, 257 LV_NotObjectType, 258 LV_IncompleteVoidType, 259 LV_DuplicateVectorComponents, 260 LV_InvalidExpression, 261 LV_InvalidMessageExpression, 262 LV_MemberFunction, 263 LV_SubObjCPropertySetting, 264 LV_ClassTemporary, 265 LV_ArrayTemporary 266 }; 267 /// Reasons why an expression might not be an l-value. 268 LValueClassification ClassifyLValue(ASTContext &Ctx) const; 269 270 enum isModifiableLvalueResult { 271 MLV_Valid, 272 MLV_NotObjectType, 273 MLV_IncompleteVoidType, 274 MLV_DuplicateVectorComponents, 275 MLV_InvalidExpression, 276 MLV_LValueCast, // Specialized form of MLV_InvalidExpression. 277 MLV_IncompleteType, 278 MLV_ConstQualified, 279 MLV_ArrayType, 280 MLV_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 297 isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc = nullptr) 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, nullptr); 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 424 private: 425 Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const; 426 427 public: 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 = nullptr, 487 bool isEvaluated = true) const; 488 bool isIntegerConstantExpr(const ASTContext &Ctx, 489 SourceLocation *Loc = nullptr) 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 = nullptr, 501 SourceLocation *Loc = nullptr) 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 /// isPotentialConstantExprUnevaluted - Return true if this expression might 512 /// be usable in a constant expression in C++11 in an unevaluated context, if 513 /// it were in function FD marked constexpr. Return false if the function can 514 /// never produce a constant expression, along with diagnostics describing 515 /// why not. 516 static bool isPotentialConstantExprUnevaluated(Expr *E, 517 const FunctionDecl *FD, 518 SmallVectorImpl< 519 PartialDiagnosticAt> &Diags); 520 521 /// isConstantInitializer - Returns true if this expression can be emitted to 522 /// IR as a constant, and thus can be used as a constant initializer in C. 523 /// If this expression is not constant and Culprit is non-null, 524 /// it is used to store the address of first non constant expr. 525 bool isConstantInitializer(ASTContext &Ctx, bool ForRef, 526 const Expr **Culprit = nullptr) const; 527 528 /// EvalStatus is a struct with detailed info about an evaluation in progress. 529 struct EvalStatus { 530 /// HasSideEffects - Whether the evaluated expression has side effects. 531 /// For example, (f() && 0) can be folded, but it still has side effects. 532 bool HasSideEffects; 533 534 /// Diag - If this is non-null, it will be filled in with a stack of notes 535 /// indicating why evaluation failed (or why it failed to produce a constant 536 /// expression). 537 /// If the expression is unfoldable, the notes will indicate why it's not 538 /// foldable. If the expression is foldable, but not a constant expression, 539 /// the notes will describes why it isn't a constant expression. If the 540 /// expression *is* a constant expression, no notes will be produced. 541 SmallVectorImpl<PartialDiagnosticAt> *Diag; 542 543 EvalStatus() : HasSideEffects(false), Diag(nullptr) {} 544 545 // hasSideEffects - Return true if the evaluated expression has 546 // side effects. 547 bool hasSideEffects() const { 548 return HasSideEffects; 549 } 550 }; 551 552 /// EvalResult is a struct with detailed info about an evaluated expression. 553 struct EvalResult : EvalStatus { 554 /// Val - This is the value the expression can be folded to. 555 APValue Val; 556 557 // isGlobalLValue - Return true if the evaluated lvalue expression 558 // is global. 559 bool isGlobalLValue() const; 560 }; 561 562 /// EvaluateAsRValue - Return true if this is a constant which we can fold to 563 /// an rvalue using any crazy technique (that has nothing to do with language 564 /// standards) that we want to, even if the expression has side-effects. If 565 /// this function returns true, it returns the folded constant in Result. If 566 /// the expression is a glvalue, an lvalue-to-rvalue conversion will be 567 /// applied. 568 bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const; 569 570 /// EvaluateAsBooleanCondition - Return true if this is a constant 571 /// which we we can fold and convert to a boolean condition using 572 /// any crazy technique that we want to, even if the expression has 573 /// side-effects. 574 bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx) const; 575 576 enum SideEffectsKind { SE_NoSideEffects, SE_AllowSideEffects }; 577 578 /// EvaluateAsInt - Return true if this is a constant which we can fold and 579 /// convert to an integer, using any crazy technique that we want to. 580 bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx, 581 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const; 582 583 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 584 /// constant folded without side-effects, but discard the result. 585 bool isEvaluatable(const ASTContext &Ctx) const; 586 587 /// HasSideEffects - This routine returns true for all those expressions 588 /// which have any effect other than producing a value. Example is a function 589 /// call, volatile variable read, or throwing an exception. 590 bool HasSideEffects(const ASTContext &Ctx) const; 591 592 /// \brief Determine whether this expression involves a call to any function 593 /// that is not trivial. 594 bool hasNonTrivialCall(ASTContext &Ctx); 595 596 /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded 597 /// integer. This must be called on an expression that constant folds to an 598 /// integer. 599 llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, 600 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const; 601 602 void EvaluateForOverflow(const ASTContext &Ctx) const; 603 604 /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an 605 /// lvalue with link time known address, with no side-effects. 606 bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const; 607 608 /// EvaluateAsInitializer - Evaluate an expression as if it were the 609 /// initializer of the given declaration. Returns true if the initializer 610 /// can be folded to a constant, and produces any relevant notes. In C++11, 611 /// notes will be produced if the expression is not a constant expression. 612 bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx, 613 const VarDecl *VD, 614 SmallVectorImpl<PartialDiagnosticAt> &Notes) const; 615 616 /// EvaluateWithSubstitution - Evaluate an expression as if from the context 617 /// of a call to the given function with the given arguments, inside an 618 /// unevaluated context. Returns true if the expression could be folded to a 619 /// constant. 620 bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 621 const FunctionDecl *Callee, 622 ArrayRef<const Expr*> Args) const; 623 624 /// \brief Enumeration used to describe the kind of Null pointer constant 625 /// returned from \c isNullPointerConstant(). 626 enum NullPointerConstantKind { 627 /// \brief Expression is not a Null pointer constant. 628 NPCK_NotNull = 0, 629 630 /// \brief Expression is a Null pointer constant built from a zero integer 631 /// expression that is not a simple, possibly parenthesized, zero literal. 632 /// C++ Core Issue 903 will classify these expressions as "not pointers" 633 /// once it is adopted. 634 /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 635 NPCK_ZeroExpression, 636 637 /// \brief Expression is a Null pointer constant built from a literal zero. 638 NPCK_ZeroLiteral, 639 640 /// \brief Expression is a C++11 nullptr. 641 NPCK_CXX11_nullptr, 642 643 /// \brief Expression is a GNU-style __null constant. 644 NPCK_GNUNull 645 }; 646 647 /// \brief Enumeration used to describe how \c isNullPointerConstant() 648 /// should cope with value-dependent expressions. 649 enum NullPointerConstantValueDependence { 650 /// \brief Specifies that the expression should never be value-dependent. 651 NPC_NeverValueDependent = 0, 652 653 /// \brief Specifies that a value-dependent expression of integral or 654 /// dependent type should be considered a null pointer constant. 655 NPC_ValueDependentIsNull, 656 657 /// \brief Specifies that a value-dependent expression should be considered 658 /// to never be a null pointer constant. 659 NPC_ValueDependentIsNotNull 660 }; 661 662 /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to 663 /// a Null pointer constant. The return value can further distinguish the 664 /// kind of NULL pointer constant that was detected. 665 NullPointerConstantKind isNullPointerConstant( 666 ASTContext &Ctx, 667 NullPointerConstantValueDependence NPC) const; 668 669 /// isOBJCGCCandidate - Return true if this expression may be used in a read/ 670 /// write barrier. 671 bool isOBJCGCCandidate(ASTContext &Ctx) const; 672 673 /// \brief Returns true if this expression is a bound member function. 674 bool isBoundMemberFunction(ASTContext &Ctx) const; 675 676 /// \brief Given an expression of bound-member type, find the type 677 /// of the member. Returns null if this is an *overloaded* bound 678 /// member expression. 679 static QualType findBoundMemberType(const Expr *expr); 680 681 /// IgnoreImpCasts - Skip past any implicit casts which might 682 /// surround this expression. Only skips ImplicitCastExprs. 683 Expr *IgnoreImpCasts() LLVM_READONLY; 684 685 /// IgnoreImplicit - Skip past any implicit AST nodes which might 686 /// surround this expression. 687 Expr *IgnoreImplicit() LLVM_READONLY { 688 return cast<Expr>(Stmt::IgnoreImplicit()); 689 } 690 691 const Expr *IgnoreImplicit() const LLVM_READONLY { 692 return const_cast<Expr*>(this)->IgnoreImplicit(); 693 } 694 695 /// IgnoreParens - Ignore parentheses. If this Expr is a ParenExpr, return 696 /// its subexpression. If that subexpression is also a ParenExpr, 697 /// then this method recursively returns its subexpression, and so forth. 698 /// Otherwise, the method returns the current Expr. 699 Expr *IgnoreParens() LLVM_READONLY; 700 701 /// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr 702 /// or CastExprs, returning their operand. 703 Expr *IgnoreParenCasts() LLVM_READONLY; 704 705 /// Ignore casts. Strip off any CastExprs, returning their operand. 706 Expr *IgnoreCasts() LLVM_READONLY; 707 708 /// IgnoreParenImpCasts - Ignore parentheses and implicit casts. Strip off 709 /// any ParenExpr or ImplicitCastExprs, returning their operand. 710 Expr *IgnoreParenImpCasts() LLVM_READONLY; 711 712 /// IgnoreConversionOperator - Ignore conversion operator. If this Expr is a 713 /// call to a conversion operator, return the argument. 714 Expr *IgnoreConversionOperator() LLVM_READONLY; 715 716 const Expr *IgnoreConversionOperator() const LLVM_READONLY { 717 return const_cast<Expr*>(this)->IgnoreConversionOperator(); 718 } 719 720 const Expr *IgnoreParenImpCasts() const LLVM_READONLY { 721 return const_cast<Expr*>(this)->IgnoreParenImpCasts(); 722 } 723 724 /// Ignore parentheses and lvalue casts. Strip off any ParenExpr and 725 /// CastExprs that represent lvalue casts, returning their operand. 726 Expr *IgnoreParenLValueCasts() LLVM_READONLY; 727 728 const Expr *IgnoreParenLValueCasts() const LLVM_READONLY { 729 return const_cast<Expr*>(this)->IgnoreParenLValueCasts(); 730 } 731 732 /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the 733 /// value (including ptr->int casts of the same size). Strip off any 734 /// ParenExpr or CastExprs, returning their operand. 735 Expr *IgnoreParenNoopCasts(ASTContext &Ctx) LLVM_READONLY; 736 737 /// Ignore parentheses and derived-to-base casts. 738 Expr *ignoreParenBaseCasts() LLVM_READONLY; 739 740 const Expr *ignoreParenBaseCasts() const LLVM_READONLY { 741 return const_cast<Expr*>(this)->ignoreParenBaseCasts(); 742 } 743 744 /// \brief Determine whether this expression is a default function argument. 745 /// 746 /// Default arguments are implicitly generated in the abstract syntax tree 747 /// by semantic analysis for function calls, object constructions, etc. in 748 /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes; 749 /// this routine also looks through any implicit casts to determine whether 750 /// the expression is a default argument. 751 bool isDefaultArgument() const; 752 753 /// \brief Determine whether the result of this expression is a 754 /// temporary object of the given class type. 755 bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const; 756 757 /// \brief Whether this expression is an implicit reference to 'this' in C++. 758 bool isImplicitCXXThis() const; 759 760 const Expr *IgnoreImpCasts() const LLVM_READONLY { 761 return const_cast<Expr*>(this)->IgnoreImpCasts(); 762 } 763 const Expr *IgnoreParens() const LLVM_READONLY { 764 return const_cast<Expr*>(this)->IgnoreParens(); 765 } 766 const Expr *IgnoreParenCasts() const LLVM_READONLY { 767 return const_cast<Expr*>(this)->IgnoreParenCasts(); 768 } 769 /// Strip off casts, but keep parentheses. 770 const Expr *IgnoreCasts() const LLVM_READONLY { 771 return const_cast<Expr*>(this)->IgnoreCasts(); 772 } 773 774 const Expr *IgnoreParenNoopCasts(ASTContext &Ctx) const LLVM_READONLY { 775 return const_cast<Expr*>(this)->IgnoreParenNoopCasts(Ctx); 776 } 777 778 static bool hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs); 779 780 /// \brief For an expression of class type or pointer to class type, 781 /// return the most derived class decl the expression is known to refer to. 782 /// 783 /// If this expression is a cast, this method looks through it to find the 784 /// most derived decl that can be inferred from the expression. 785 /// This is valid because derived-to-base conversions have undefined 786 /// behavior if the object isn't dynamically of the derived type. 787 const CXXRecordDecl *getBestDynamicClassType() const; 788 789 /// Walk outwards from an expression we want to bind a reference to and 790 /// find the expression whose lifetime needs to be extended. Record 791 /// the LHSs of comma expressions and adjustments needed along the path. 792 const Expr *skipRValueSubobjectAdjustments( 793 SmallVectorImpl<const Expr *> &CommaLHS, 794 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const; 795 796 static bool classof(const Stmt *T) { 797 return T->getStmtClass() >= firstExprConstant && 798 T->getStmtClass() <= lastExprConstant; 799 } 800 }; 801 802 803 //===----------------------------------------------------------------------===// 804 // Primary Expressions. 805 //===----------------------------------------------------------------------===// 806 807 /// OpaqueValueExpr - An expression referring to an opaque object of a 808 /// fixed type and value class. These don't correspond to concrete 809 /// syntax; instead they're used to express operations (usually copy 810 /// operations) on values whose source is generally obvious from 811 /// context. 812 class OpaqueValueExpr : public Expr { 813 friend class ASTStmtReader; 814 Expr *SourceExpr; 815 SourceLocation Loc; 816 817 public: 818 OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK, 819 ExprObjectKind OK = OK_Ordinary, 820 Expr *SourceExpr = nullptr) 821 : Expr(OpaqueValueExprClass, T, VK, OK, 822 T->isDependentType(), 823 T->isDependentType() || 824 (SourceExpr && SourceExpr->isValueDependent()), 825 T->isInstantiationDependentType(), 826 false), 827 SourceExpr(SourceExpr), Loc(Loc) { 828 } 829 830 /// Given an expression which invokes a copy constructor --- i.e. a 831 /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups --- 832 /// find the OpaqueValueExpr that's the source of the construction. 833 static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr); 834 835 explicit OpaqueValueExpr(EmptyShell Empty) 836 : Expr(OpaqueValueExprClass, Empty) { } 837 838 /// \brief Retrieve the location of this expression. 839 SourceLocation getLocation() const { return Loc; } 840 841 SourceLocation getLocStart() const LLVM_READONLY { 842 return SourceExpr ? SourceExpr->getLocStart() : Loc; 843 } 844 SourceLocation getLocEnd() const LLVM_READONLY { 845 return SourceExpr ? SourceExpr->getLocEnd() : Loc; 846 } 847 SourceLocation getExprLoc() const LLVM_READONLY { 848 if (SourceExpr) return SourceExpr->getExprLoc(); 849 return Loc; 850 } 851 852 child_range children() { return child_range(); } 853 854 /// The source expression of an opaque value expression is the 855 /// expression which originally generated the value. This is 856 /// provided as a convenience for analyses that don't wish to 857 /// precisely model the execution behavior of the program. 858 /// 859 /// The source expression is typically set when building the 860 /// expression which binds the opaque value expression in the first 861 /// place. 862 Expr *getSourceExpr() const { return SourceExpr; } 863 864 static bool classof(const Stmt *T) { 865 return T->getStmtClass() == OpaqueValueExprClass; 866 } 867 }; 868 869 /// \brief A reference to a declared variable, function, enum, etc. 870 /// [C99 6.5.1p2] 871 /// 872 /// This encodes all the information about how a declaration is referenced 873 /// within an expression. 874 /// 875 /// There are several optional constructs attached to DeclRefExprs only when 876 /// they apply in order to conserve memory. These are laid out past the end of 877 /// the object, and flags in the DeclRefExprBitfield track whether they exist: 878 /// 879 /// DeclRefExprBits.HasQualifier: 880 /// Specifies when this declaration reference expression has a C++ 881 /// nested-name-specifier. 882 /// DeclRefExprBits.HasFoundDecl: 883 /// Specifies when this declaration reference expression has a record of 884 /// a NamedDecl (different from the referenced ValueDecl) which was found 885 /// during name lookup and/or overload resolution. 886 /// DeclRefExprBits.HasTemplateKWAndArgsInfo: 887 /// Specifies when this declaration reference expression has an explicit 888 /// C++ template keyword and/or template argument list. 889 /// DeclRefExprBits.RefersToEnclosingLocal 890 /// Specifies when this declaration reference expression (validly) 891 /// refers to a local variable from a different function. 892 class DeclRefExpr : public Expr { 893 /// \brief The declaration that we are referencing. 894 ValueDecl *D; 895 896 /// \brief The location of the declaration name itself. 897 SourceLocation Loc; 898 899 /// \brief Provides source/type location info for the declaration name 900 /// embedded in D. 901 DeclarationNameLoc DNLoc; 902 903 /// \brief Helper to retrieve the optional NestedNameSpecifierLoc. 904 NestedNameSpecifierLoc &getInternalQualifierLoc() { 905 assert(hasQualifier()); 906 return *reinterpret_cast<NestedNameSpecifierLoc *>(this + 1); 907 } 908 909 /// \brief Helper to retrieve the optional NestedNameSpecifierLoc. 910 const NestedNameSpecifierLoc &getInternalQualifierLoc() const { 911 return const_cast<DeclRefExpr *>(this)->getInternalQualifierLoc(); 912 } 913 914 /// \brief Test whether there is a distinct FoundDecl attached to the end of 915 /// this DRE. 916 bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; } 917 918 /// \brief Helper to retrieve the optional NamedDecl through which this 919 /// reference occurred. 920 NamedDecl *&getInternalFoundDecl() { 921 assert(hasFoundDecl()); 922 if (hasQualifier()) 923 return *reinterpret_cast<NamedDecl **>(&getInternalQualifierLoc() + 1); 924 return *reinterpret_cast<NamedDecl **>(this + 1); 925 } 926 927 /// \brief Helper to retrieve the optional NamedDecl through which this 928 /// reference occurred. 929 NamedDecl *getInternalFoundDecl() const { 930 return const_cast<DeclRefExpr *>(this)->getInternalFoundDecl(); 931 } 932 933 DeclRefExpr(const ASTContext &Ctx, 934 NestedNameSpecifierLoc QualifierLoc, 935 SourceLocation TemplateKWLoc, 936 ValueDecl *D, bool refersToEnclosingLocal, 937 const DeclarationNameInfo &NameInfo, 938 NamedDecl *FoundD, 939 const TemplateArgumentListInfo *TemplateArgs, 940 QualType T, ExprValueKind VK); 941 942 /// \brief Construct an empty declaration reference expression. 943 explicit DeclRefExpr(EmptyShell Empty) 944 : Expr(DeclRefExprClass, Empty) { } 945 946 /// \brief Computes the type- and value-dependence flags for this 947 /// declaration reference expression. 948 void computeDependence(const ASTContext &C); 949 950 public: 951 DeclRefExpr(ValueDecl *D, bool refersToEnclosingLocal, QualType T, 952 ExprValueKind VK, SourceLocation L, 953 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) 954 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false), 955 D(D), Loc(L), DNLoc(LocInfo) { 956 DeclRefExprBits.HasQualifier = 0; 957 DeclRefExprBits.HasTemplateKWAndArgsInfo = 0; 958 DeclRefExprBits.HasFoundDecl = 0; 959 DeclRefExprBits.HadMultipleCandidates = 0; 960 DeclRefExprBits.RefersToEnclosingLocal = refersToEnclosingLocal; 961 computeDependence(D->getASTContext()); 962 } 963 964 static DeclRefExpr * 965 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, 966 SourceLocation TemplateKWLoc, ValueDecl *D, bool isEnclosingLocal, 967 SourceLocation NameLoc, QualType T, ExprValueKind VK, 968 NamedDecl *FoundD = nullptr, 969 const TemplateArgumentListInfo *TemplateArgs = nullptr); 970 971 static DeclRefExpr * 972 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, 973 SourceLocation TemplateKWLoc, ValueDecl *D, bool isEnclosingLocal, 974 const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK, 975 NamedDecl *FoundD = nullptr, 976 const TemplateArgumentListInfo *TemplateArgs = nullptr); 977 978 /// \brief Construct an empty declaration reference expression. 979 static DeclRefExpr *CreateEmpty(const ASTContext &Context, 980 bool HasQualifier, 981 bool HasFoundDecl, 982 bool HasTemplateKWAndArgsInfo, 983 unsigned NumTemplateArgs); 984 985 ValueDecl *getDecl() { return D; } 986 const ValueDecl *getDecl() const { return D; } 987 void setDecl(ValueDecl *NewD) { D = NewD; } 988 989 DeclarationNameInfo getNameInfo() const { 990 return DeclarationNameInfo(getDecl()->getDeclName(), Loc, DNLoc); 991 } 992 993 SourceLocation getLocation() const { return Loc; } 994 void setLocation(SourceLocation L) { Loc = L; } 995 SourceLocation getLocStart() const LLVM_READONLY; 996 SourceLocation getLocEnd() const LLVM_READONLY; 997 998 /// \brief Determine whether this declaration reference was preceded by a 999 /// C++ nested-name-specifier, e.g., \c N::foo. 1000 bool hasQualifier() const { return DeclRefExprBits.HasQualifier; } 1001 1002 /// \brief If the name was qualified, retrieves the nested-name-specifier 1003 /// that precedes the name. Otherwise, returns NULL. 1004 NestedNameSpecifier *getQualifier() const { 1005 if (!hasQualifier()) 1006 return nullptr; 1007 1008 return getInternalQualifierLoc().getNestedNameSpecifier(); 1009 } 1010 1011 /// \brief If the name was qualified, retrieves the nested-name-specifier 1012 /// that precedes the name, with source-location information. 1013 NestedNameSpecifierLoc getQualifierLoc() const { 1014 if (!hasQualifier()) 1015 return NestedNameSpecifierLoc(); 1016 1017 return getInternalQualifierLoc(); 1018 } 1019 1020 /// \brief Get the NamedDecl through which this reference occurred. 1021 /// 1022 /// This Decl may be different from the ValueDecl actually referred to in the 1023 /// presence of using declarations, etc. It always returns non-NULL, and may 1024 /// simple return the ValueDecl when appropriate. 1025 NamedDecl *getFoundDecl() { 1026 return hasFoundDecl() ? getInternalFoundDecl() : D; 1027 } 1028 1029 /// \brief Get the NamedDecl through which this reference occurred. 1030 /// See non-const variant. 1031 const NamedDecl *getFoundDecl() const { 1032 return hasFoundDecl() ? getInternalFoundDecl() : D; 1033 } 1034 1035 bool hasTemplateKWAndArgsInfo() const { 1036 return DeclRefExprBits.HasTemplateKWAndArgsInfo; 1037 } 1038 1039 /// \brief Return the optional template keyword and arguments info. 1040 ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() { 1041 if (!hasTemplateKWAndArgsInfo()) 1042 return nullptr; 1043 1044 if (hasFoundDecl()) 1045 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>( 1046 &getInternalFoundDecl() + 1); 1047 1048 if (hasQualifier()) 1049 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>( 1050 &getInternalQualifierLoc() + 1); 1051 1052 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(this + 1); 1053 } 1054 1055 /// \brief Return the optional template keyword and arguments info. 1056 const ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() const { 1057 return const_cast<DeclRefExpr*>(this)->getTemplateKWAndArgsInfo(); 1058 } 1059 1060 /// \brief Retrieve the location of the template keyword preceding 1061 /// this name, if any. 1062 SourceLocation getTemplateKeywordLoc() const { 1063 if (!hasTemplateKWAndArgsInfo()) return SourceLocation(); 1064 return getTemplateKWAndArgsInfo()->getTemplateKeywordLoc(); 1065 } 1066 1067 /// \brief Retrieve the location of the left angle bracket starting the 1068 /// explicit template argument list following the name, if any. 1069 SourceLocation getLAngleLoc() const { 1070 if (!hasTemplateKWAndArgsInfo()) return SourceLocation(); 1071 return getTemplateKWAndArgsInfo()->LAngleLoc; 1072 } 1073 1074 /// \brief Retrieve the location of the right angle bracket ending the 1075 /// explicit template argument list following the name, if any. 1076 SourceLocation getRAngleLoc() const { 1077 if (!hasTemplateKWAndArgsInfo()) return SourceLocation(); 1078 return getTemplateKWAndArgsInfo()->RAngleLoc; 1079 } 1080 1081 /// \brief Determines whether the name in this declaration reference 1082 /// was preceded by the template keyword. 1083 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); } 1084 1085 /// \brief Determines whether this declaration reference was followed by an 1086 /// explicit template argument list. 1087 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); } 1088 1089 /// \brief Retrieve the explicit template argument list that followed the 1090 /// member template name. 1091 ASTTemplateArgumentListInfo &getExplicitTemplateArgs() { 1092 assert(hasExplicitTemplateArgs()); 1093 return *getTemplateKWAndArgsInfo(); 1094 } 1095 1096 /// \brief Retrieve the explicit template argument list that followed the 1097 /// member template name. 1098 const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const { 1099 return const_cast<DeclRefExpr *>(this)->getExplicitTemplateArgs(); 1100 } 1101 1102 /// \brief Retrieves the optional explicit template arguments. 1103 /// This points to the same data as getExplicitTemplateArgs(), but 1104 /// returns null if there are no explicit template arguments. 1105 const ASTTemplateArgumentListInfo *getOptionalExplicitTemplateArgs() const { 1106 if (!hasExplicitTemplateArgs()) return nullptr; 1107 return &getExplicitTemplateArgs(); 1108 } 1109 1110 /// \brief Copies the template arguments (if present) into the given 1111 /// structure. 1112 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const { 1113 if (hasExplicitTemplateArgs()) 1114 getExplicitTemplateArgs().copyInto(List); 1115 } 1116 1117 /// \brief Retrieve the template arguments provided as part of this 1118 /// template-id. 1119 const TemplateArgumentLoc *getTemplateArgs() const { 1120 if (!hasExplicitTemplateArgs()) 1121 return nullptr; 1122 1123 return getExplicitTemplateArgs().getTemplateArgs(); 1124 } 1125 1126 /// \brief Retrieve the number of template arguments provided as part of this 1127 /// template-id. 1128 unsigned getNumTemplateArgs() const { 1129 if (!hasExplicitTemplateArgs()) 1130 return 0; 1131 1132 return getExplicitTemplateArgs().NumTemplateArgs; 1133 } 1134 1135 /// \brief Returns true if this expression refers to a function that 1136 /// was resolved from an overloaded set having size greater than 1. 1137 bool hadMultipleCandidates() const { 1138 return DeclRefExprBits.HadMultipleCandidates; 1139 } 1140 /// \brief Sets the flag telling whether this expression refers to 1141 /// a function that was resolved from an overloaded set having size 1142 /// greater than 1. 1143 void setHadMultipleCandidates(bool V = true) { 1144 DeclRefExprBits.HadMultipleCandidates = V; 1145 } 1146 1147 /// Does this DeclRefExpr refer to a local declaration from an 1148 /// enclosing function scope? 1149 bool refersToEnclosingLocal() const { 1150 return DeclRefExprBits.RefersToEnclosingLocal; 1151 } 1152 1153 static bool classof(const Stmt *T) { 1154 return T->getStmtClass() == DeclRefExprClass; 1155 } 1156 1157 // Iterators 1158 child_range children() { return child_range(); } 1159 1160 friend class ASTStmtReader; 1161 friend class ASTStmtWriter; 1162 }; 1163 1164 /// PredefinedExpr - [C99 6.4.2.2] - A predefined identifier such as __func__. 1165 class PredefinedExpr : public Expr { 1166 public: 1167 enum IdentType { 1168 Func, 1169 Function, 1170 LFunction, // Same as Function, but as wide string. 1171 FuncDName, 1172 FuncSig, 1173 PrettyFunction, 1174 /// PrettyFunctionNoVirtual - The same as PrettyFunction, except that the 1175 /// 'virtual' keyword is omitted for virtual member functions. 1176 PrettyFunctionNoVirtual 1177 }; 1178 1179 private: 1180 SourceLocation Loc; 1181 IdentType Type; 1182 public: 1183 PredefinedExpr(SourceLocation l, QualType type, IdentType IT) 1184 : Expr(PredefinedExprClass, type, VK_LValue, OK_Ordinary, 1185 type->isDependentType(), type->isDependentType(), 1186 type->isInstantiationDependentType(), 1187 /*ContainsUnexpandedParameterPack=*/false), 1188 Loc(l), Type(IT) {} 1189 1190 /// \brief Construct an empty predefined expression. 1191 explicit PredefinedExpr(EmptyShell Empty) 1192 : Expr(PredefinedExprClass, Empty) { } 1193 1194 IdentType getIdentType() const { return Type; } 1195 void setIdentType(IdentType IT) { Type = IT; } 1196 1197 SourceLocation getLocation() const { return Loc; } 1198 void setLocation(SourceLocation L) { Loc = L; } 1199 1200 static std::string ComputeName(IdentType IT, const Decl *CurrentDecl); 1201 1202 SourceLocation getLocStart() const LLVM_READONLY { return Loc; } 1203 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; } 1204 1205 static bool classof(const Stmt *T) { 1206 return T->getStmtClass() == PredefinedExprClass; 1207 } 1208 1209 // Iterators 1210 child_range children() { return child_range(); } 1211 }; 1212 1213 /// \brief Used by IntegerLiteral/FloatingLiteral to store the numeric without 1214 /// leaking memory. 1215 /// 1216 /// For large floats/integers, APFloat/APInt will allocate memory from the heap 1217 /// to represent these numbers. Unfortunately, when we use a BumpPtrAllocator 1218 /// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with 1219 /// the APFloat/APInt values will never get freed. APNumericStorage uses 1220 /// ASTContext's allocator for memory allocation. 1221 class APNumericStorage { 1222 union { 1223 uint64_t VAL; ///< Used to store the <= 64 bits integer value. 1224 uint64_t *pVal; ///< Used to store the >64 bits integer value. 1225 }; 1226 unsigned BitWidth; 1227 1228 bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; } 1229 1230 APNumericStorage(const APNumericStorage &) LLVM_DELETED_FUNCTION; 1231 void operator=(const APNumericStorage &) LLVM_DELETED_FUNCTION; 1232 1233 protected: 1234 APNumericStorage() : VAL(0), BitWidth(0) { } 1235 1236 llvm::APInt getIntValue() const { 1237 unsigned NumWords = llvm::APInt::getNumWords(BitWidth); 1238 if (NumWords > 1) 1239 return llvm::APInt(BitWidth, NumWords, pVal); 1240 else 1241 return llvm::APInt(BitWidth, VAL); 1242 } 1243 void setIntValue(const ASTContext &C, const llvm::APInt &Val); 1244 }; 1245 1246 class APIntStorage : private APNumericStorage { 1247 public: 1248 llvm::APInt getValue() const { return getIntValue(); } 1249 void setValue(const ASTContext &C, const llvm::APInt &Val) { 1250 setIntValue(C, Val); 1251 } 1252 }; 1253 1254 class APFloatStorage : private APNumericStorage { 1255 public: 1256 llvm::APFloat getValue(const llvm::fltSemantics &Semantics) const { 1257 return llvm::APFloat(Semantics, getIntValue()); 1258 } 1259 void setValue(const ASTContext &C, const llvm::APFloat &Val) { 1260 setIntValue(C, Val.bitcastToAPInt()); 1261 } 1262 }; 1263 1264 class IntegerLiteral : public Expr, public APIntStorage { 1265 SourceLocation Loc; 1266 1267 /// \brief Construct an empty integer literal. 1268 explicit IntegerLiteral(EmptyShell Empty) 1269 : Expr(IntegerLiteralClass, Empty) { } 1270 1271 public: 1272 // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy, 1273 // or UnsignedLongLongTy 1274 IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type, 1275 SourceLocation l); 1276 1277 /// \brief Returns a new integer literal with value 'V' and type 'type'. 1278 /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy, 1279 /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V 1280 /// \param V - the value that the returned integer literal contains. 1281 static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V, 1282 QualType type, SourceLocation l); 1283 /// \brief Returns a new empty integer literal. 1284 static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty); 1285 1286 SourceLocation getLocStart() const LLVM_READONLY { return Loc; } 1287 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; } 1288 1289 /// \brief Retrieve the location of the literal. 1290 SourceLocation getLocation() const { return Loc; } 1291 1292 void setLocation(SourceLocation Location) { Loc = Location; } 1293 1294 static bool classof(const Stmt *T) { 1295 return T->getStmtClass() == IntegerLiteralClass; 1296 } 1297 1298 // Iterators 1299 child_range children() { return child_range(); } 1300 }; 1301 1302 class CharacterLiteral : public Expr { 1303 public: 1304 enum CharacterKind { 1305 Ascii, 1306 Wide, 1307 UTF16, 1308 UTF32 1309 }; 1310 1311 private: 1312 unsigned Value; 1313 SourceLocation Loc; 1314 public: 1315 // type should be IntTy 1316 CharacterLiteral(unsigned value, CharacterKind kind, QualType type, 1317 SourceLocation l) 1318 : Expr(CharacterLiteralClass, type, VK_RValue, OK_Ordinary, false, false, 1319 false, false), 1320 Value(value), Loc(l) { 1321 CharacterLiteralBits.Kind = kind; 1322 } 1323 1324 /// \brief Construct an empty character literal. 1325 CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { } 1326 1327 SourceLocation getLocation() const { return Loc; } 1328 CharacterKind getKind() const { 1329 return static_cast<CharacterKind>(CharacterLiteralBits.Kind); 1330 } 1331 1332 SourceLocation getLocStart() const LLVM_READONLY { return Loc; } 1333 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; } 1334 1335 unsigned getValue() const { return Value; } 1336 1337 void setLocation(SourceLocation Location) { Loc = Location; } 1338 void setKind(CharacterKind kind) { CharacterLiteralBits.Kind = kind; } 1339 void setValue(unsigned Val) { Value = Val; } 1340 1341 static bool classof(const Stmt *T) { 1342 return T->getStmtClass() == CharacterLiteralClass; 1343 } 1344 1345 // Iterators 1346 child_range children() { return child_range(); } 1347 }; 1348 1349 class FloatingLiteral : public Expr, private APFloatStorage { 1350 SourceLocation Loc; 1351 1352 FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact, 1353 QualType Type, SourceLocation L); 1354 1355 /// \brief Construct an empty floating-point literal. 1356 explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty); 1357 1358 public: 1359 static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V, 1360 bool isexact, QualType Type, SourceLocation L); 1361 static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty); 1362 1363 llvm::APFloat getValue() const { 1364 return APFloatStorage::getValue(getSemantics()); 1365 } 1366 void setValue(const ASTContext &C, const llvm::APFloat &Val) { 1367 assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics"); 1368 APFloatStorage::setValue(C, Val); 1369 } 1370 1371 /// Get a raw enumeration value representing the floating-point semantics of 1372 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation. 1373 APFloatSemantics getRawSemantics() const { 1374 return static_cast<APFloatSemantics>(FloatingLiteralBits.Semantics); 1375 } 1376 1377 /// Set the raw enumeration value representing the floating-point semantics of 1378 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation. 1379 void setRawSemantics(APFloatSemantics Sem) { 1380 FloatingLiteralBits.Semantics = Sem; 1381 } 1382 1383 /// Return the APFloat semantics this literal uses. 1384 const llvm::fltSemantics &getSemantics() const; 1385 1386 /// Set the APFloat semantics this literal uses. 1387 void setSemantics(const llvm::fltSemantics &Sem); 1388 1389 bool isExact() const { return FloatingLiteralBits.IsExact; } 1390 void setExact(bool E) { FloatingLiteralBits.IsExact = E; } 1391 1392 /// getValueAsApproximateDouble - This returns the value as an inaccurate 1393 /// double. Note that this may cause loss of precision, but is useful for 1394 /// debugging dumps, etc. 1395 double getValueAsApproximateDouble() const; 1396 1397 SourceLocation getLocation() const { return Loc; } 1398 void setLocation(SourceLocation L) { Loc = L; } 1399 1400 SourceLocation getLocStart() const LLVM_READONLY { return Loc; } 1401 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; } 1402 1403 static bool classof(const Stmt *T) { 1404 return T->getStmtClass() == FloatingLiteralClass; 1405 } 1406 1407 // Iterators 1408 child_range children() { return child_range(); } 1409 }; 1410 1411 /// ImaginaryLiteral - We support imaginary integer and floating point literals, 1412 /// like "1.0i". We represent these as a wrapper around FloatingLiteral and 1413 /// IntegerLiteral classes. Instances of this class always have a Complex type 1414 /// whose element type matches the subexpression. 1415 /// 1416 class ImaginaryLiteral : public Expr { 1417 Stmt *Val; 1418 public: 1419 ImaginaryLiteral(Expr *val, QualType Ty) 1420 : Expr(ImaginaryLiteralClass, Ty, VK_RValue, OK_Ordinary, false, false, 1421 false, false), 1422 Val(val) {} 1423 1424 /// \brief Build an empty imaginary literal. 1425 explicit ImaginaryLiteral(EmptyShell Empty) 1426 : Expr(ImaginaryLiteralClass, Empty) { } 1427 1428 const Expr *getSubExpr() const { return cast<Expr>(Val); } 1429 Expr *getSubExpr() { return cast<Expr>(Val); } 1430 void setSubExpr(Expr *E) { Val = E; } 1431 1432 SourceLocation getLocStart() const LLVM_READONLY { return Val->getLocStart(); } 1433 SourceLocation getLocEnd() const LLVM_READONLY { return Val->getLocEnd(); } 1434 1435 static bool classof(const Stmt *T) { 1436 return T->getStmtClass() == ImaginaryLiteralClass; 1437 } 1438 1439 // Iterators 1440 child_range children() { return child_range(&Val, &Val+1); } 1441 }; 1442 1443 /// StringLiteral - This represents a string literal expression, e.g. "foo" 1444 /// or L"bar" (wide strings). The actual string is returned by getBytes() 1445 /// is NOT null-terminated, and the length of the string is determined by 1446 /// calling getByteLength(). The C type for a string is always a 1447 /// ConstantArrayType. In C++, the char type is const qualified, in C it is 1448 /// not. 1449 /// 1450 /// Note that strings in C can be formed by concatenation of multiple string 1451 /// literal pptokens in translation phase #6. This keeps track of the locations 1452 /// of each of these pieces. 1453 /// 1454 /// Strings in C can also be truncated and extended by assigning into arrays, 1455 /// e.g. with constructs like: 1456 /// char X[2] = "foobar"; 1457 /// In this case, getByteLength() will return 6, but the string literal will 1458 /// have type "char[2]". 1459 class StringLiteral : public Expr { 1460 public: 1461 enum StringKind { 1462 Ascii, 1463 Wide, 1464 UTF8, 1465 UTF16, 1466 UTF32 1467 }; 1468 1469 private: 1470 friend class ASTStmtReader; 1471 1472 union { 1473 const char *asChar; 1474 const uint16_t *asUInt16; 1475 const uint32_t *asUInt32; 1476 } StrData; 1477 unsigned Length; 1478 unsigned CharByteWidth : 4; 1479 unsigned Kind : 3; 1480 unsigned IsPascal : 1; 1481 unsigned NumConcatenated; 1482 SourceLocation TokLocs[1]; 1483 1484 StringLiteral(QualType Ty) : 1485 Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false, 1486 false) {} 1487 1488 static int mapCharByteWidth(TargetInfo const &target,StringKind k); 1489 1490 public: 1491 /// This is the "fully general" constructor that allows representation of 1492 /// strings formed from multiple concatenated tokens. 1493 static StringLiteral *Create(const ASTContext &C, StringRef Str, 1494 StringKind Kind, bool Pascal, QualType Ty, 1495 const SourceLocation *Loc, unsigned NumStrs); 1496 1497 /// Simple constructor for string literals made from one token. 1498 static StringLiteral *Create(const ASTContext &C, StringRef Str, 1499 StringKind Kind, bool Pascal, QualType Ty, 1500 SourceLocation Loc) { 1501 return Create(C, Str, Kind, Pascal, Ty, &Loc, 1); 1502 } 1503 1504 /// \brief Construct an empty string literal. 1505 static StringLiteral *CreateEmpty(const ASTContext &C, unsigned NumStrs); 1506 1507 StringRef getString() const { 1508 assert(CharByteWidth==1 1509 && "This function is used in places that assume strings use char"); 1510 return StringRef(StrData.asChar, getByteLength()); 1511 } 1512 1513 /// Allow access to clients that need the byte representation, such as 1514 /// ASTWriterStmt::VisitStringLiteral(). 1515 StringRef getBytes() const { 1516 // FIXME: StringRef may not be the right type to use as a result for this. 1517 if (CharByteWidth == 1) 1518 return StringRef(StrData.asChar, getByteLength()); 1519 if (CharByteWidth == 4) 1520 return StringRef(reinterpret_cast<const char*>(StrData.asUInt32), 1521 getByteLength()); 1522 assert(CharByteWidth == 2 && "unsupported CharByteWidth"); 1523 return StringRef(reinterpret_cast<const char*>(StrData.asUInt16), 1524 getByteLength()); 1525 } 1526 1527 void outputString(raw_ostream &OS) const; 1528 1529 uint32_t getCodeUnit(size_t i) const { 1530 assert(i < Length && "out of bounds access"); 1531 if (CharByteWidth == 1) 1532 return static_cast<unsigned char>(StrData.asChar[i]); 1533 if (CharByteWidth == 4) 1534 return StrData.asUInt32[i]; 1535 assert(CharByteWidth == 2 && "unsupported CharByteWidth"); 1536 return StrData.asUInt16[i]; 1537 } 1538 1539 unsigned getByteLength() const { return CharByteWidth*Length; } 1540 unsigned getLength() const { return Length; } 1541 unsigned getCharByteWidth() const { return CharByteWidth; } 1542 1543 /// \brief Sets the string data to the given string data. 1544 void setString(const ASTContext &C, StringRef Str, 1545 StringKind Kind, bool IsPascal); 1546 1547 StringKind getKind() const { return static_cast<StringKind>(Kind); } 1548 1549 1550 bool isAscii() const { return Kind == Ascii; } 1551 bool isWide() const { return Kind == Wide; } 1552 bool isUTF8() const { return Kind == UTF8; } 1553 bool isUTF16() const { return Kind == UTF16; } 1554 bool isUTF32() const { return Kind == UTF32; } 1555 bool isPascal() const { return IsPascal; } 1556 1557 bool containsNonAsciiOrNull() const { 1558 StringRef Str = getString(); 1559 for (unsigned i = 0, e = Str.size(); i != e; ++i) 1560 if (!isASCII(Str[i]) || !Str[i]) 1561 return true; 1562 return false; 1563 } 1564 1565 /// getNumConcatenated - Get the number of string literal tokens that were 1566 /// concatenated in translation phase #6 to form this string literal. 1567 unsigned getNumConcatenated() const { return NumConcatenated; } 1568 1569 SourceLocation getStrTokenLoc(unsigned TokNum) const { 1570 assert(TokNum < NumConcatenated && "Invalid tok number"); 1571 return TokLocs[TokNum]; 1572 } 1573 void setStrTokenLoc(unsigned TokNum, SourceLocation L) { 1574 assert(TokNum < NumConcatenated && "Invalid tok number"); 1575 TokLocs[TokNum] = L; 1576 } 1577 1578 /// getLocationOfByte - Return a source location that points to the specified 1579 /// byte of this string literal. 1580 /// 1581 /// Strings are amazingly complex. They can be formed from multiple tokens 1582 /// and can have escape sequences in them in addition to the usual trigraph 1583 /// and escaped newline business. This routine handles this complexity. 1584 /// 1585 SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM, 1586 const LangOptions &Features, 1587 const TargetInfo &Target) const; 1588 1589 typedef const SourceLocation *tokloc_iterator; 1590 tokloc_iterator tokloc_begin() const { return TokLocs; } 1591 tokloc_iterator tokloc_end() const { return TokLocs+NumConcatenated; } 1592 1593 SourceLocation getLocStart() const LLVM_READONLY { return TokLocs[0]; } 1594 SourceLocation getLocEnd() const LLVM_READONLY { 1595 return TokLocs[NumConcatenated - 1]; 1596 } 1597 1598 static bool classof(const Stmt *T) { 1599 return T->getStmtClass() == StringLiteralClass; 1600 } 1601 1602 // Iterators 1603 child_range children() { return child_range(); } 1604 }; 1605 1606 /// ParenExpr - This represents a parethesized expression, e.g. "(1)". This 1607 /// AST node is only formed if full location information is requested. 1608 class ParenExpr : public Expr { 1609 SourceLocation L, R; 1610 Stmt *Val; 1611 public: 1612 ParenExpr(SourceLocation l, SourceLocation r, Expr *val) 1613 : Expr(ParenExprClass, val->getType(), 1614 val->getValueKind(), val->getObjectKind(), 1615 val->isTypeDependent(), val->isValueDependent(), 1616 val->isInstantiationDependent(), 1617 val->containsUnexpandedParameterPack()), 1618 L(l), R(r), Val(val) {} 1619 1620 /// \brief Construct an empty parenthesized expression. 1621 explicit ParenExpr(EmptyShell Empty) 1622 : Expr(ParenExprClass, Empty) { } 1623 1624 const Expr *getSubExpr() const { return cast<Expr>(Val); } 1625 Expr *getSubExpr() { return cast<Expr>(Val); } 1626 void setSubExpr(Expr *E) { Val = E; } 1627 1628 SourceLocation getLocStart() const LLVM_READONLY { return L; } 1629 SourceLocation getLocEnd() const LLVM_READONLY { return R; } 1630 1631 /// \brief Get the location of the left parentheses '('. 1632 SourceLocation getLParen() const { return L; } 1633 void setLParen(SourceLocation Loc) { L = Loc; } 1634 1635 /// \brief Get the location of the right parentheses ')'. 1636 SourceLocation getRParen() const { return R; } 1637 void setRParen(SourceLocation Loc) { R = Loc; } 1638 1639 static bool classof(const Stmt *T) { 1640 return T->getStmtClass() == ParenExprClass; 1641 } 1642 1643 // Iterators 1644 child_range children() { return child_range(&Val, &Val+1); } 1645 }; 1646 1647 1648 /// UnaryOperator - This represents the unary-expression's (except sizeof and 1649 /// alignof), the postinc/postdec operators from postfix-expression, and various 1650 /// extensions. 1651 /// 1652 /// Notes on various nodes: 1653 /// 1654 /// Real/Imag - These return the real/imag part of a complex operand. If 1655 /// applied to a non-complex value, the former returns its operand and the 1656 /// later returns zero in the type of the operand. 1657 /// 1658 class UnaryOperator : public Expr { 1659 public: 1660 typedef UnaryOperatorKind Opcode; 1661 1662 private: 1663 unsigned Opc : 5; 1664 SourceLocation Loc; 1665 Stmt *Val; 1666 public: 1667 1668 UnaryOperator(Expr *input, Opcode opc, QualType type, 1669 ExprValueKind VK, ExprObjectKind OK, SourceLocation l) 1670 : Expr(UnaryOperatorClass, type, VK, OK, 1671 input->isTypeDependent() || type->isDependentType(), 1672 input->isValueDependent(), 1673 (input->isInstantiationDependent() || 1674 type->isInstantiationDependentType()), 1675 input->containsUnexpandedParameterPack()), 1676 Opc(opc), Loc(l), Val(input) {} 1677 1678 /// \brief Build an empty unary operator. 1679 explicit UnaryOperator(EmptyShell Empty) 1680 : Expr(UnaryOperatorClass, Empty), Opc(UO_AddrOf) { } 1681 1682 Opcode getOpcode() const { return static_cast<Opcode>(Opc); } 1683 void setOpcode(Opcode O) { Opc = O; } 1684 1685 Expr *getSubExpr() const { return cast<Expr>(Val); } 1686 void setSubExpr(Expr *E) { Val = E; } 1687 1688 /// getOperatorLoc - Return the location of the operator. 1689 SourceLocation getOperatorLoc() const { return Loc; } 1690 void setOperatorLoc(SourceLocation L) { Loc = L; } 1691 1692 /// isPostfix - Return true if this is a postfix operation, like x++. 1693 static bool isPostfix(Opcode Op) { 1694 return Op == UO_PostInc || Op == UO_PostDec; 1695 } 1696 1697 /// isPrefix - Return true if this is a prefix operation, like --x. 1698 static bool isPrefix(Opcode Op) { 1699 return Op == UO_PreInc || Op == UO_PreDec; 1700 } 1701 1702 bool isPrefix() const { return isPrefix(getOpcode()); } 1703 bool isPostfix() const { return isPostfix(getOpcode()); } 1704 1705 static bool isIncrementOp(Opcode Op) { 1706 return Op == UO_PreInc || Op == UO_PostInc; 1707 } 1708 bool isIncrementOp() const { 1709 return isIncrementOp(getOpcode()); 1710 } 1711 1712 static bool isDecrementOp(Opcode Op) { 1713 return Op == UO_PreDec || Op == UO_PostDec; 1714 } 1715 bool isDecrementOp() const { 1716 return isDecrementOp(getOpcode()); 1717 } 1718 1719 static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; } 1720 bool isIncrementDecrementOp() const { 1721 return isIncrementDecrementOp(getOpcode()); 1722 } 1723 1724 static bool isArithmeticOp(Opcode Op) { 1725 return Op >= UO_Plus && Op <= UO_LNot; 1726 } 1727 bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); } 1728 1729 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it 1730 /// corresponds to, e.g. "sizeof" or "[pre]++" 1731 static StringRef getOpcodeStr(Opcode Op); 1732 1733 /// \brief Retrieve the unary opcode that corresponds to the given 1734 /// overloaded operator. 1735 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix); 1736 1737 /// \brief Retrieve the overloaded operator kind that corresponds to 1738 /// the given unary opcode. 1739 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc); 1740 1741 SourceLocation getLocStart() const LLVM_READONLY { 1742 return isPostfix() ? Val->getLocStart() : Loc; 1743 } 1744 SourceLocation getLocEnd() const LLVM_READONLY { 1745 return isPostfix() ? Loc : Val->getLocEnd(); 1746 } 1747 SourceLocation getExprLoc() const LLVM_READONLY { return Loc; } 1748 1749 static bool classof(const Stmt *T) { 1750 return T->getStmtClass() == UnaryOperatorClass; 1751 } 1752 1753 // Iterators 1754 child_range children() { return child_range(&Val, &Val+1); } 1755 }; 1756 1757 /// OffsetOfExpr - [C99 7.17] - This represents an expression of the form 1758 /// offsetof(record-type, member-designator). For example, given: 1759 /// @code 1760 /// struct S { 1761 /// float f; 1762 /// double d; 1763 /// }; 1764 /// struct T { 1765 /// int i; 1766 /// struct S s[10]; 1767 /// }; 1768 /// @endcode 1769 /// we can represent and evaluate the expression @c offsetof(struct T, s[2].d). 1770 1771 class OffsetOfExpr : public Expr { 1772 public: 1773 // __builtin_offsetof(type, identifier(.identifier|[expr])*) 1774 class OffsetOfNode { 1775 public: 1776 /// \brief The kind of offsetof node we have. 1777 enum Kind { 1778 /// \brief An index into an array. 1779 Array = 0x00, 1780 /// \brief A field. 1781 Field = 0x01, 1782 /// \brief A field in a dependent type, known only by its name. 1783 Identifier = 0x02, 1784 /// \brief An implicit indirection through a C++ base class, when the 1785 /// field found is in a base class. 1786 Base = 0x03 1787 }; 1788 1789 private: 1790 enum { MaskBits = 2, Mask = 0x03 }; 1791 1792 /// \brief The source range that covers this part of the designator. 1793 SourceRange Range; 1794 1795 /// \brief The data describing the designator, which comes in three 1796 /// different forms, depending on the lower two bits. 1797 /// - An unsigned index into the array of Expr*'s stored after this node 1798 /// in memory, for [constant-expression] designators. 1799 /// - A FieldDecl*, for references to a known field. 1800 /// - An IdentifierInfo*, for references to a field with a given name 1801 /// when the class type is dependent. 1802 /// - A CXXBaseSpecifier*, for references that look at a field in a 1803 /// base class. 1804 uintptr_t Data; 1805 1806 public: 1807 /// \brief Create an offsetof node that refers to an array element. 1808 OffsetOfNode(SourceLocation LBracketLoc, unsigned Index, 1809 SourceLocation RBracketLoc) 1810 : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) { } 1811 1812 /// \brief Create an offsetof node that refers to a field. 1813 OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field, 1814 SourceLocation NameLoc) 1815 : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc), 1816 Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) { } 1817 1818 /// \brief Create an offsetof node that refers to an identifier. 1819 OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name, 1820 SourceLocation NameLoc) 1821 : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc), 1822 Data(reinterpret_cast<uintptr_t>(Name) | Identifier) { } 1823 1824 /// \brief Create an offsetof node that refers into a C++ base class. 1825 explicit OffsetOfNode(const CXXBaseSpecifier *Base) 1826 : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {} 1827 1828 /// \brief Determine what kind of offsetof node this is. 1829 Kind getKind() const { 1830 return static_cast<Kind>(Data & Mask); 1831 } 1832 1833 /// \brief For an array element node, returns the index into the array 1834 /// of expressions. 1835 unsigned getArrayExprIndex() const { 1836 assert(getKind() == Array); 1837 return Data >> 2; 1838 } 1839 1840 /// \brief For a field offsetof node, returns the field. 1841 FieldDecl *getField() const { 1842 assert(getKind() == Field); 1843 return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask); 1844 } 1845 1846 /// \brief For a field or identifier offsetof node, returns the name of 1847 /// the field. 1848 IdentifierInfo *getFieldName() const; 1849 1850 /// \brief For a base class node, returns the base specifier. 1851 CXXBaseSpecifier *getBase() const { 1852 assert(getKind() == Base); 1853 return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask); 1854 } 1855 1856 /// \brief Retrieve the source range that covers this offsetof node. 1857 /// 1858 /// For an array element node, the source range contains the locations of 1859 /// the square brackets. For a field or identifier node, the source range 1860 /// contains the location of the period (if there is one) and the 1861 /// identifier. 1862 SourceRange getSourceRange() const LLVM_READONLY { return Range; } 1863 SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); } 1864 SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); } 1865 }; 1866 1867 private: 1868 1869 SourceLocation OperatorLoc, RParenLoc; 1870 // Base type; 1871 TypeSourceInfo *TSInfo; 1872 // Number of sub-components (i.e. instances of OffsetOfNode). 1873 unsigned NumComps; 1874 // Number of sub-expressions (i.e. array subscript expressions). 1875 unsigned NumExprs; 1876 1877 OffsetOfExpr(const ASTContext &C, QualType type, 1878 SourceLocation OperatorLoc, TypeSourceInfo *tsi, 1879 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs, 1880 SourceLocation RParenLoc); 1881 1882 explicit OffsetOfExpr(unsigned numComps, unsigned numExprs) 1883 : Expr(OffsetOfExprClass, EmptyShell()), 1884 TSInfo(nullptr), NumComps(numComps), NumExprs(numExprs) {} 1885 1886 public: 1887 1888 static OffsetOfExpr *Create(const ASTContext &C, QualType type, 1889 SourceLocation OperatorLoc, TypeSourceInfo *tsi, 1890 ArrayRef<OffsetOfNode> comps, 1891 ArrayRef<Expr*> exprs, SourceLocation RParenLoc); 1892 1893 static OffsetOfExpr *CreateEmpty(const ASTContext &C, 1894 unsigned NumComps, unsigned NumExprs); 1895 1896 /// getOperatorLoc - Return the location of the operator. 1897 SourceLocation getOperatorLoc() const { return OperatorLoc; } 1898 void setOperatorLoc(SourceLocation L) { OperatorLoc = L; } 1899 1900 /// \brief Return the location of the right parentheses. 1901 SourceLocation getRParenLoc() const { return RParenLoc; } 1902 void setRParenLoc(SourceLocation R) { RParenLoc = R; } 1903 1904 TypeSourceInfo *getTypeSourceInfo() const { 1905 return TSInfo; 1906 } 1907 void setTypeSourceInfo(TypeSourceInfo *tsi) { 1908 TSInfo = tsi; 1909 } 1910 1911 const OffsetOfNode &getComponent(unsigned Idx) const { 1912 assert(Idx < NumComps && "Subscript out of range"); 1913 return reinterpret_cast<const OffsetOfNode *> (this + 1)[Idx]; 1914 } 1915 1916 void setComponent(unsigned Idx, OffsetOfNode ON) { 1917 assert(Idx < NumComps && "Subscript out of range"); 1918 reinterpret_cast<OffsetOfNode *> (this + 1)[Idx] = ON; 1919 } 1920 1921 unsigned getNumComponents() const { 1922 return NumComps; 1923 } 1924 1925 Expr* getIndexExpr(unsigned Idx) { 1926 assert(Idx < NumExprs && "Subscript out of range"); 1927 return reinterpret_cast<Expr **>( 1928 reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx]; 1929 } 1930 const Expr *getIndexExpr(unsigned Idx) const { 1931 return const_cast<OffsetOfExpr*>(this)->getIndexExpr(Idx); 1932 } 1933 1934 void setIndexExpr(unsigned Idx, Expr* E) { 1935 assert(Idx < NumComps && "Subscript out of range"); 1936 reinterpret_cast<Expr **>( 1937 reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx] = E; 1938 } 1939 1940 unsigned getNumExpressions() const { 1941 return NumExprs; 1942 } 1943 1944 SourceLocation getLocStart() const LLVM_READONLY { return OperatorLoc; } 1945 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } 1946 1947 static bool classof(const Stmt *T) { 1948 return T->getStmtClass() == OffsetOfExprClass; 1949 } 1950 1951 // Iterators 1952 child_range children() { 1953 Stmt **begin = 1954 reinterpret_cast<Stmt**>(reinterpret_cast<OffsetOfNode*>(this + 1) 1955 + NumComps); 1956 return child_range(begin, begin + NumExprs); 1957 } 1958 }; 1959 1960 /// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) 1961 /// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and 1962 /// vec_step (OpenCL 1.1 6.11.12). 1963 class UnaryExprOrTypeTraitExpr : public Expr { 1964 union { 1965 TypeSourceInfo *Ty; 1966 Stmt *Ex; 1967 } Argument; 1968 SourceLocation OpLoc, RParenLoc; 1969 1970 public: 1971 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo, 1972 QualType resultType, SourceLocation op, 1973 SourceLocation rp) : 1974 Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary, 1975 false, // Never type-dependent (C++ [temp.dep.expr]p3). 1976 // Value-dependent if the argument is type-dependent. 1977 TInfo->getType()->isDependentType(), 1978 TInfo->getType()->isInstantiationDependentType(), 1979 TInfo->getType()->containsUnexpandedParameterPack()), 1980 OpLoc(op), RParenLoc(rp) { 1981 UnaryExprOrTypeTraitExprBits.Kind = ExprKind; 1982 UnaryExprOrTypeTraitExprBits.IsType = true; 1983 Argument.Ty = TInfo; 1984 } 1985 1986 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E, 1987 QualType resultType, SourceLocation op, 1988 SourceLocation rp) : 1989 Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary, 1990 false, // Never type-dependent (C++ [temp.dep.expr]p3). 1991 // Value-dependent if the argument is type-dependent. 1992 E->isTypeDependent(), 1993 E->isInstantiationDependent(), 1994 E->containsUnexpandedParameterPack()), 1995 OpLoc(op), RParenLoc(rp) { 1996 UnaryExprOrTypeTraitExprBits.Kind = ExprKind; 1997 UnaryExprOrTypeTraitExprBits.IsType = false; 1998 Argument.Ex = E; 1999 } 2000 2001 /// \brief Construct an empty sizeof/alignof expression. 2002 explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty) 2003 : Expr(UnaryExprOrTypeTraitExprClass, Empty) { } 2004 2005 UnaryExprOrTypeTrait getKind() const { 2006 return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind); 2007 } 2008 void setKind(UnaryExprOrTypeTrait K) { UnaryExprOrTypeTraitExprBits.Kind = K;} 2009 2010 bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; } 2011 QualType getArgumentType() const { 2012 return getArgumentTypeInfo()->getType(); 2013 } 2014 TypeSourceInfo *getArgumentTypeInfo() const { 2015 assert(isArgumentType() && "calling getArgumentType() when arg is expr"); 2016 return Argument.Ty; 2017 } 2018 Expr *getArgumentExpr() { 2019 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type"); 2020 return static_cast<Expr*>(Argument.Ex); 2021 } 2022 const Expr *getArgumentExpr() const { 2023 return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr(); 2024 } 2025 2026 void setArgument(Expr *E) { 2027 Argument.Ex = E; 2028 UnaryExprOrTypeTraitExprBits.IsType = false; 2029 } 2030 void setArgument(TypeSourceInfo *TInfo) { 2031 Argument.Ty = TInfo; 2032 UnaryExprOrTypeTraitExprBits.IsType = true; 2033 } 2034 2035 /// Gets the argument type, or the type of the argument expression, whichever 2036 /// is appropriate. 2037 QualType getTypeOfArgument() const { 2038 return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType(); 2039 } 2040 2041 SourceLocation getOperatorLoc() const { return OpLoc; } 2042 void setOperatorLoc(SourceLocation L) { OpLoc = L; } 2043 2044 SourceLocation getRParenLoc() const { return RParenLoc; } 2045 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 2046 2047 SourceLocation getLocStart() const LLVM_READONLY { return OpLoc; } 2048 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } 2049 2050 static bool classof(const Stmt *T) { 2051 return T->getStmtClass() == UnaryExprOrTypeTraitExprClass; 2052 } 2053 2054 // Iterators 2055 child_range children(); 2056 }; 2057 2058 //===----------------------------------------------------------------------===// 2059 // Postfix Operators. 2060 //===----------------------------------------------------------------------===// 2061 2062 /// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting. 2063 class ArraySubscriptExpr : public Expr { 2064 enum { LHS, RHS, END_EXPR=2 }; 2065 Stmt* SubExprs[END_EXPR]; 2066 SourceLocation RBracketLoc; 2067 public: 2068 ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t, 2069 ExprValueKind VK, ExprObjectKind OK, 2070 SourceLocation rbracketloc) 2071 : Expr(ArraySubscriptExprClass, t, VK, OK, 2072 lhs->isTypeDependent() || rhs->isTypeDependent(), 2073 lhs->isValueDependent() || rhs->isValueDependent(), 2074 (lhs->isInstantiationDependent() || 2075 rhs->isInstantiationDependent()), 2076 (lhs->containsUnexpandedParameterPack() || 2077 rhs->containsUnexpandedParameterPack())), 2078 RBracketLoc(rbracketloc) { 2079 SubExprs[LHS] = lhs; 2080 SubExprs[RHS] = rhs; 2081 } 2082 2083 /// \brief Create an empty array subscript expression. 2084 explicit ArraySubscriptExpr(EmptyShell Shell) 2085 : Expr(ArraySubscriptExprClass, Shell) { } 2086 2087 /// An array access can be written A[4] or 4[A] (both are equivalent). 2088 /// - getBase() and getIdx() always present the normalized view: A[4]. 2089 /// In this case getBase() returns "A" and getIdx() returns "4". 2090 /// - getLHS() and getRHS() present the syntactic view. e.g. for 2091 /// 4[A] getLHS() returns "4". 2092 /// Note: Because vector element access is also written A[4] we must 2093 /// predicate the format conversion in getBase and getIdx only on the 2094 /// the type of the RHS, as it is possible for the LHS to be a vector of 2095 /// integer type 2096 Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); } 2097 const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } 2098 void setLHS(Expr *E) { SubExprs[LHS] = E; } 2099 2100 Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); } 2101 const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } 2102 void setRHS(Expr *E) { SubExprs[RHS] = E; } 2103 2104 Expr *getBase() { 2105 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS()); 2106 } 2107 2108 const Expr *getBase() const { 2109 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS()); 2110 } 2111 2112 Expr *getIdx() { 2113 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS()); 2114 } 2115 2116 const Expr *getIdx() const { 2117 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS()); 2118 } 2119 2120 SourceLocation getLocStart() const LLVM_READONLY { 2121 return getLHS()->getLocStart(); 2122 } 2123 SourceLocation getLocEnd() const LLVM_READONLY { return RBracketLoc; } 2124 2125 SourceLocation getRBracketLoc() const { return RBracketLoc; } 2126 void setRBracketLoc(SourceLocation L) { RBracketLoc = L; } 2127 2128 SourceLocation getExprLoc() const LLVM_READONLY { 2129 return getBase()->getExprLoc(); 2130 } 2131 2132 static bool classof(const Stmt *T) { 2133 return T->getStmtClass() == ArraySubscriptExprClass; 2134 } 2135 2136 // Iterators 2137 child_range children() { 2138 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); 2139 } 2140 }; 2141 2142 2143 /// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]). 2144 /// CallExpr itself represents a normal function call, e.g., "f(x, 2)", 2145 /// while its subclasses may represent alternative syntax that (semantically) 2146 /// results in a function call. For example, CXXOperatorCallExpr is 2147 /// a subclass for overloaded operator calls that use operator syntax, e.g., 2148 /// "str1 + str2" to resolve to a function call. 2149 class CallExpr : public Expr { 2150 enum { FN=0, PREARGS_START=1 }; 2151 Stmt **SubExprs; 2152 unsigned NumArgs; 2153 SourceLocation RParenLoc; 2154 2155 protected: 2156 // These versions of the constructor are for derived classes. 2157 CallExpr(const ASTContext& C, StmtClass SC, Expr *fn, unsigned NumPreArgs, 2158 ArrayRef<Expr*> args, QualType t, ExprValueKind VK, 2159 SourceLocation rparenloc); 2160 CallExpr(const ASTContext &C, StmtClass SC, unsigned NumPreArgs, 2161 EmptyShell Empty); 2162 2163 Stmt *getPreArg(unsigned i) { 2164 assert(i < getNumPreArgs() && "Prearg access out of range!"); 2165 return SubExprs[PREARGS_START+i]; 2166 } 2167 const Stmt *getPreArg(unsigned i) const { 2168 assert(i < getNumPreArgs() && "Prearg access out of range!"); 2169 return SubExprs[PREARGS_START+i]; 2170 } 2171 void setPreArg(unsigned i, Stmt *PreArg) { 2172 assert(i < getNumPreArgs() && "Prearg access out of range!"); 2173 SubExprs[PREARGS_START+i] = PreArg; 2174 } 2175 2176 unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; } 2177 2178 public: 2179 CallExpr(const ASTContext& C, Expr *fn, ArrayRef<Expr*> args, QualType t, 2180 ExprValueKind VK, SourceLocation rparenloc); 2181 2182 /// \brief Build an empty call expression. 2183 CallExpr(const ASTContext &C, StmtClass SC, EmptyShell Empty); 2184 2185 const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); } 2186 Expr *getCallee() { return cast<Expr>(SubExprs[FN]); } 2187 void setCallee(Expr *F) { SubExprs[FN] = F; } 2188 2189 Decl *getCalleeDecl(); 2190 const Decl *getCalleeDecl() const { 2191 return const_cast<CallExpr*>(this)->getCalleeDecl(); 2192 } 2193 2194 /// \brief If the callee is a FunctionDecl, return it. Otherwise return 0. 2195 FunctionDecl *getDirectCallee(); 2196 const FunctionDecl *getDirectCallee() const { 2197 return const_cast<CallExpr*>(this)->getDirectCallee(); 2198 } 2199 2200 /// getNumArgs - Return the number of actual arguments to this call. 2201 /// 2202 unsigned getNumArgs() const { return NumArgs; } 2203 2204 /// \brief Retrieve the call arguments. 2205 Expr **getArgs() { 2206 return reinterpret_cast<Expr **>(SubExprs+getNumPreArgs()+PREARGS_START); 2207 } 2208 const Expr *const *getArgs() const { 2209 return const_cast<CallExpr*>(this)->getArgs(); 2210 } 2211 2212 /// getArg - Return the specified argument. 2213 Expr *getArg(unsigned Arg) { 2214 assert(Arg < NumArgs && "Arg access out of range!"); 2215 return cast<Expr>(SubExprs[Arg+getNumPreArgs()+PREARGS_START]); 2216 } 2217 const Expr *getArg(unsigned Arg) const { 2218 assert(Arg < NumArgs && "Arg access out of range!"); 2219 return cast<Expr>(SubExprs[Arg+getNumPreArgs()+PREARGS_START]); 2220 } 2221 2222 /// setArg - Set the specified argument. 2223 void setArg(unsigned Arg, Expr *ArgExpr) { 2224 assert(Arg < NumArgs && "Arg access out of range!"); 2225 SubExprs[Arg+getNumPreArgs()+PREARGS_START] = ArgExpr; 2226 } 2227 2228 /// setNumArgs - This changes the number of arguments present in this call. 2229 /// Any orphaned expressions are deleted by this, and any new operands are set 2230 /// to null. 2231 void setNumArgs(const ASTContext& C, unsigned NumArgs); 2232 2233 typedef ExprIterator arg_iterator; 2234 typedef ConstExprIterator const_arg_iterator; 2235 typedef llvm::iterator_range<arg_iterator> arg_range; 2236 typedef llvm::iterator_range<const_arg_iterator> arg_const_range; 2237 2238 arg_range arguments() { return arg_range(arg_begin(), arg_end()); } 2239 arg_const_range arguments() const { 2240 return arg_const_range(arg_begin(), arg_end()); 2241 } 2242 2243 arg_iterator arg_begin() { return SubExprs+PREARGS_START+getNumPreArgs(); } 2244 arg_iterator arg_end() { 2245 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs(); 2246 } 2247 const_arg_iterator arg_begin() const { 2248 return SubExprs+PREARGS_START+getNumPreArgs(); 2249 } 2250 const_arg_iterator arg_end() const { 2251 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs(); 2252 } 2253 2254 /// This method provides fast access to all the subexpressions of 2255 /// a CallExpr without going through the slower virtual child_iterator 2256 /// interface. This provides efficient reverse iteration of the 2257 /// subexpressions. This is currently used for CFG construction. 2258 ArrayRef<Stmt*> getRawSubExprs() { 2259 return ArrayRef<Stmt*>(SubExprs, 2260 getNumPreArgs() + PREARGS_START + getNumArgs()); 2261 } 2262 2263 /// getNumCommas - Return the number of commas that must have been present in 2264 /// this function call. 2265 unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; } 2266 2267 /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID 2268 /// of the callee. If not, return 0. 2269 unsigned getBuiltinCallee() const; 2270 2271 /// \brief Returns \c true if this is a call to a builtin which does not 2272 /// evaluate side-effects within its arguments. 2273 bool isUnevaluatedBuiltinCall(ASTContext &Ctx) const; 2274 2275 /// getCallReturnType - Get the return type of the call expr. This is not 2276 /// always the type of the expr itself, if the return type is a reference 2277 /// type. 2278 QualType getCallReturnType() const; 2279 2280 SourceLocation getRParenLoc() const { return RParenLoc; } 2281 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 2282 2283 SourceLocation getLocStart() const LLVM_READONLY; 2284 SourceLocation getLocEnd() const LLVM_READONLY; 2285 2286 static bool classof(const Stmt *T) { 2287 return T->getStmtClass() >= firstCallExprConstant && 2288 T->getStmtClass() <= lastCallExprConstant; 2289 } 2290 2291 // Iterators 2292 child_range children() { 2293 return child_range(&SubExprs[0], 2294 &SubExprs[0]+NumArgs+getNumPreArgs()+PREARGS_START); 2295 } 2296 }; 2297 2298 /// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F. 2299 /// 2300 class MemberExpr : public Expr { 2301 /// Extra data stored in some member expressions. 2302 struct MemberNameQualifier { 2303 /// \brief The nested-name-specifier that qualifies the name, including 2304 /// source-location information. 2305 NestedNameSpecifierLoc QualifierLoc; 2306 2307 /// \brief The DeclAccessPair through which the MemberDecl was found due to 2308 /// name qualifiers. 2309 DeclAccessPair FoundDecl; 2310 }; 2311 2312 /// Base - the expression for the base pointer or structure references. In 2313 /// X.F, this is "X". 2314 Stmt *Base; 2315 2316 /// MemberDecl - This is the decl being referenced by the field/member name. 2317 /// In X.F, this is the decl referenced by F. 2318 ValueDecl *MemberDecl; 2319 2320 /// MemberDNLoc - Provides source/type location info for the 2321 /// declaration name embedded in MemberDecl. 2322 DeclarationNameLoc MemberDNLoc; 2323 2324 /// MemberLoc - This is the location of the member name. 2325 SourceLocation MemberLoc; 2326 2327 /// IsArrow - True if this is "X->F", false if this is "X.F". 2328 bool IsArrow : 1; 2329 2330 /// \brief True if this member expression used a nested-name-specifier to 2331 /// refer to the member, e.g., "x->Base::f", or found its member via a using 2332 /// declaration. When true, a MemberNameQualifier 2333 /// structure is allocated immediately after the MemberExpr. 2334 bool HasQualifierOrFoundDecl : 1; 2335 2336 /// \brief True if this member expression specified a template keyword 2337 /// and/or a template argument list explicitly, e.g., x->f<int>, 2338 /// x->template f, x->template f<int>. 2339 /// When true, an ASTTemplateKWAndArgsInfo structure and its 2340 /// TemplateArguments (if any) are allocated immediately after 2341 /// the MemberExpr or, if the member expression also has a qualifier, 2342 /// after the MemberNameQualifier structure. 2343 bool HasTemplateKWAndArgsInfo : 1; 2344 2345 /// \brief True if this member expression refers to a method that 2346 /// was resolved from an overloaded set having size greater than 1. 2347 bool HadMultipleCandidates : 1; 2348 2349 /// \brief Retrieve the qualifier that preceded the member name, if any. 2350 MemberNameQualifier *getMemberQualifier() { 2351 assert(HasQualifierOrFoundDecl); 2352 return reinterpret_cast<MemberNameQualifier *> (this + 1); 2353 } 2354 2355 /// \brief Retrieve the qualifier that preceded the member name, if any. 2356 const MemberNameQualifier *getMemberQualifier() const { 2357 return const_cast<MemberExpr *>(this)->getMemberQualifier(); 2358 } 2359 2360 public: 2361 MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl, 2362 const DeclarationNameInfo &NameInfo, QualType ty, 2363 ExprValueKind VK, ExprObjectKind OK) 2364 : Expr(MemberExprClass, ty, VK, OK, 2365 base->isTypeDependent(), 2366 base->isValueDependent(), 2367 base->isInstantiationDependent(), 2368 base->containsUnexpandedParameterPack()), 2369 Base(base), MemberDecl(memberdecl), MemberDNLoc(NameInfo.getInfo()), 2370 MemberLoc(NameInfo.getLoc()), IsArrow(isarrow), 2371 HasQualifierOrFoundDecl(false), HasTemplateKWAndArgsInfo(false), 2372 HadMultipleCandidates(false) { 2373 assert(memberdecl->getDeclName() == NameInfo.getName()); 2374 } 2375 2376 // NOTE: this constructor should be used only when it is known that 2377 // the member name can not provide additional syntactic info 2378 // (i.e., source locations for C++ operator names or type source info 2379 // for constructors, destructors and conversion operators). 2380 MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl, 2381 SourceLocation l, QualType ty, 2382 ExprValueKind VK, ExprObjectKind OK) 2383 : Expr(MemberExprClass, ty, VK, OK, 2384 base->isTypeDependent(), base->isValueDependent(), 2385 base->isInstantiationDependent(), 2386 base->containsUnexpandedParameterPack()), 2387 Base(base), MemberDecl(memberdecl), MemberDNLoc(), MemberLoc(l), 2388 IsArrow(isarrow), 2389 HasQualifierOrFoundDecl(false), HasTemplateKWAndArgsInfo(false), 2390 HadMultipleCandidates(false) {} 2391 2392 static MemberExpr *Create(const ASTContext &C, Expr *base, bool isarrow, 2393 NestedNameSpecifierLoc QualifierLoc, 2394 SourceLocation TemplateKWLoc, 2395 ValueDecl *memberdecl, DeclAccessPair founddecl, 2396 DeclarationNameInfo MemberNameInfo, 2397 const TemplateArgumentListInfo *targs, 2398 QualType ty, ExprValueKind VK, ExprObjectKind OK); 2399 2400 void setBase(Expr *E) { Base = E; } 2401 Expr *getBase() const { return cast<Expr>(Base); } 2402 2403 /// \brief Retrieve the member declaration to which this expression refers. 2404 /// 2405 /// The returned declaration will either be a FieldDecl or (in C++) 2406 /// a CXXMethodDecl. 2407 ValueDecl *getMemberDecl() const { return MemberDecl; } 2408 void setMemberDecl(ValueDecl *D) { MemberDecl = D; } 2409 2410 /// \brief Retrieves the declaration found by lookup. 2411 DeclAccessPair getFoundDecl() const { 2412 if (!HasQualifierOrFoundDecl) 2413 return DeclAccessPair::make(getMemberDecl(), 2414 getMemberDecl()->getAccess()); 2415 return getMemberQualifier()->FoundDecl; 2416 } 2417 2418 /// \brief Determines whether this member expression actually had 2419 /// a C++ nested-name-specifier prior to the name of the member, e.g., 2420 /// x->Base::foo. 2421 bool hasQualifier() const { return getQualifier() != nullptr; } 2422 2423 /// \brief If the member name was qualified, retrieves the 2424 /// nested-name-specifier that precedes the member name. Otherwise, returns 2425 /// NULL. 2426 NestedNameSpecifier *getQualifier() const { 2427 if (!HasQualifierOrFoundDecl) 2428 return nullptr; 2429 2430 return getMemberQualifier()->QualifierLoc.getNestedNameSpecifier(); 2431 } 2432 2433 /// \brief If the member name was qualified, retrieves the 2434 /// nested-name-specifier that precedes the member name, with source-location 2435 /// information. 2436 NestedNameSpecifierLoc getQualifierLoc() const { 2437 if (!hasQualifier()) 2438 return NestedNameSpecifierLoc(); 2439 2440 return getMemberQualifier()->QualifierLoc; 2441 } 2442 2443 /// \brief Return the optional template keyword and arguments info. 2444 ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() { 2445 if (!HasTemplateKWAndArgsInfo) 2446 return nullptr; 2447 2448 if (!HasQualifierOrFoundDecl) 2449 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(this + 1); 2450 2451 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>( 2452 getMemberQualifier() + 1); 2453 } 2454 2455 /// \brief Return the optional template keyword and arguments info. 2456 const ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() const { 2457 return const_cast<MemberExpr*>(this)->getTemplateKWAndArgsInfo(); 2458 } 2459 2460 /// \brief Retrieve the location of the template keyword preceding 2461 /// the member name, if any. 2462 SourceLocation getTemplateKeywordLoc() const { 2463 if (!HasTemplateKWAndArgsInfo) return SourceLocation(); 2464 return getTemplateKWAndArgsInfo()->getTemplateKeywordLoc(); 2465 } 2466 2467 /// \brief Retrieve the location of the left angle bracket starting the 2468 /// explicit template argument list following the member name, if any. 2469 SourceLocation getLAngleLoc() const { 2470 if (!HasTemplateKWAndArgsInfo) return SourceLocation(); 2471 return getTemplateKWAndArgsInfo()->LAngleLoc; 2472 } 2473 2474 /// \brief Retrieve the location of the right angle bracket ending the 2475 /// explicit template argument list following the member name, if any. 2476 SourceLocation getRAngleLoc() const { 2477 if (!HasTemplateKWAndArgsInfo) return SourceLocation(); 2478 return getTemplateKWAndArgsInfo()->RAngleLoc; 2479 } 2480 2481 /// Determines whether the member name was preceded by the template keyword. 2482 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); } 2483 2484 /// \brief Determines whether the member name was followed by an 2485 /// explicit template argument list. 2486 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); } 2487 2488 /// \brief Copies the template arguments (if present) into the given 2489 /// structure. 2490 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const { 2491 if (hasExplicitTemplateArgs()) 2492 getExplicitTemplateArgs().copyInto(List); 2493 } 2494 2495 /// \brief Retrieve the explicit template argument list that 2496 /// follow the member template name. This must only be called on an 2497 /// expression with explicit template arguments. 2498 ASTTemplateArgumentListInfo &getExplicitTemplateArgs() { 2499 assert(hasExplicitTemplateArgs()); 2500 return *getTemplateKWAndArgsInfo(); 2501 } 2502 2503 /// \brief Retrieve the explicit template argument list that 2504 /// followed the member template name. This must only be called on 2505 /// an expression with explicit template arguments. 2506 const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const { 2507 return const_cast<MemberExpr *>(this)->getExplicitTemplateArgs(); 2508 } 2509 2510 /// \brief Retrieves the optional explicit template arguments. 2511 /// This points to the same data as getExplicitTemplateArgs(), but 2512 /// returns null if there are no explicit template arguments. 2513 const ASTTemplateArgumentListInfo *getOptionalExplicitTemplateArgs() const { 2514 if (!hasExplicitTemplateArgs()) return nullptr; 2515 return &getExplicitTemplateArgs(); 2516 } 2517 2518 /// \brief Retrieve the template arguments provided as part of this 2519 /// template-id. 2520 const TemplateArgumentLoc *getTemplateArgs() const { 2521 if (!hasExplicitTemplateArgs()) 2522 return nullptr; 2523 2524 return getExplicitTemplateArgs().getTemplateArgs(); 2525 } 2526 2527 /// \brief Retrieve the number of template arguments provided as part of this 2528 /// template-id. 2529 unsigned getNumTemplateArgs() const { 2530 if (!hasExplicitTemplateArgs()) 2531 return 0; 2532 2533 return getExplicitTemplateArgs().NumTemplateArgs; 2534 } 2535 2536 /// \brief Retrieve the member declaration name info. 2537 DeclarationNameInfo getMemberNameInfo() const { 2538 return DeclarationNameInfo(MemberDecl->getDeclName(), 2539 MemberLoc, MemberDNLoc); 2540 } 2541 2542 bool isArrow() const { return IsArrow; } 2543 void setArrow(bool A) { IsArrow = A; } 2544 2545 /// getMemberLoc - Return the location of the "member", in X->F, it is the 2546 /// location of 'F'. 2547 SourceLocation getMemberLoc() const { return MemberLoc; } 2548 void setMemberLoc(SourceLocation L) { MemberLoc = L; } 2549 2550 SourceLocation getLocStart() const LLVM_READONLY; 2551 SourceLocation getLocEnd() const LLVM_READONLY; 2552 2553 SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; } 2554 2555 /// \brief Determine whether the base of this explicit is implicit. 2556 bool isImplicitAccess() const { 2557 return getBase() && getBase()->isImplicitCXXThis(); 2558 } 2559 2560 /// \brief Returns true if this member expression refers to a method that 2561 /// was resolved from an overloaded set having size greater than 1. 2562 bool hadMultipleCandidates() const { 2563 return HadMultipleCandidates; 2564 } 2565 /// \brief Sets the flag telling whether this expression refers to 2566 /// a method that was resolved from an overloaded set having size 2567 /// greater than 1. 2568 void setHadMultipleCandidates(bool V = true) { 2569 HadMultipleCandidates = V; 2570 } 2571 2572 static bool classof(const Stmt *T) { 2573 return T->getStmtClass() == MemberExprClass; 2574 } 2575 2576 // Iterators 2577 child_range children() { return child_range(&Base, &Base+1); } 2578 2579 friend class ASTReader; 2580 friend class ASTStmtWriter; 2581 }; 2582 2583 /// CompoundLiteralExpr - [C99 6.5.2.5] 2584 /// 2585 class CompoundLiteralExpr : public Expr { 2586 /// LParenLoc - If non-null, this is the location of the left paren in a 2587 /// compound literal like "(int){4}". This can be null if this is a 2588 /// synthesized compound expression. 2589 SourceLocation LParenLoc; 2590 2591 /// The type as written. This can be an incomplete array type, in 2592 /// which case the actual expression type will be different. 2593 /// The int part of the pair stores whether this expr is file scope. 2594 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope; 2595 Stmt *Init; 2596 public: 2597 CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo, 2598 QualType T, ExprValueKind VK, Expr *init, bool fileScope) 2599 : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary, 2600 tinfo->getType()->isDependentType(), 2601 init->isValueDependent(), 2602 (init->isInstantiationDependent() || 2603 tinfo->getType()->isInstantiationDependentType()), 2604 init->containsUnexpandedParameterPack()), 2605 LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {} 2606 2607 /// \brief Construct an empty compound literal. 2608 explicit CompoundLiteralExpr(EmptyShell Empty) 2609 : Expr(CompoundLiteralExprClass, Empty) { } 2610 2611 const Expr *getInitializer() const { return cast<Expr>(Init); } 2612 Expr *getInitializer() { return cast<Expr>(Init); } 2613 void setInitializer(Expr *E) { Init = E; } 2614 2615 bool isFileScope() const { return TInfoAndScope.getInt(); } 2616 void setFileScope(bool FS) { TInfoAndScope.setInt(FS); } 2617 2618 SourceLocation getLParenLoc() const { return LParenLoc; } 2619 void setLParenLoc(SourceLocation L) { LParenLoc = L; } 2620 2621 TypeSourceInfo *getTypeSourceInfo() const { 2622 return TInfoAndScope.getPointer(); 2623 } 2624 void setTypeSourceInfo(TypeSourceInfo *tinfo) { 2625 TInfoAndScope.setPointer(tinfo); 2626 } 2627 2628 SourceLocation getLocStart() const LLVM_READONLY { 2629 // FIXME: Init should never be null. 2630 if (!Init) 2631 return SourceLocation(); 2632 if (LParenLoc.isInvalid()) 2633 return Init->getLocStart(); 2634 return LParenLoc; 2635 } 2636 SourceLocation getLocEnd() const LLVM_READONLY { 2637 // FIXME: Init should never be null. 2638 if (!Init) 2639 return SourceLocation(); 2640 return Init->getLocEnd(); 2641 } 2642 2643 static bool classof(const Stmt *T) { 2644 return T->getStmtClass() == CompoundLiteralExprClass; 2645 } 2646 2647 // Iterators 2648 child_range children() { return child_range(&Init, &Init+1); } 2649 }; 2650 2651 /// CastExpr - Base class for type casts, including both implicit 2652 /// casts (ImplicitCastExpr) and explicit casts that have some 2653 /// representation in the source code (ExplicitCastExpr's derived 2654 /// classes). 2655 class CastExpr : public Expr { 2656 public: 2657 typedef clang::CastKind CastKind; 2658 2659 private: 2660 Stmt *Op; 2661 2662 bool CastConsistency() const; 2663 2664 const CXXBaseSpecifier * const *path_buffer() const { 2665 return const_cast<CastExpr*>(this)->path_buffer(); 2666 } 2667 CXXBaseSpecifier **path_buffer(); 2668 2669 void setBasePathSize(unsigned basePathSize) { 2670 CastExprBits.BasePathSize = basePathSize; 2671 assert(CastExprBits.BasePathSize == basePathSize && 2672 "basePathSize doesn't fit in bits of CastExprBits.BasePathSize!"); 2673 } 2674 2675 protected: 2676 CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, 2677 const CastKind kind, Expr *op, unsigned BasePathSize) : 2678 Expr(SC, ty, VK, OK_Ordinary, 2679 // Cast expressions are type-dependent if the type is 2680 // dependent (C++ [temp.dep.expr]p3). 2681 ty->isDependentType(), 2682 // Cast expressions are value-dependent if the type is 2683 // dependent or if the subexpression is value-dependent. 2684 ty->isDependentType() || (op && op->isValueDependent()), 2685 (ty->isInstantiationDependentType() || 2686 (op && op->isInstantiationDependent())), 2687 (ty->containsUnexpandedParameterPack() || 2688 (op && op->containsUnexpandedParameterPack()))), 2689 Op(op) { 2690 assert(kind != CK_Invalid && "creating cast with invalid cast kind"); 2691 CastExprBits.Kind = kind; 2692 setBasePathSize(BasePathSize); 2693 assert(CastConsistency()); 2694 } 2695 2696 /// \brief Construct an empty cast. 2697 CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize) 2698 : Expr(SC, Empty) { 2699 setBasePathSize(BasePathSize); 2700 } 2701 2702 public: 2703 CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; } 2704 void setCastKind(CastKind K) { CastExprBits.Kind = K; } 2705 const char *getCastKindName() const; 2706 2707 Expr *getSubExpr() { return cast<Expr>(Op); } 2708 const Expr *getSubExpr() const { return cast<Expr>(Op); } 2709 void setSubExpr(Expr *E) { Op = E; } 2710 2711 /// \brief Retrieve the cast subexpression as it was written in the source 2712 /// code, looking through any implicit casts or other intermediate nodes 2713 /// introduced by semantic analysis. 2714 Expr *getSubExprAsWritten(); 2715 const Expr *getSubExprAsWritten() const { 2716 return const_cast<CastExpr *>(this)->getSubExprAsWritten(); 2717 } 2718 2719 typedef CXXBaseSpecifier **path_iterator; 2720 typedef const CXXBaseSpecifier * const *path_const_iterator; 2721 bool path_empty() const { return CastExprBits.BasePathSize == 0; } 2722 unsigned path_size() const { return CastExprBits.BasePathSize; } 2723 path_iterator path_begin() { return path_buffer(); } 2724 path_iterator path_end() { return path_buffer() + path_size(); } 2725 path_const_iterator path_begin() const { return path_buffer(); } 2726 path_const_iterator path_end() const { return path_buffer() + path_size(); } 2727 2728 void setCastPath(const CXXCastPath &Path); 2729 2730 static bool classof(const Stmt *T) { 2731 return T->getStmtClass() >= firstCastExprConstant && 2732 T->getStmtClass() <= lastCastExprConstant; 2733 } 2734 2735 // Iterators 2736 child_range children() { return child_range(&Op, &Op+1); } 2737 }; 2738 2739 /// ImplicitCastExpr - Allows us to explicitly represent implicit type 2740 /// conversions, which have no direct representation in the original 2741 /// source code. For example: converting T[]->T*, void f()->void 2742 /// (*f)(), float->double, short->int, etc. 2743 /// 2744 /// In C, implicit casts always produce rvalues. However, in C++, an 2745 /// implicit cast whose result is being bound to a reference will be 2746 /// an lvalue or xvalue. For example: 2747 /// 2748 /// @code 2749 /// class Base { }; 2750 /// class Derived : public Base { }; 2751 /// Derived &&ref(); 2752 /// void f(Derived d) { 2753 /// Base& b = d; // initializer is an ImplicitCastExpr 2754 /// // to an lvalue of type Base 2755 /// Base&& r = ref(); // initializer is an ImplicitCastExpr 2756 /// // to an xvalue of type Base 2757 /// } 2758 /// @endcode 2759 class ImplicitCastExpr : public CastExpr { 2760 private: 2761 ImplicitCastExpr(QualType ty, CastKind kind, Expr *op, 2762 unsigned BasePathLength, ExprValueKind VK) 2763 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) { 2764 } 2765 2766 /// \brief Construct an empty implicit cast. 2767 explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize) 2768 : CastExpr(ImplicitCastExprClass, Shell, PathSize) { } 2769 2770 public: 2771 enum OnStack_t { OnStack }; 2772 ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op, 2773 ExprValueKind VK) 2774 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) { 2775 } 2776 2777 static ImplicitCastExpr *Create(const ASTContext &Context, QualType T, 2778 CastKind Kind, Expr *Operand, 2779 const CXXCastPath *BasePath, 2780 ExprValueKind Cat); 2781 2782 static ImplicitCastExpr *CreateEmpty(const ASTContext &Context, 2783 unsigned PathSize); 2784 2785 SourceLocation getLocStart() const LLVM_READONLY { 2786 return getSubExpr()->getLocStart(); 2787 } 2788 SourceLocation getLocEnd() const LLVM_READONLY { 2789 return getSubExpr()->getLocEnd(); 2790 } 2791 2792 static bool classof(const Stmt *T) { 2793 return T->getStmtClass() == ImplicitCastExprClass; 2794 } 2795 }; 2796 2797 inline Expr *Expr::IgnoreImpCasts() { 2798 Expr *e = this; 2799 while (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e)) 2800 e = ice->getSubExpr(); 2801 return e; 2802 } 2803 2804 /// ExplicitCastExpr - An explicit cast written in the source 2805 /// code. 2806 /// 2807 /// This class is effectively an abstract class, because it provides 2808 /// the basic representation of an explicitly-written cast without 2809 /// specifying which kind of cast (C cast, functional cast, static 2810 /// cast, etc.) was written; specific derived classes represent the 2811 /// particular style of cast and its location information. 2812 /// 2813 /// Unlike implicit casts, explicit cast nodes have two different 2814 /// types: the type that was written into the source code, and the 2815 /// actual type of the expression as determined by semantic 2816 /// analysis. These types may differ slightly. For example, in C++ one 2817 /// can cast to a reference type, which indicates that the resulting 2818 /// expression will be an lvalue or xvalue. The reference type, however, 2819 /// will not be used as the type of the expression. 2820 class ExplicitCastExpr : public CastExpr { 2821 /// TInfo - Source type info for the (written) type 2822 /// this expression is casting to. 2823 TypeSourceInfo *TInfo; 2824 2825 protected: 2826 ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK, 2827 CastKind kind, Expr *op, unsigned PathSize, 2828 TypeSourceInfo *writtenTy) 2829 : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {} 2830 2831 /// \brief Construct an empty explicit cast. 2832 ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize) 2833 : CastExpr(SC, Shell, PathSize) { } 2834 2835 public: 2836 /// getTypeInfoAsWritten - Returns the type source info for the type 2837 /// that this expression is casting to. 2838 TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; } 2839 void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; } 2840 2841 /// getTypeAsWritten - Returns the type that this expression is 2842 /// casting to, as written in the source code. 2843 QualType getTypeAsWritten() const { return TInfo->getType(); } 2844 2845 static bool classof(const Stmt *T) { 2846 return T->getStmtClass() >= firstExplicitCastExprConstant && 2847 T->getStmtClass() <= lastExplicitCastExprConstant; 2848 } 2849 }; 2850 2851 /// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style 2852 /// cast in C++ (C++ [expr.cast]), which uses the syntax 2853 /// (Type)expr. For example: @c (int)f. 2854 class CStyleCastExpr : public ExplicitCastExpr { 2855 SourceLocation LPLoc; // the location of the left paren 2856 SourceLocation RPLoc; // the location of the right paren 2857 2858 CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op, 2859 unsigned PathSize, TypeSourceInfo *writtenTy, 2860 SourceLocation l, SourceLocation r) 2861 : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize, 2862 writtenTy), LPLoc(l), RPLoc(r) {} 2863 2864 /// \brief Construct an empty C-style explicit cast. 2865 explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize) 2866 : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { } 2867 2868 public: 2869 static CStyleCastExpr *Create(const ASTContext &Context, QualType T, 2870 ExprValueKind VK, CastKind K, 2871 Expr *Op, const CXXCastPath *BasePath, 2872 TypeSourceInfo *WrittenTy, SourceLocation L, 2873 SourceLocation R); 2874 2875 static CStyleCastExpr *CreateEmpty(const ASTContext &Context, 2876 unsigned PathSize); 2877 2878 SourceLocation getLParenLoc() const { return LPLoc; } 2879 void setLParenLoc(SourceLocation L) { LPLoc = L; } 2880 2881 SourceLocation getRParenLoc() const { return RPLoc; } 2882 void setRParenLoc(SourceLocation L) { RPLoc = L; } 2883 2884 SourceLocation getLocStart() const LLVM_READONLY { return LPLoc; } 2885 SourceLocation getLocEnd() const LLVM_READONLY { 2886 return getSubExpr()->getLocEnd(); 2887 } 2888 2889 static bool classof(const Stmt *T) { 2890 return T->getStmtClass() == CStyleCastExprClass; 2891 } 2892 }; 2893 2894 /// \brief A builtin binary operation expression such as "x + y" or "x <= y". 2895 /// 2896 /// This expression node kind describes a builtin binary operation, 2897 /// such as "x + y" for integer values "x" and "y". The operands will 2898 /// already have been converted to appropriate types (e.g., by 2899 /// performing promotions or conversions). 2900 /// 2901 /// In C++, where operators may be overloaded, a different kind of 2902 /// expression node (CXXOperatorCallExpr) is used to express the 2903 /// invocation of an overloaded operator with operator syntax. Within 2904 /// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is 2905 /// used to store an expression "x + y" depends on the subexpressions 2906 /// for x and y. If neither x or y is type-dependent, and the "+" 2907 /// operator resolves to a built-in operation, BinaryOperator will be 2908 /// used to express the computation (x and y may still be 2909 /// value-dependent). If either x or y is type-dependent, or if the 2910 /// "+" resolves to an overloaded operator, CXXOperatorCallExpr will 2911 /// be used to express the computation. 2912 class BinaryOperator : public Expr { 2913 public: 2914 typedef BinaryOperatorKind Opcode; 2915 2916 private: 2917 unsigned Opc : 6; 2918 2919 // Records the FP_CONTRACT pragma status at the point that this binary 2920 // operator was parsed. This bit is only meaningful for operations on 2921 // floating point types. For all other types it should default to 2922 // false. 2923 unsigned FPContractable : 1; 2924 SourceLocation OpLoc; 2925 2926 enum { LHS, RHS, END_EXPR }; 2927 Stmt* SubExprs[END_EXPR]; 2928 public: 2929 2930 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, 2931 ExprValueKind VK, ExprObjectKind OK, 2932 SourceLocation opLoc, bool fpContractable) 2933 : Expr(BinaryOperatorClass, ResTy, VK, OK, 2934 lhs->isTypeDependent() || rhs->isTypeDependent(), 2935 lhs->isValueDependent() || rhs->isValueDependent(), 2936 (lhs->isInstantiationDependent() || 2937 rhs->isInstantiationDependent()), 2938 (lhs->containsUnexpandedParameterPack() || 2939 rhs->containsUnexpandedParameterPack())), 2940 Opc(opc), FPContractable(fpContractable), OpLoc(opLoc) { 2941 SubExprs[LHS] = lhs; 2942 SubExprs[RHS] = rhs; 2943 assert(!isCompoundAssignmentOp() && 2944 "Use CompoundAssignOperator for compound assignments"); 2945 } 2946 2947 /// \brief Construct an empty binary operator. 2948 explicit BinaryOperator(EmptyShell Empty) 2949 : Expr(BinaryOperatorClass, Empty), Opc(BO_Comma) { } 2950 2951 SourceLocation getExprLoc() const LLVM_READONLY { return OpLoc; } 2952 SourceLocation getOperatorLoc() const { return OpLoc; } 2953 void setOperatorLoc(SourceLocation L) { OpLoc = L; } 2954 2955 Opcode getOpcode() const { return static_cast<Opcode>(Opc); } 2956 void setOpcode(Opcode O) { Opc = O; } 2957 2958 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } 2959 void setLHS(Expr *E) { SubExprs[LHS] = E; } 2960 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } 2961 void setRHS(Expr *E) { SubExprs[RHS] = E; } 2962 2963 SourceLocation getLocStart() const LLVM_READONLY { 2964 return getLHS()->getLocStart(); 2965 } 2966 SourceLocation getLocEnd() const LLVM_READONLY { 2967 return getRHS()->getLocEnd(); 2968 } 2969 2970 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it 2971 /// corresponds to, e.g. "<<=". 2972 static StringRef getOpcodeStr(Opcode Op); 2973 2974 StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); } 2975 2976 /// \brief Retrieve the binary opcode that corresponds to the given 2977 /// overloaded operator. 2978 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO); 2979 2980 /// \brief Retrieve the overloaded operator kind that corresponds to 2981 /// the given binary opcode. 2982 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc); 2983 2984 /// predicates to categorize the respective opcodes. 2985 bool isPtrMemOp() const { return Opc == BO_PtrMemD || Opc == BO_PtrMemI; } 2986 bool isMultiplicativeOp() const { return Opc >= BO_Mul && Opc <= BO_Rem; } 2987 static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; } 2988 bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); } 2989 static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; } 2990 bool isShiftOp() const { return isShiftOp(getOpcode()); } 2991 2992 static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; } 2993 bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); } 2994 2995 static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; } 2996 bool isRelationalOp() const { return isRelationalOp(getOpcode()); } 2997 2998 static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; } 2999 bool isEqualityOp() const { return isEqualityOp(getOpcode()); } 3000 3001 static bool isComparisonOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_NE; } 3002 bool isComparisonOp() const { return isComparisonOp(getOpcode()); } 3003 3004 static Opcode negateComparisonOp(Opcode Opc) { 3005 switch (Opc) { 3006 default: 3007 llvm_unreachable("Not a comparsion operator."); 3008 case BO_LT: return BO_GE; 3009 case BO_GT: return BO_LE; 3010 case BO_LE: return BO_GT; 3011 case BO_GE: return BO_LT; 3012 case BO_EQ: return BO_NE; 3013 case BO_NE: return BO_EQ; 3014 } 3015 } 3016 3017 static Opcode reverseComparisonOp(Opcode Opc) { 3018 switch (Opc) { 3019 default: 3020 llvm_unreachable("Not a comparsion operator."); 3021 case BO_LT: return BO_GT; 3022 case BO_GT: return BO_LT; 3023 case BO_LE: return BO_GE; 3024 case BO_GE: return BO_LE; 3025 case BO_EQ: 3026 case BO_NE: 3027 return Opc; 3028 } 3029 } 3030 3031 static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; } 3032 bool isLogicalOp() const { return isLogicalOp(getOpcode()); } 3033 3034 static bool isAssignmentOp(Opcode Opc) { 3035 return Opc >= BO_Assign && Opc <= BO_OrAssign; 3036 } 3037 bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); } 3038 3039 static bool isCompoundAssignmentOp(Opcode Opc) { 3040 return Opc > BO_Assign && Opc <= BO_OrAssign; 3041 } 3042 bool isCompoundAssignmentOp() const { 3043 return isCompoundAssignmentOp(getOpcode()); 3044 } 3045 static Opcode getOpForCompoundAssignment(Opcode Opc) { 3046 assert(isCompoundAssignmentOp(Opc)); 3047 if (Opc >= BO_AndAssign) 3048 return Opcode(unsigned(Opc) - BO_AndAssign + BO_And); 3049 else 3050 return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul); 3051 } 3052 3053 static bool isShiftAssignOp(Opcode Opc) { 3054 return Opc == BO_ShlAssign || Opc == BO_ShrAssign; 3055 } 3056 bool isShiftAssignOp() const { 3057 return isShiftAssignOp(getOpcode()); 3058 } 3059 3060 static bool classof(const Stmt *S) { 3061 return S->getStmtClass() >= firstBinaryOperatorConstant && 3062 S->getStmtClass() <= lastBinaryOperatorConstant; 3063 } 3064 3065 // Iterators 3066 child_range children() { 3067 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); 3068 } 3069 3070 // Set the FP contractability status of this operator. Only meaningful for 3071 // operations on floating point types. 3072 void setFPContractable(bool FPC) { FPContractable = FPC; } 3073 3074 // Get the FP contractability status of this operator. Only meaningful for 3075 // operations on floating point types. 3076 bool isFPContractable() const { return FPContractable; } 3077 3078 protected: 3079 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, 3080 ExprValueKind VK, ExprObjectKind OK, 3081 SourceLocation opLoc, bool fpContractable, bool dead2) 3082 : Expr(CompoundAssignOperatorClass, ResTy, VK, OK, 3083 lhs->isTypeDependent() || rhs->isTypeDependent(), 3084 lhs->isValueDependent() || rhs->isValueDependent(), 3085 (lhs->isInstantiationDependent() || 3086 rhs->isInstantiationDependent()), 3087 (lhs->containsUnexpandedParameterPack() || 3088 rhs->containsUnexpandedParameterPack())), 3089 Opc(opc), FPContractable(fpContractable), OpLoc(opLoc) { 3090 SubExprs[LHS] = lhs; 3091 SubExprs[RHS] = rhs; 3092 } 3093 3094 BinaryOperator(StmtClass SC, EmptyShell Empty) 3095 : Expr(SC, Empty), Opc(BO_MulAssign) { } 3096 }; 3097 3098 /// CompoundAssignOperator - For compound assignments (e.g. +=), we keep 3099 /// track of the type the operation is performed in. Due to the semantics of 3100 /// these operators, the operands are promoted, the arithmetic performed, an 3101 /// implicit conversion back to the result type done, then the assignment takes 3102 /// place. This captures the intermediate type which the computation is done 3103 /// in. 3104 class CompoundAssignOperator : public BinaryOperator { 3105 QualType ComputationLHSType; 3106 QualType ComputationResultType; 3107 public: 3108 CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResType, 3109 ExprValueKind VK, ExprObjectKind OK, 3110 QualType CompLHSType, QualType CompResultType, 3111 SourceLocation OpLoc, bool fpContractable) 3112 : BinaryOperator(lhs, rhs, opc, ResType, VK, OK, OpLoc, fpContractable, 3113 true), 3114 ComputationLHSType(CompLHSType), 3115 ComputationResultType(CompResultType) { 3116 assert(isCompoundAssignmentOp() && 3117 "Only should be used for compound assignments"); 3118 } 3119 3120 /// \brief Build an empty compound assignment operator expression.