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