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