Expr.h revision d0dcceae2a8ca0e37b5dd471a704de8583d49c95
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 1461 static bool isIncrementOp(Opcode Op) { 1462 return Op == UO_PreInc || Op == UO_PostInc; 1463 } 1464 bool isIncrementOp() const { 1465 return isIncrementOp(getOpcode()); 1466 } 1467 1468 static bool isDecrementOp(Opcode Op) { 1469 return Op == UO_PreDec || Op == UO_PostDec; 1470 } 1471 bool isDecrementOp() const { 1472 return isDecrementOp(getOpcode()); 1473 } 1474 1475 static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; } 1476 bool isIncrementDecrementOp() const { 1477 return isIncrementDecrementOp(getOpcode()); 1478 } 1479 1480 static bool isArithmeticOp(Opcode Op) { 1481 return Op >= UO_Plus && Op <= UO_LNot; 1482 } 1483 bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); } 1484 1485 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it 1486 /// corresponds to, e.g. "sizeof" or "[pre]++" 1487 static const char *getOpcodeStr(Opcode Op); 1488 1489 /// \brief Retrieve the unary opcode that corresponds to the given 1490 /// overloaded operator. 1491 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix); 1492 1493 /// \brief Retrieve the overloaded operator kind that corresponds to 1494 /// the given unary opcode. 1495 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc); 1496 1497 SourceRange getSourceRange() const { 1498 if (isPostfix()) 1499 return SourceRange(Val->getLocStart(), Loc); 1500 else 1501 return SourceRange(Loc, Val->getLocEnd()); 1502 } 1503 SourceLocation getExprLoc() const { return Loc; } 1504 1505 static bool classof(const Stmt *T) { 1506 return T->getStmtClass() == UnaryOperatorClass; 1507 } 1508 static bool classof(const UnaryOperator *) { return true; } 1509 1510 // Iterators 1511 child_range children() { return child_range(&Val, &Val+1); } 1512}; 1513 1514/// OffsetOfExpr - [C99 7.17] - This represents an expression of the form 1515/// offsetof(record-type, member-designator). For example, given: 1516/// @code 1517/// struct S { 1518/// float f; 1519/// double d; 1520/// }; 1521/// struct T { 1522/// int i; 1523/// struct S s[10]; 1524/// }; 1525/// @endcode 1526/// we can represent and evaluate the expression @c offsetof(struct T, s[2].d). 1527 1528class OffsetOfExpr : public Expr { 1529public: 1530 // __builtin_offsetof(type, identifier(.identifier|[expr])*) 1531 class OffsetOfNode { 1532 public: 1533 /// \brief The kind of offsetof node we have. 1534 enum Kind { 1535 /// \brief An index into an array. 1536 Array = 0x00, 1537 /// \brief A field. 1538 Field = 0x01, 1539 /// \brief A field in a dependent type, known only by its name. 1540 Identifier = 0x02, 1541 /// \brief An implicit indirection through a C++ base class, when the 1542 /// field found is in a base class. 1543 Base = 0x03 1544 }; 1545 1546 private: 1547 enum { MaskBits = 2, Mask = 0x03 }; 1548 1549 /// \brief The source range that covers this part of the designator. 1550 SourceRange Range; 1551 1552 /// \brief The data describing the designator, which comes in three 1553 /// different forms, depending on the lower two bits. 1554 /// - An unsigned index into the array of Expr*'s stored after this node 1555 /// in memory, for [constant-expression] designators. 1556 /// - A FieldDecl*, for references to a known field. 1557 /// - An IdentifierInfo*, for references to a field with a given name 1558 /// when the class type is dependent. 1559 /// - A CXXBaseSpecifier*, for references that look at a field in a 1560 /// base class. 1561 uintptr_t Data; 1562 1563 public: 1564 /// \brief Create an offsetof node that refers to an array element. 1565 OffsetOfNode(SourceLocation LBracketLoc, unsigned Index, 1566 SourceLocation RBracketLoc) 1567 : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) { } 1568 1569 /// \brief Create an offsetof node that refers to a field. 1570 OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field, 1571 SourceLocation NameLoc) 1572 : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc), 1573 Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) { } 1574 1575 /// \brief Create an offsetof node that refers to an identifier. 1576 OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name, 1577 SourceLocation NameLoc) 1578 : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc), 1579 Data(reinterpret_cast<uintptr_t>(Name) | Identifier) { } 1580 1581 /// \brief Create an offsetof node that refers into a C++ base class. 1582 explicit OffsetOfNode(const CXXBaseSpecifier *Base) 1583 : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {} 1584 1585 /// \brief Determine what kind of offsetof node this is. 1586 Kind getKind() const { 1587 return static_cast<Kind>(Data & Mask); 1588 } 1589 1590 /// \brief For an array element node, returns the index into the array 1591 /// of expressions. 1592 unsigned getArrayExprIndex() const { 1593 assert(getKind() == Array); 1594 return Data >> 2; 1595 } 1596 1597 /// \brief For a field offsetof node, returns the field. 1598 FieldDecl *getField() const { 1599 assert(getKind() == Field); 1600 return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask); 1601 } 1602 1603 /// \brief For a field or identifier offsetof node, returns the name of 1604 /// the field. 1605 IdentifierInfo *getFieldName() const; 1606 1607 /// \brief For a base class node, returns the base specifier. 1608 CXXBaseSpecifier *getBase() const { 1609 assert(getKind() == Base); 1610 return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask); 1611 } 1612 1613 /// \brief Retrieve the source range that covers this offsetof node. 1614 /// 1615 /// For an array element node, the source range contains the locations of 1616 /// the square brackets. For a field or identifier node, the source range 1617 /// contains the location of the period (if there is one) and the 1618 /// identifier. 1619 SourceRange getSourceRange() const { return Range; } 1620 }; 1621 1622private: 1623 1624 SourceLocation OperatorLoc, RParenLoc; 1625 // Base type; 1626 TypeSourceInfo *TSInfo; 1627 // Number of sub-components (i.e. instances of OffsetOfNode). 1628 unsigned NumComps; 1629 // Number of sub-expressions (i.e. array subscript expressions). 1630 unsigned NumExprs; 1631 1632 OffsetOfExpr(ASTContext &C, QualType type, 1633 SourceLocation OperatorLoc, TypeSourceInfo *tsi, 1634 OffsetOfNode* compsPtr, unsigned numComps, 1635 Expr** exprsPtr, unsigned numExprs, 1636 SourceLocation RParenLoc); 1637 1638 explicit OffsetOfExpr(unsigned numComps, unsigned numExprs) 1639 : Expr(OffsetOfExprClass, EmptyShell()), 1640 TSInfo(0), NumComps(numComps), NumExprs(numExprs) {} 1641 1642public: 1643 1644 static OffsetOfExpr *Create(ASTContext &C, QualType type, 1645 SourceLocation OperatorLoc, TypeSourceInfo *tsi, 1646 OffsetOfNode* compsPtr, unsigned numComps, 1647 Expr** exprsPtr, unsigned numExprs, 1648 SourceLocation RParenLoc); 1649 1650 static OffsetOfExpr *CreateEmpty(ASTContext &C, 1651 unsigned NumComps, unsigned NumExprs); 1652 1653 /// getOperatorLoc - Return the location of the operator. 1654 SourceLocation getOperatorLoc() const { return OperatorLoc; } 1655 void setOperatorLoc(SourceLocation L) { OperatorLoc = L; } 1656 1657 /// \brief Return the location of the right parentheses. 1658 SourceLocation getRParenLoc() const { return RParenLoc; } 1659 void setRParenLoc(SourceLocation R) { RParenLoc = R; } 1660 1661 TypeSourceInfo *getTypeSourceInfo() const { 1662 return TSInfo; 1663 } 1664 void setTypeSourceInfo(TypeSourceInfo *tsi) { 1665 TSInfo = tsi; 1666 } 1667 1668 const OffsetOfNode &getComponent(unsigned Idx) const { 1669 assert(Idx < NumComps && "Subscript out of range"); 1670 return reinterpret_cast<const OffsetOfNode *> (this + 1)[Idx]; 1671 } 1672 1673 void setComponent(unsigned Idx, OffsetOfNode ON) { 1674 assert(Idx < NumComps && "Subscript out of range"); 1675 reinterpret_cast<OffsetOfNode *> (this + 1)[Idx] = ON; 1676 } 1677 1678 unsigned getNumComponents() const { 1679 return NumComps; 1680 } 1681 1682 Expr* getIndexExpr(unsigned Idx) { 1683 assert(Idx < NumExprs && "Subscript out of range"); 1684 return reinterpret_cast<Expr **>( 1685 reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx]; 1686 } 1687 const Expr *getIndexExpr(unsigned Idx) const { 1688 return const_cast<OffsetOfExpr*>(this)->getIndexExpr(Idx); 1689 } 1690 1691 void setIndexExpr(unsigned Idx, Expr* E) { 1692 assert(Idx < NumComps && "Subscript out of range"); 1693 reinterpret_cast<Expr **>( 1694 reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx] = E; 1695 } 1696 1697 unsigned getNumExpressions() const { 1698 return NumExprs; 1699 } 1700 1701 SourceRange getSourceRange() const { 1702 return SourceRange(OperatorLoc, RParenLoc); 1703 } 1704 1705 static bool classof(const Stmt *T) { 1706 return T->getStmtClass() == OffsetOfExprClass; 1707 } 1708 1709 static bool classof(const OffsetOfExpr *) { return true; } 1710 1711 // Iterators 1712 child_range children() { 1713 Stmt **begin = 1714 reinterpret_cast<Stmt**>(reinterpret_cast<OffsetOfNode*>(this + 1) 1715 + NumComps); 1716 return child_range(begin, begin + NumExprs); 1717 } 1718}; 1719 1720/// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) 1721/// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and 1722/// vec_step (OpenCL 1.1 6.11.12). 1723class UnaryExprOrTypeTraitExpr : public Expr { 1724 unsigned Kind : 2; 1725 bool isType : 1; // true if operand is a type, false if an expression 1726 union { 1727 TypeSourceInfo *Ty; 1728 Stmt *Ex; 1729 } Argument; 1730 SourceLocation OpLoc, RParenLoc; 1731 1732public: 1733 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo, 1734 QualType resultType, SourceLocation op, 1735 SourceLocation rp) : 1736 Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary, 1737 false, // Never type-dependent (C++ [temp.dep.expr]p3). 1738 // Value-dependent if the argument is type-dependent. 1739 TInfo->getType()->isDependentType(), 1740 TInfo->getType()->isInstantiationDependentType(), 1741 TInfo->getType()->containsUnexpandedParameterPack()), 1742 Kind(ExprKind), isType(true), OpLoc(op), RParenLoc(rp) { 1743 Argument.Ty = TInfo; 1744 } 1745 1746 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E, 1747 QualType resultType, SourceLocation op, 1748 SourceLocation rp) : 1749 Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary, 1750 false, // Never type-dependent (C++ [temp.dep.expr]p3). 1751 // Value-dependent if the argument is type-dependent. 1752 E->isTypeDependent(), 1753 E->isInstantiationDependent(), 1754 E->containsUnexpandedParameterPack()), 1755 Kind(ExprKind), isType(false), OpLoc(op), RParenLoc(rp) { 1756 Argument.Ex = E; 1757 } 1758 1759 /// \brief Construct an empty sizeof/alignof expression. 1760 explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty) 1761 : Expr(UnaryExprOrTypeTraitExprClass, Empty) { } 1762 1763 UnaryExprOrTypeTrait getKind() const { 1764 return static_cast<UnaryExprOrTypeTrait>(Kind); 1765 } 1766 void setKind(UnaryExprOrTypeTrait K) { Kind = K; } 1767 1768 bool isArgumentType() const { return isType; } 1769 QualType getArgumentType() const { 1770 return getArgumentTypeInfo()->getType(); 1771 } 1772 TypeSourceInfo *getArgumentTypeInfo() const { 1773 assert(isArgumentType() && "calling getArgumentType() when arg is expr"); 1774 return Argument.Ty; 1775 } 1776 Expr *getArgumentExpr() { 1777 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type"); 1778 return static_cast<Expr*>(Argument.Ex); 1779 } 1780 const Expr *getArgumentExpr() const { 1781 return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr(); 1782 } 1783 1784 void setArgument(Expr *E) { Argument.Ex = E; isType = false; } 1785 void setArgument(TypeSourceInfo *TInfo) { 1786 Argument.Ty = TInfo; 1787 isType = true; 1788 } 1789 1790 /// Gets the argument type, or the type of the argument expression, whichever 1791 /// is appropriate. 1792 QualType getTypeOfArgument() const { 1793 return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType(); 1794 } 1795 1796 SourceLocation getOperatorLoc() const { return OpLoc; } 1797 void setOperatorLoc(SourceLocation L) { OpLoc = L; } 1798 1799 SourceLocation getRParenLoc() const { return RParenLoc; } 1800 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 1801 1802 SourceRange getSourceRange() const { 1803 return SourceRange(OpLoc, RParenLoc); 1804 } 1805 1806 static bool classof(const Stmt *T) { 1807 return T->getStmtClass() == UnaryExprOrTypeTraitExprClass; 1808 } 1809 static bool classof(const UnaryExprOrTypeTraitExpr *) { return true; } 1810 1811 // Iterators 1812 child_range children(); 1813}; 1814 1815//===----------------------------------------------------------------------===// 1816// Postfix Operators. 1817//===----------------------------------------------------------------------===// 1818 1819/// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting. 1820class ArraySubscriptExpr : public Expr { 1821 enum { LHS, RHS, END_EXPR=2 }; 1822 Stmt* SubExprs[END_EXPR]; 1823 SourceLocation RBracketLoc; 1824public: 1825 ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t, 1826 ExprValueKind VK, ExprObjectKind OK, 1827 SourceLocation rbracketloc) 1828 : Expr(ArraySubscriptExprClass, t, VK, OK, 1829 lhs->isTypeDependent() || rhs->isTypeDependent(), 1830 lhs->isValueDependent() || rhs->isValueDependent(), 1831 (lhs->isInstantiationDependent() || 1832 rhs->isInstantiationDependent()), 1833 (lhs->containsUnexpandedParameterPack() || 1834 rhs->containsUnexpandedParameterPack())), 1835 RBracketLoc(rbracketloc) { 1836 SubExprs[LHS] = lhs; 1837 SubExprs[RHS] = rhs; 1838 } 1839 1840 /// \brief Create an empty array subscript expression. 1841 explicit ArraySubscriptExpr(EmptyShell Shell) 1842 : Expr(ArraySubscriptExprClass, Shell) { } 1843 1844 /// An array access can be written A[4] or 4[A] (both are equivalent). 1845 /// - getBase() and getIdx() always present the normalized view: A[4]. 1846 /// In this case getBase() returns "A" and getIdx() returns "4". 1847 /// - getLHS() and getRHS() present the syntactic view. e.g. for 1848 /// 4[A] getLHS() returns "4". 1849 /// Note: Because vector element access is also written A[4] we must 1850 /// predicate the format conversion in getBase and getIdx only on the 1851 /// the type of the RHS, as it is possible for the LHS to be a vector of 1852 /// integer type 1853 Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); } 1854 const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } 1855 void setLHS(Expr *E) { SubExprs[LHS] = E; } 1856 1857 Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); } 1858 const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } 1859 void setRHS(Expr *E) { SubExprs[RHS] = E; } 1860 1861 Expr *getBase() { 1862 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS()); 1863 } 1864 1865 const Expr *getBase() const { 1866 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS()); 1867 } 1868 1869 Expr *getIdx() { 1870 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS()); 1871 } 1872 1873 const Expr *getIdx() const { 1874 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS()); 1875 } 1876 1877 SourceRange getSourceRange() const { 1878 return SourceRange(getLHS()->getLocStart(), RBracketLoc); 1879 } 1880 1881 SourceLocation getRBracketLoc() const { return RBracketLoc; } 1882 void setRBracketLoc(SourceLocation L) { RBracketLoc = L; } 1883 1884 SourceLocation getExprLoc() const { return getBase()->getExprLoc(); } 1885 1886 static bool classof(const Stmt *T) { 1887 return T->getStmtClass() == ArraySubscriptExprClass; 1888 } 1889 static bool classof(const ArraySubscriptExpr *) { return true; } 1890 1891 // Iterators 1892 child_range children() { 1893 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); 1894 } 1895}; 1896 1897 1898/// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]). 1899/// CallExpr itself represents a normal function call, e.g., "f(x, 2)", 1900/// while its subclasses may represent alternative syntax that (semantically) 1901/// results in a function call. For example, CXXOperatorCallExpr is 1902/// a subclass for overloaded operator calls that use operator syntax, e.g., 1903/// "str1 + str2" to resolve to a function call. 1904class CallExpr : public Expr { 1905 enum { FN=0, PREARGS_START=1 }; 1906 Stmt **SubExprs; 1907 unsigned NumArgs; 1908 SourceLocation RParenLoc; 1909 1910protected: 1911 // These versions of the constructor are for derived classes. 1912 CallExpr(ASTContext& C, StmtClass SC, Expr *fn, unsigned NumPreArgs, 1913 Expr **args, unsigned numargs, QualType t, ExprValueKind VK, 1914 SourceLocation rparenloc); 1915 CallExpr(ASTContext &C, StmtClass SC, unsigned NumPreArgs, EmptyShell Empty); 1916 1917 Stmt *getPreArg(unsigned i) { 1918 assert(i < getNumPreArgs() && "Prearg access out of range!"); 1919 return SubExprs[PREARGS_START+i]; 1920 } 1921 const Stmt *getPreArg(unsigned i) const { 1922 assert(i < getNumPreArgs() && "Prearg access out of range!"); 1923 return SubExprs[PREARGS_START+i]; 1924 } 1925 void setPreArg(unsigned i, Stmt *PreArg) { 1926 assert(i < getNumPreArgs() && "Prearg access out of range!"); 1927 SubExprs[PREARGS_START+i] = PreArg; 1928 } 1929 1930 unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; } 1931 1932public: 1933 CallExpr(ASTContext& C, Expr *fn, Expr **args, unsigned numargs, QualType t, 1934 ExprValueKind VK, SourceLocation rparenloc); 1935 1936 /// \brief Build an empty call expression. 1937 CallExpr(ASTContext &C, StmtClass SC, EmptyShell Empty); 1938 1939 const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); } 1940 Expr *getCallee() { return cast<Expr>(SubExprs[FN]); } 1941 void setCallee(Expr *F) { SubExprs[FN] = F; } 1942 1943 Decl *getCalleeDecl(); 1944 const Decl *getCalleeDecl() const { 1945 return const_cast<CallExpr*>(this)->getCalleeDecl(); 1946 } 1947 1948 /// \brief If the callee is a FunctionDecl, return it. Otherwise return 0. 1949 FunctionDecl *getDirectCallee(); 1950 const FunctionDecl *getDirectCallee() const { 1951 return const_cast<CallExpr*>(this)->getDirectCallee(); 1952 } 1953 1954 /// getNumArgs - Return the number of actual arguments to this call. 1955 /// 1956 unsigned getNumArgs() const { return NumArgs; } 1957 1958 /// \brief Retrieve the call arguments. 1959 Expr **getArgs() { 1960 return reinterpret_cast<Expr **>(SubExprs+getNumPreArgs()+PREARGS_START); 1961 } 1962 const Expr *const *getArgs() const { 1963 return const_cast<CallExpr*>(this)->getArgs(); 1964 } 1965 1966 /// getArg - Return the specified argument. 1967 Expr *getArg(unsigned Arg) { 1968 assert(Arg < NumArgs && "Arg access out of range!"); 1969 return cast<Expr>(SubExprs[Arg+getNumPreArgs()+PREARGS_START]); 1970 } 1971 const Expr *getArg(unsigned Arg) const { 1972 assert(Arg < NumArgs && "Arg access out of range!"); 1973 return cast<Expr>(SubExprs[Arg+getNumPreArgs()+PREARGS_START]); 1974 } 1975 1976 /// setArg - Set the specified argument. 1977 void setArg(unsigned Arg, Expr *ArgExpr) { 1978 assert(Arg < NumArgs && "Arg access out of range!"); 1979 SubExprs[Arg+getNumPreArgs()+PREARGS_START] = ArgExpr; 1980 } 1981 1982 /// setNumArgs - This changes the number of arguments present in this call. 1983 /// Any orphaned expressions are deleted by this, and any new operands are set 1984 /// to null. 1985 void setNumArgs(ASTContext& C, unsigned NumArgs); 1986 1987 typedef ExprIterator arg_iterator; 1988 typedef ConstExprIterator const_arg_iterator; 1989 1990 arg_iterator arg_begin() { return SubExprs+PREARGS_START+getNumPreArgs(); } 1991 arg_iterator arg_end() { 1992 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs(); 1993 } 1994 const_arg_iterator arg_begin() const { 1995 return SubExprs+PREARGS_START+getNumPreArgs(); 1996 } 1997 const_arg_iterator arg_end() const { 1998 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs(); 1999 } 2000 2001 /// getNumCommas - Return the number of commas that must have been present in 2002 /// this function call. 2003 unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; } 2004 2005 /// isBuiltinCall - If this is a call to a builtin, return the builtin ID. If 2006 /// not, return 0. 2007 unsigned isBuiltinCall(const ASTContext &Context) const; 2008 2009 /// getCallReturnType - Get the return type of the call expr. This is not 2010 /// always the type of the expr itself, if the return type is a reference 2011 /// type. 2012 QualType getCallReturnType() const; 2013 2014 SourceLocation getRParenLoc() const { return RParenLoc; } 2015 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 2016 2017 SourceRange getSourceRange() const; 2018 2019 static bool classof(const Stmt *T) { 2020 return T->getStmtClass() >= firstCallExprConstant && 2021 T->getStmtClass() <= lastCallExprConstant; 2022 } 2023 static bool classof(const CallExpr *) { return true; } 2024 2025 // Iterators 2026 child_range children() { 2027 return child_range(&SubExprs[0], 2028 &SubExprs[0]+NumArgs+getNumPreArgs()+PREARGS_START); 2029 } 2030}; 2031 2032/// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F. 2033/// 2034class MemberExpr : public Expr { 2035 /// Extra data stored in some member expressions. 2036 struct MemberNameQualifier { 2037 /// \brief The nested-name-specifier that qualifies the name, including 2038 /// source-location information. 2039 NestedNameSpecifierLoc QualifierLoc; 2040 2041 /// \brief The DeclAccessPair through which the MemberDecl was found due to 2042 /// name qualifiers. 2043 DeclAccessPair FoundDecl; 2044 }; 2045 2046 /// Base - the expression for the base pointer or structure references. In 2047 /// X.F, this is "X". 2048 Stmt *Base; 2049 2050 /// MemberDecl - This is the decl being referenced by the field/member name. 2051 /// In X.F, this is the decl referenced by F. 2052 ValueDecl *MemberDecl; 2053 2054 /// MemberLoc - This is the location of the member name. 2055 SourceLocation MemberLoc; 2056 2057 /// MemberDNLoc - Provides source/type location info for the 2058 /// declaration name embedded in MemberDecl. 2059 DeclarationNameLoc MemberDNLoc; 2060 2061 /// IsArrow - True if this is "X->F", false if this is "X.F". 2062 bool IsArrow : 1; 2063 2064 /// \brief True if this member expression used a nested-name-specifier to 2065 /// refer to the member, e.g., "x->Base::f", or found its member via a using 2066 /// declaration. When true, a MemberNameQualifier 2067 /// structure is allocated immediately after the MemberExpr. 2068 bool HasQualifierOrFoundDecl : 1; 2069 2070 /// \brief True if this member expression specified a template argument list 2071 /// explicitly, e.g., x->f<int>. When true, an ExplicitTemplateArgumentList 2072 /// structure (and its TemplateArguments) are allocated immediately after 2073 /// the MemberExpr or, if the member expression also has a qualifier, after 2074 /// the MemberNameQualifier structure. 2075 bool HasExplicitTemplateArgumentList : 1; 2076 2077 /// \brief True if this member expression refers to a method that 2078 /// was resolved from an overloaded set having size greater than 1. 2079 bool HadMultipleCandidates : 1; 2080 2081 /// \brief Retrieve the qualifier that preceded the member name, if any. 2082 MemberNameQualifier *getMemberQualifier() { 2083 assert(HasQualifierOrFoundDecl); 2084 return reinterpret_cast<MemberNameQualifier *> (this + 1); 2085 } 2086 2087 /// \brief Retrieve the qualifier that preceded the member name, if any. 2088 const MemberNameQualifier *getMemberQualifier() const { 2089 return const_cast<MemberExpr *>(this)->getMemberQualifier(); 2090 } 2091 2092public: 2093 MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl, 2094 const DeclarationNameInfo &NameInfo, QualType ty, 2095 ExprValueKind VK, ExprObjectKind OK) 2096 : Expr(MemberExprClass, ty, VK, OK, 2097 base->isTypeDependent(), 2098 base->isValueDependent(), 2099 base->isInstantiationDependent(), 2100 base->containsUnexpandedParameterPack()), 2101 Base(base), MemberDecl(memberdecl), MemberLoc(NameInfo.getLoc()), 2102 MemberDNLoc(NameInfo.getInfo()), IsArrow(isarrow), 2103 HasQualifierOrFoundDecl(false), HasExplicitTemplateArgumentList(false), 2104 HadMultipleCandidates(false) { 2105 assert(memberdecl->getDeclName() == NameInfo.getName()); 2106 } 2107 2108 // NOTE: this constructor should be used only when it is known that 2109 // the member name can not provide additional syntactic info 2110 // (i.e., source locations for C++ operator names or type source info 2111 // for constructors, destructors and conversion oeprators). 2112 MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl, 2113 SourceLocation l, QualType ty, 2114 ExprValueKind VK, ExprObjectKind OK) 2115 : Expr(MemberExprClass, ty, VK, OK, 2116 base->isTypeDependent(), base->isValueDependent(), 2117 base->isInstantiationDependent(), 2118 base->containsUnexpandedParameterPack()), 2119 Base(base), MemberDecl(memberdecl), MemberLoc(l), MemberDNLoc(), 2120 IsArrow(isarrow), 2121 HasQualifierOrFoundDecl(false), HasExplicitTemplateArgumentList(false), 2122 HadMultipleCandidates(false) {} 2123 2124 static MemberExpr *Create(ASTContext &C, Expr *base, bool isarrow, 2125 NestedNameSpecifierLoc QualifierLoc, 2126 ValueDecl *memberdecl, DeclAccessPair founddecl, 2127 DeclarationNameInfo MemberNameInfo, 2128 const TemplateArgumentListInfo *targs, 2129 QualType ty, ExprValueKind VK, ExprObjectKind OK); 2130 2131 void setBase(Expr *E) { Base = E; } 2132 Expr *getBase() const { return cast<Expr>(Base); } 2133 2134 /// \brief Retrieve the member declaration to which this expression refers. 2135 /// 2136 /// The returned declaration will either be a FieldDecl or (in C++) 2137 /// a CXXMethodDecl. 2138 ValueDecl *getMemberDecl() const { return MemberDecl; } 2139 void setMemberDecl(ValueDecl *D) { MemberDecl = D; } 2140 2141 /// \brief Retrieves the declaration found by lookup. 2142 DeclAccessPair getFoundDecl() const { 2143 if (!HasQualifierOrFoundDecl) 2144 return DeclAccessPair::make(getMemberDecl(), 2145 getMemberDecl()->getAccess()); 2146 return getMemberQualifier()->FoundDecl; 2147 } 2148 2149 /// \brief Determines whether this member expression actually had 2150 /// a C++ nested-name-specifier prior to the name of the member, e.g., 2151 /// x->Base::foo. 2152 bool hasQualifier() const { return getQualifier() != 0; } 2153 2154 /// \brief If the member name was qualified, retrieves the 2155 /// nested-name-specifier that precedes the member name. Otherwise, returns 2156 /// NULL. 2157 NestedNameSpecifier *getQualifier() const { 2158 if (!HasQualifierOrFoundDecl) 2159 return 0; 2160 2161 return getMemberQualifier()->QualifierLoc.getNestedNameSpecifier(); 2162 } 2163 2164 /// \brief If the member name was qualified, retrieves the 2165 /// nested-name-specifier that precedes the member name, with source-location 2166 /// information. 2167 NestedNameSpecifierLoc getQualifierLoc() const { 2168 if (!hasQualifier()) 2169 return NestedNameSpecifierLoc(); 2170 2171 return getMemberQualifier()->QualifierLoc; 2172 } 2173 2174 /// \brief Determines whether this member expression actually had a C++ 2175 /// template argument list explicitly specified, e.g., x.f<int>. 2176 bool hasExplicitTemplateArgs() const { 2177 return HasExplicitTemplateArgumentList; 2178 } 2179 2180 /// \brief Copies the template arguments (if present) into the given 2181 /// structure. 2182 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const { 2183 if (hasExplicitTemplateArgs()) 2184 getExplicitTemplateArgs().copyInto(List); 2185 } 2186 2187 /// \brief Retrieve the explicit template argument list that 2188 /// follow the member template name. This must only be called on an 2189 /// expression with explicit template arguments. 2190 ASTTemplateArgumentListInfo &getExplicitTemplateArgs() { 2191 assert(HasExplicitTemplateArgumentList); 2192 if (!HasQualifierOrFoundDecl) 2193 return *reinterpret_cast<ASTTemplateArgumentListInfo *>(this + 1); 2194 2195 return *reinterpret_cast<ASTTemplateArgumentListInfo *>( 2196 getMemberQualifier() + 1); 2197 } 2198 2199 /// \brief Retrieve the explicit template argument list that 2200 /// followed the member template name. This must only be called on 2201 /// an expression with explicit template arguments. 2202 const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const { 2203 return const_cast<MemberExpr *>(this)->getExplicitTemplateArgs(); 2204 } 2205 2206 /// \brief Retrieves the optional explicit template arguments. 2207 /// This points to the same data as getExplicitTemplateArgs(), but 2208 /// returns null if there are no explicit template arguments. 2209 const ASTTemplateArgumentListInfo *getOptionalExplicitTemplateArgs() const { 2210 if (!hasExplicitTemplateArgs()) return 0; 2211 return &getExplicitTemplateArgs(); 2212 } 2213 2214 /// \brief Retrieve the location of the left angle bracket following the 2215 /// member name ('<'), if any. 2216 SourceLocation getLAngleLoc() const { 2217 if (!HasExplicitTemplateArgumentList) 2218 return SourceLocation(); 2219 2220 return getExplicitTemplateArgs().LAngleLoc; 2221 } 2222 2223 /// \brief Retrieve the template arguments provided as part of this 2224 /// template-id. 2225 const TemplateArgumentLoc *getTemplateArgs() const { 2226 if (!HasExplicitTemplateArgumentList) 2227 return 0; 2228 2229 return getExplicitTemplateArgs().getTemplateArgs(); 2230 } 2231 2232 /// \brief Retrieve the number of template arguments provided as part of this 2233 /// template-id. 2234 unsigned getNumTemplateArgs() const { 2235 if (!HasExplicitTemplateArgumentList) 2236 return 0; 2237 2238 return getExplicitTemplateArgs().NumTemplateArgs; 2239 } 2240 2241 /// \brief Retrieve the location of the right angle bracket following the 2242 /// template arguments ('>'). 2243 SourceLocation getRAngleLoc() const { 2244 if (!HasExplicitTemplateArgumentList) 2245 return SourceLocation(); 2246 2247 return getExplicitTemplateArgs().RAngleLoc; 2248 } 2249 2250 /// \brief Retrieve the member declaration name info. 2251 DeclarationNameInfo getMemberNameInfo() const { 2252 return DeclarationNameInfo(MemberDecl->getDeclName(), 2253 MemberLoc, MemberDNLoc); 2254 } 2255 2256 bool isArrow() const { return IsArrow; } 2257 void setArrow(bool A) { IsArrow = A; } 2258 2259 /// getMemberLoc - Return the location of the "member", in X->F, it is the 2260 /// location of 'F'. 2261 SourceLocation getMemberLoc() const { return MemberLoc; } 2262 void setMemberLoc(SourceLocation L) { MemberLoc = L; } 2263 2264 SourceRange getSourceRange() const; 2265 2266 SourceLocation getExprLoc() const { return MemberLoc; } 2267 2268 /// \brief Determine whether the base of this explicit is implicit. 2269 bool isImplicitAccess() const { 2270 return getBase() && getBase()->isImplicitCXXThis(); 2271 } 2272 2273 /// \brief Returns true if this member expression refers to a method that 2274 /// was resolved from an overloaded set having size greater than 1. 2275 bool hadMultipleCandidates() const { 2276 return HadMultipleCandidates; 2277 } 2278 /// \brief Sets the flag telling whether this expression refers to 2279 /// a method that was resolved from an overloaded set having size 2280 /// greater than 1. 2281 void setHadMultipleCandidates(bool V = true) { 2282 HadMultipleCandidates = V; 2283 } 2284 2285 static bool classof(const Stmt *T) { 2286 return T->getStmtClass() == MemberExprClass; 2287 } 2288 static bool classof(const MemberExpr *) { return true; } 2289 2290 // Iterators 2291 child_range children() { return child_range(&Base, &Base+1); } 2292 2293 friend class ASTReader; 2294 friend class ASTStmtWriter; 2295}; 2296 2297/// CompoundLiteralExpr - [C99 6.5.2.5] 2298/// 2299class CompoundLiteralExpr : public Expr { 2300 /// LParenLoc - If non-null, this is the location of the left paren in a 2301 /// compound literal like "(int){4}". This can be null if this is a 2302 /// synthesized compound expression. 2303 SourceLocation LParenLoc; 2304 2305 /// The type as written. This can be an incomplete array type, in 2306 /// which case the actual expression type will be different. 2307 TypeSourceInfo *TInfo; 2308 Stmt *Init; 2309 bool FileScope; 2310public: 2311 CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo, 2312 QualType T, ExprValueKind VK, Expr *init, bool fileScope) 2313 : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary, 2314 tinfo->getType()->isDependentType(), 2315 init->isValueDependent(), 2316 (init->isInstantiationDependent() || 2317 tinfo->getType()->isInstantiationDependentType()), 2318 init->containsUnexpandedParameterPack()), 2319 LParenLoc(lparenloc), TInfo(tinfo), Init(init), FileScope(fileScope) {} 2320 2321 /// \brief Construct an empty compound literal. 2322 explicit CompoundLiteralExpr(EmptyShell Empty) 2323 : Expr(CompoundLiteralExprClass, Empty) { } 2324 2325 const Expr *getInitializer() const { return cast<Expr>(Init); } 2326 Expr *getInitializer() { return cast<Expr>(Init); } 2327 void setInitializer(Expr *E) { Init = E; } 2328 2329 bool isFileScope() const { return FileScope; } 2330 void setFileScope(bool FS) { FileScope = FS; } 2331 2332 SourceLocation getLParenLoc() const { return LParenLoc; } 2333 void setLParenLoc(SourceLocation L) { LParenLoc = L; } 2334 2335 TypeSourceInfo *getTypeSourceInfo() const { return TInfo; } 2336 void setTypeSourceInfo(TypeSourceInfo* tinfo) { TInfo = tinfo; } 2337 2338 SourceRange getSourceRange() const { 2339 // FIXME: Init should never be null. 2340 if (!Init) 2341 return SourceRange(); 2342 if (LParenLoc.isInvalid()) 2343 return Init->getSourceRange(); 2344 return SourceRange(LParenLoc, Init->getLocEnd()); 2345 } 2346 2347 static bool classof(const Stmt *T) { 2348 return T->getStmtClass() == CompoundLiteralExprClass; 2349 } 2350 static bool classof(const CompoundLiteralExpr *) { return true; } 2351 2352 // Iterators 2353 child_range children() { return child_range(&Init, &Init+1); } 2354}; 2355 2356/// CastExpr - Base class for type casts, including both implicit 2357/// casts (ImplicitCastExpr) and explicit casts that have some 2358/// representation in the source code (ExplicitCastExpr's derived 2359/// classes). 2360class CastExpr : public Expr { 2361public: 2362 typedef clang::CastKind CastKind; 2363 2364private: 2365 Stmt *Op; 2366 2367 void CheckCastConsistency() const; 2368 2369 const CXXBaseSpecifier * const *path_buffer() const { 2370 return const_cast<CastExpr*>(this)->path_buffer(); 2371 } 2372 CXXBaseSpecifier **path_buffer(); 2373 2374 void setBasePathSize(unsigned basePathSize) { 2375 CastExprBits.BasePathSize = basePathSize; 2376 assert(CastExprBits.BasePathSize == basePathSize && 2377 "basePathSize doesn't fit in bits of CastExprBits.BasePathSize!"); 2378 } 2379 2380protected: 2381 CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, 2382 const CastKind kind, Expr *op, unsigned BasePathSize) : 2383 Expr(SC, ty, VK, OK_Ordinary, 2384 // Cast expressions are type-dependent if the type is 2385 // dependent (C++ [temp.dep.expr]p3). 2386 ty->isDependentType(), 2387 // Cast expressions are value-dependent if the type is 2388 // dependent or if the subexpression is value-dependent. 2389 ty->isDependentType() || (op && op->isValueDependent()), 2390 (ty->isInstantiationDependentType() || 2391 (op && op->isInstantiationDependent())), 2392 (ty->containsUnexpandedParameterPack() || 2393 op->containsUnexpandedParameterPack())), 2394 Op(op) { 2395 assert(kind != CK_Invalid && "creating cast with invalid cast kind"); 2396 CastExprBits.Kind = kind; 2397 setBasePathSize(BasePathSize); 2398#ifndef NDEBUG 2399 CheckCastConsistency(); 2400#endif 2401 } 2402 2403 /// \brief Construct an empty cast. 2404 CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize) 2405 : Expr(SC, Empty) { 2406 setBasePathSize(BasePathSize); 2407 } 2408 2409public: 2410 CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; } 2411 void setCastKind(CastKind K) { CastExprBits.Kind = K; } 2412 const char *getCastKindName() const; 2413 2414 Expr *getSubExpr() { return cast<Expr>(Op); } 2415 const Expr *getSubExpr() const { return cast<Expr>(Op); } 2416 void setSubExpr(Expr *E) { Op = E; } 2417 2418 /// \brief Retrieve the cast subexpression as it was written in the source 2419 /// code, looking through any implicit casts or other intermediate nodes 2420 /// introduced by semantic analysis. 2421 Expr *getSubExprAsWritten(); 2422 const Expr *getSubExprAsWritten() const { 2423 return const_cast<CastExpr *>(this)->getSubExprAsWritten(); 2424 } 2425 2426 typedef CXXBaseSpecifier **path_iterator; 2427 typedef const CXXBaseSpecifier * const *path_const_iterator; 2428 bool path_empty() const { return CastExprBits.BasePathSize == 0; } 2429 unsigned path_size() const { return CastExprBits.BasePathSize; } 2430 path_iterator path_begin() { return path_buffer(); } 2431 path_iterator path_end() { return path_buffer() + path_size(); } 2432 path_const_iterator path_begin() const { return path_buffer(); } 2433 path_const_iterator path_end() const { return path_buffer() + path_size(); } 2434 2435 void setCastPath(const CXXCastPath &Path); 2436 2437 static bool classof(const Stmt *T) { 2438 return T->getStmtClass() >= firstCastExprConstant && 2439 T->getStmtClass() <= lastCastExprConstant; 2440 } 2441 static bool classof(const CastExpr *) { return true; } 2442 2443 // Iterators 2444 child_range children() { return child_range(&Op, &Op+1); } 2445}; 2446 2447/// ImplicitCastExpr - Allows us to explicitly represent implicit type 2448/// conversions, which have no direct representation in the original 2449/// source code. For example: converting T[]->T*, void f()->void 2450/// (*f)(), float->double, short->int, etc. 2451/// 2452/// In C, implicit casts always produce rvalues. However, in C++, an 2453/// implicit cast whose result is being bound to a reference will be 2454/// an lvalue or xvalue. For example: 2455/// 2456/// @code 2457/// class Base { }; 2458/// class Derived : public Base { }; 2459/// Derived &&ref(); 2460/// void f(Derived d) { 2461/// Base& b = d; // initializer is an ImplicitCastExpr 2462/// // to an lvalue of type Base 2463/// Base&& r = ref(); // initializer is an ImplicitCastExpr 2464/// // to an xvalue of type Base 2465/// } 2466/// @endcode 2467class ImplicitCastExpr : public CastExpr { 2468private: 2469 ImplicitCastExpr(QualType ty, CastKind kind, Expr *op, 2470 unsigned BasePathLength, ExprValueKind VK) 2471 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) { 2472 } 2473 2474 /// \brief Construct an empty implicit cast. 2475 explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize) 2476 : CastExpr(ImplicitCastExprClass, Shell, PathSize) { } 2477 2478public: 2479 enum OnStack_t { OnStack }; 2480 ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op, 2481 ExprValueKind VK) 2482 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) { 2483 } 2484 2485 static ImplicitCastExpr *Create(ASTContext &Context, QualType T, 2486 CastKind Kind, Expr *Operand, 2487 const CXXCastPath *BasePath, 2488 ExprValueKind Cat); 2489 2490 static ImplicitCastExpr *CreateEmpty(ASTContext &Context, unsigned PathSize); 2491 2492 SourceRange getSourceRange() const { 2493 return getSubExpr()->getSourceRange(); 2494 } 2495 2496 static bool classof(const Stmt *T) { 2497 return T->getStmtClass() == ImplicitCastExprClass; 2498 } 2499 static bool classof(const ImplicitCastExpr *) { return true; } 2500}; 2501 2502inline Expr *Expr::IgnoreImpCasts() { 2503 Expr *e = this; 2504 while (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e)) 2505 e = ice->getSubExpr(); 2506 return e; 2507} 2508 2509/// ExplicitCastExpr - An explicit cast written in the source 2510/// code. 2511/// 2512/// This class is effectively an abstract class, because it provides 2513/// the basic representation of an explicitly-written cast without 2514/// specifying which kind of cast (C cast, functional cast, static 2515/// cast, etc.) was written; specific derived classes represent the 2516/// particular style of cast and its location information. 2517/// 2518/// Unlike implicit casts, explicit cast nodes have two different 2519/// types: the type that was written into the source code, and the 2520/// actual type of the expression as determined by semantic 2521/// analysis. These types may differ slightly. For example, in C++ one 2522/// can cast to a reference type, which indicates that the resulting 2523/// expression will be an lvalue or xvalue. The reference type, however, 2524/// will not be used as the type of the expression. 2525class ExplicitCastExpr : public CastExpr { 2526 /// TInfo - Source type info for the (written) type 2527 /// this expression is casting to. 2528 TypeSourceInfo *TInfo; 2529 2530protected: 2531 ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK, 2532 CastKind kind, Expr *op, unsigned PathSize, 2533 TypeSourceInfo *writtenTy) 2534 : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {} 2535 2536 /// \brief Construct an empty explicit cast. 2537 ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize) 2538 : CastExpr(SC, Shell, PathSize) { } 2539 2540public: 2541 /// getTypeInfoAsWritten - Returns the type source info for the type 2542 /// that this expression is casting to. 2543 TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; } 2544 void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; } 2545 2546 /// getTypeAsWritten - Returns the type that this expression is 2547 /// casting to, as written in the source code. 2548 QualType getTypeAsWritten() const { return TInfo->getType(); } 2549 2550 static bool classof(const Stmt *T) { 2551 return T->getStmtClass() >= firstExplicitCastExprConstant && 2552 T->getStmtClass() <= lastExplicitCastExprConstant; 2553 } 2554 static bool classof(const ExplicitCastExpr *) { return true; } 2555}; 2556 2557/// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style 2558/// cast in C++ (C++ [expr.cast]), which uses the syntax 2559/// (Type)expr. For example: @c (int)f. 2560class CStyleCastExpr : public ExplicitCastExpr { 2561 SourceLocation LPLoc; // the location of the left paren 2562 SourceLocation RPLoc; // the location of the right paren 2563 2564 CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op, 2565 unsigned PathSize, TypeSourceInfo *writtenTy, 2566 SourceLocation l, SourceLocation r) 2567 : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize, 2568 writtenTy), LPLoc(l), RPLoc(r) {} 2569 2570 /// \brief Construct an empty C-style explicit cast. 2571 explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize) 2572 : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { } 2573 2574public: 2575 static CStyleCastExpr *Create(ASTContext &Context, QualType T, 2576 ExprValueKind VK, CastKind K, 2577 Expr *Op, const CXXCastPath *BasePath, 2578 TypeSourceInfo *WrittenTy, SourceLocation L, 2579 SourceLocation R); 2580 2581 static CStyleCastExpr *CreateEmpty(ASTContext &Context, unsigned PathSize); 2582 2583 SourceLocation getLParenLoc() const { return LPLoc; } 2584 void setLParenLoc(SourceLocation L) { LPLoc = L; } 2585 2586 SourceLocation getRParenLoc() const { return RPLoc; } 2587 void setRParenLoc(SourceLocation L) { RPLoc = L; } 2588 2589 SourceRange getSourceRange() const { 2590 return SourceRange(LPLoc, getSubExpr()->getSourceRange().getEnd()); 2591 } 2592 static bool classof(const Stmt *T) { 2593 return T->getStmtClass() == CStyleCastExprClass; 2594 } 2595 static bool classof(const CStyleCastExpr *) { return true; } 2596}; 2597 2598/// \brief A builtin binary operation expression such as "x + y" or "x <= y". 2599/// 2600/// This expression node kind describes a builtin binary operation, 2601/// such as "x + y" for integer values "x" and "y". The operands will 2602/// already have been converted to appropriate types (e.g., by 2603/// performing promotions or conversions). 2604/// 2605/// In C++, where operators may be overloaded, a different kind of 2606/// expression node (CXXOperatorCallExpr) is used to express the 2607/// invocation of an overloaded operator with operator syntax. Within 2608/// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is 2609/// used to store an expression "x + y" depends on the subexpressions 2610/// for x and y. If neither x or y is type-dependent, and the "+" 2611/// operator resolves to a built-in operation, BinaryOperator will be 2612/// used to express the computation (x and y may still be 2613/// value-dependent). If either x or y is type-dependent, or if the 2614/// "+" resolves to an overloaded operator, CXXOperatorCallExpr will 2615/// be used to express the computation. 2616class BinaryOperator : public Expr { 2617public: 2618 typedef BinaryOperatorKind Opcode; 2619 2620private: 2621 unsigned Opc : 6; 2622 SourceLocation OpLoc; 2623 2624 enum { LHS, RHS, END_EXPR }; 2625 Stmt* SubExprs[END_EXPR]; 2626public: 2627 2628 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, 2629 ExprValueKind VK, ExprObjectKind OK, 2630 SourceLocation opLoc) 2631 : Expr(BinaryOperatorClass, ResTy, VK, OK, 2632 lhs->isTypeDependent() || rhs->isTypeDependent(), 2633 lhs->isValueDependent() || rhs->isValueDependent(), 2634 (lhs->isInstantiationDependent() || 2635 rhs->isInstantiationDependent()), 2636 (lhs->containsUnexpandedParameterPack() || 2637 rhs->containsUnexpandedParameterPack())), 2638 Opc(opc), OpLoc(opLoc) { 2639 SubExprs[LHS] = lhs; 2640 SubExprs[RHS] = rhs; 2641 assert(!isCompoundAssignmentOp() && 2642 "Use ArithAssignBinaryOperator for compound assignments"); 2643 } 2644 2645 /// \brief Construct an empty binary operator. 2646 explicit BinaryOperator(EmptyShell Empty) 2647 : Expr(BinaryOperatorClass, Empty), Opc(BO_Comma) { } 2648 2649 SourceLocation getOperatorLoc() const { return OpLoc; } 2650 void setOperatorLoc(SourceLocation L) { OpLoc = L; } 2651 2652 Opcode getOpcode() const { return static_cast<Opcode>(Opc); } 2653 void setOpcode(Opcode O) { Opc = O; } 2654 2655 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } 2656 void setLHS(Expr *E) { SubExprs[LHS] = E; } 2657 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } 2658 void setRHS(Expr *E) { SubExprs[RHS] = E; } 2659 2660 SourceRange getSourceRange() const { 2661 return SourceRange(getLHS()->getLocStart(), getRHS()->getLocEnd()); 2662 } 2663 2664 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it 2665 /// corresponds to, e.g. "<<=". 2666 static const char *getOpcodeStr(Opcode Op); 2667 2668 const char *getOpcodeStr() const { return getOpcodeStr(getOpcode()); } 2669 2670 /// \brief Retrieve the binary opcode that corresponds to the given 2671 /// overloaded operator. 2672 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO); 2673 2674 /// \brief Retrieve the overloaded operator kind that corresponds to 2675 /// the given binary opcode. 2676 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc); 2677 2678 /// predicates to categorize the respective opcodes. 2679 bool isPtrMemOp() const { return Opc == BO_PtrMemD || Opc == BO_PtrMemI; } 2680 bool isMultiplicativeOp() const { return Opc >= BO_Mul && Opc <= BO_Rem; } 2681 static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; } 2682 bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); } 2683 static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; } 2684 bool isShiftOp() const { return isShiftOp(getOpcode()); } 2685 2686 static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; } 2687 bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); } 2688 2689 static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; } 2690 bool isRelationalOp() const { return isRelationalOp(getOpcode()); } 2691 2692 static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; } 2693 bool isEqualityOp() const { return isEqualityOp(getOpcode()); } 2694 2695 static bool isComparisonOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_NE; } 2696 bool isComparisonOp() const { return isComparisonOp(getOpcode()); } 2697 2698 static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; } 2699 bool isLogicalOp() const { return isLogicalOp(getOpcode()); } 2700 2701 static bool isAssignmentOp(Opcode Opc) { 2702 return Opc >= BO_Assign && Opc <= BO_OrAssign; 2703 } 2704 bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); } 2705 2706 static bool isCompoundAssignmentOp(Opcode Opc) { 2707 return Opc > BO_Assign && Opc <= BO_OrAssign; 2708 } 2709 bool isCompoundAssignmentOp() const { 2710 return isCompoundAssignmentOp(getOpcode()); 2711 } 2712 2713 static bool isShiftAssignOp(Opcode Opc) { 2714 return Opc == BO_ShlAssign || Opc == BO_ShrAssign; 2715 } 2716 bool isShiftAssignOp() const { 2717 return isShiftAssignOp(getOpcode()); 2718 } 2719 2720 static bool classof(const Stmt *S) { 2721 return S->getStmtClass() >= firstBinaryOperatorConstant && 2722 S->getStmtClass() <= lastBinaryOperatorConstant; 2723 } 2724 static bool classof(const BinaryOperator *) { return true; } 2725 2726 // Iterators 2727 child_range children() { 2728 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); 2729 } 2730 2731protected: 2732 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, 2733 ExprValueKind VK, ExprObjectKind OK, 2734 SourceLocation opLoc, bool dead) 2735 : Expr(CompoundAssignOperatorClass, ResTy, VK, OK, 2736 lhs->isTypeDependent() || rhs->isTypeDependent(), 2737 lhs->isValueDependent() || rhs->isValueDependent(), 2738 (lhs->isInstantiationDependent() || 2739 rhs->isInstantiationDependent()), 2740 (lhs->containsUnexpandedParameterPack() || 2741 rhs->containsUnexpandedParameterPack())), 2742 Opc(opc), OpLoc(opLoc) { 2743 SubExprs[LHS] = lhs; 2744 SubExprs[RHS] = rhs; 2745 } 2746 2747 BinaryOperator(StmtClass SC, EmptyShell Empty) 2748 : Expr(SC, Empty), Opc(BO_MulAssign) { } 2749}; 2750 2751/// CompoundAssignOperator - For compound assignments (e.g. +=), we keep 2752/// track of the type the operation is performed in. Due to the semantics of 2753/// these operators, the operands are promoted, the arithmetic performed, an 2754/// implicit conversion back to the result type done, then the assignment takes 2755/// place. This captures the intermediate type which the computation is done 2756/// in. 2757class CompoundAssignOperator : public BinaryOperator { 2758 QualType ComputationLHSType; 2759 QualType ComputationResultType; 2760public: 2761 CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResType, 2762 ExprValueKind VK, ExprObjectKind OK, 2763 QualType CompLHSType, QualType CompResultType, 2764 SourceLocation OpLoc) 2765 : BinaryOperator(lhs, rhs, opc, ResType, VK, OK, OpLoc, true), 2766 ComputationLHSType(CompLHSType), 2767 ComputationResultType(CompResultType) { 2768 assert(isCompoundAssignmentOp() && 2769 "Only should be used for compound assignments"); 2770 } 2771 2772 /// \brief Build an empty compound assignment operator expression. 2773 explicit CompoundAssignOperator(EmptyShell Empty) 2774 : BinaryOperator(CompoundAssignOperatorClass, Empty) { } 2775 2776 // The two computation types are the type the LHS is converted 2777 // to for the computation and the type of the result; the two are 2778 // distinct in a few cases (specifically, int+=ptr and ptr-=ptr). 2779 QualType getComputationLHSType() const { return ComputationLHSType; } 2780 void setComputationLHSType(QualType T) { ComputationLHSType = T; } 2781 2782 QualType getComputationResultType() const { return ComputationResultType; } 2783 void setComputationResultType(QualType T) { ComputationResultType = T; } 2784 2785 static bool classof(const CompoundAssignOperator *) { return true; } 2786 static bool classof(const Stmt *S) { 2787 return S->getStmtClass() == CompoundAssignOperatorClass; 2788 } 2789}; 2790 2791/// AbstractConditionalOperator - An abstract base class for 2792/// ConditionalOperator and BinaryConditionalOperator. 2793class AbstractConditionalOperator : public Expr { 2794 SourceLocation QuestionLoc, ColonLoc; 2795 friend class ASTStmtReader; 2796 2797protected: 2798 AbstractConditionalOperator(StmtClass SC, QualType T, 2799 ExprValueKind VK, ExprObjectKind OK, 2800 bool TD, bool VD, bool ID, 2801 bool ContainsUnexpandedParameterPack, 2802 SourceLocation qloc, 2803 SourceLocation cloc) 2804 : Expr(SC, T, VK, OK, TD, VD, ID, ContainsUnexpandedParameterPack), 2805 QuestionLoc(qloc), ColonLoc(cloc) {} 2806 2807 AbstractConditionalOperator(StmtClass SC, EmptyShell Empty) 2808 : Expr(SC, Empty) { } 2809 2810public: 2811 // getCond - Return the expression representing the condition for 2812 // the ?: operator. 2813 Expr *getCond() const; 2814 2815 // getTrueExpr - Return the subexpression representing the value of 2816 // the expression if the condition evaluates to true. 2817 Expr *getTrueExpr() const; 2818 2819 // getFalseExpr - Return the subexpression representing the value of 2820 // the expression if the condition evaluates to false. This is 2821 // the same as getRHS. 2822 Expr *getFalseExpr() const; 2823 2824 SourceLocation getQuestionLoc() const { return QuestionLoc; } 2825 SourceLocation getColonLoc() const { return ColonLoc; } 2826 2827 static bool classof(const Stmt *T) { 2828 return T->getStmtClass() == ConditionalOperatorClass || 2829 T->getStmtClass() == BinaryConditionalOperatorClass; 2830 } 2831 static bool classof(const AbstractConditionalOperator *) { return true; } 2832}; 2833 2834/// ConditionalOperator - The ?: ternary operator. The GNU "missing 2835/// middle" extension is a BinaryConditionalOperator. 2836class ConditionalOperator : public AbstractConditionalOperator { 2837 enum { COND, LHS, RHS, END_EXPR }; 2838 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides. 2839 2840 friend class ASTStmtReader; 2841public: 2842 ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs, 2843 SourceLocation CLoc, Expr *rhs, 2844 QualType t, ExprValueKind VK, ExprObjectKind OK) 2845 : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK, 2846 // FIXME: the type of the conditional operator doesn't 2847 // depend on the type of the conditional, but the standard 2848 // seems to imply that it could. File a bug! 2849 (lhs->isTypeDependent() || rhs->isTypeDependent()), 2850 (cond->isValueDependent() || lhs->isValueDependent() || 2851 rhs->isValueDependent()), 2852 (cond->isInstantiationDependent() || 2853 lhs->isInstantiationDependent() || 2854 rhs->isInstantiationDependent()), 2855 (cond->containsUnexpandedParameterPack() || 2856 lhs->containsUnexpandedParameterPack() || 2857 rhs->containsUnexpandedParameterPack()), 2858 QLoc, CLoc) { 2859 SubExprs[COND] = cond; 2860 SubExprs[LHS] = lhs; 2861 SubExprs[RHS] = rhs; 2862 } 2863 2864 /// \brief Build an empty conditional operator. 2865 explicit ConditionalOperator(EmptyShell Empty) 2866 : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { } 2867 2868 // getCond - Return the expression representing the condition for 2869 // the ?: operator. 2870 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); } 2871 2872 // getTrueExpr - Return the subexpression representing the value of 2873 // the expression if the condition evaluates to true. 2874 Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); } 2875 2876 // getFalseExpr - Return the subexpression representing the value of 2877 // the expression if the condition evaluates to false. This is 2878 // the same as getRHS. 2879 Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); } 2880 2881 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } 2882 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } 2883 2884 SourceRange getSourceRange() const { 2885 return SourceRange(getCond()->getLocStart(), getRHS()->getLocEnd()); 2886 } 2887 static bool classof(const Stmt *T) { 2888 return T->getStmtClass() == ConditionalOperatorClass; 2889 } 2890 static bool classof(const ConditionalOperator *) { return true; } 2891 2892 // Iterators 2893 child_range children() { 2894 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); 2895 } 2896}; 2897 2898/// BinaryConditionalOperator - The GNU extension to the conditional 2899/// operator which allows the middle operand to be omitted. 2900/// 2901/// This is a different expression kind on the assumption that almost 2902/// every client ends up needing to know that these are different. 2903class BinaryConditionalOperator : public AbstractConditionalOperator { 2904 enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS }; 2905 2906 /// - the common condition/left-hand-side expression, which will be 2907 /// evaluated as the opaque value 2908 /// - the condition, expressed in terms of the opaque value 2909 /// - the left-hand-side, expressed in terms of the opaque value 2910 /// - the right-hand-side 2911 Stmt *SubExprs[NUM_SUBEXPRS]; 2912 OpaqueValueExpr *OpaqueValue; 2913 2914 friend class ASTStmtReader; 2915public: 2916 BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue, 2917 Expr *cond, Expr *lhs, Expr *rhs, 2918 SourceLocation qloc, SourceLocation cloc, 2919 QualType t, ExprValueKind VK, ExprObjectKind OK) 2920 : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK, 2921 (common->isTypeDependent() || rhs->isTypeDependent()), 2922 (common->isValueDependent() || rhs->isValueDependent()), 2923 (common->isInstantiationDependent() || 2924 rhs->isInstantiationDependent()), 2925 (common->containsUnexpandedParameterPack() || 2926 rhs->containsUnexpandedParameterPack()), 2927 qloc, cloc), 2928 OpaqueValue(opaqueValue) { 2929 SubExprs[COMMON] = common; 2930 SubExprs[COND] = cond; 2931 SubExprs[LHS] = lhs; 2932 SubExprs[RHS] = rhs; 2933 2934 OpaqueValue->setSourceExpr(common); 2935 } 2936 2937 /// \brief Build an empty conditional operator. 2938 explicit BinaryConditionalOperator(EmptyShell Empty) 2939 : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { } 2940 2941 /// \brief getCommon - Return the common expression, written to the 2942 /// left of the condition. The opaque value will be bound to the 2943 /// result of this expression. 2944 Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); } 2945 2946 /// \brief getOpaqueValue - Return the opaque value placeholder. 2947 OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; } 2948 2949 /// \brief getCond - Return the condition expression; this is defined 2950 /// in terms of the opaque value. 2951 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); } 2952 2953 /// \brief getTrueExpr - Return the subexpression which will be 2954 /// evaluated if the condition evaluates to true; this is defined 2955 /// in terms of the opaque value. 2956 Expr *getTrueExpr() const { 2957 return cast<Expr>(SubExprs[LHS]); 2958 } 2959 2960 /// \brief getFalseExpr - Return the subexpression which will be 2961 /// evaluated if the condnition evaluates to false; this is 2962 /// defined in terms of the opaque value. 2963 Expr *getFalseExpr() const { 2964 return cast<Expr>(SubExprs[RHS]); 2965 } 2966 2967 SourceRange getSourceRange() const { 2968 return SourceRange(getCommon()->getLocStart(), getFalseExpr()->getLocEnd()); 2969 } 2970 static bool classof(const Stmt *T) { 2971 return T->getStmtClass() == BinaryConditionalOperatorClass; 2972 } 2973 static bool classof(const BinaryConditionalOperator *) { return true; } 2974 2975 // Iterators 2976 child_range children() { 2977 return child_range(SubExprs, SubExprs + NUM_SUBEXPRS); 2978 } 2979}; 2980 2981inline Expr *AbstractConditionalOperator::getCond() const { 2982 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this)) 2983 return co->getCond(); 2984 return cast<BinaryConditionalOperator>(this)->getCond(); 2985} 2986 2987inline Expr *AbstractConditionalOperator::getTrueExpr() const { 2988 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this)) 2989 return co->getTrueExpr(); 2990 return cast<BinaryConditionalOperator>(this)->getTrueExpr(); 2991} 2992 2993inline Expr *AbstractConditionalOperator::getFalseExpr() const { 2994 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this)) 2995 return co->getFalseExpr(); 2996 return cast<BinaryConditionalOperator>(this)->getFalseExpr(); 2997} 2998 2999/// AddrLabelExpr - The GNU address of label extension, representing &&label. 3000class AddrLabelExpr : public Expr { 3001 SourceLocation AmpAmpLoc, LabelLoc; 3002 LabelDecl *Label; 3003public: 3004 AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L, 3005 QualType t) 3006 : Expr(AddrLabelExprClass, t, VK_RValue, OK_Ordinary, false, false, false, 3007 false), 3008 AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {} 3009 3010 /// \brief Build an empty address of a label expression. 3011 explicit AddrLabelExpr(EmptyShell Empty) 3012 : Expr(AddrLabelExprClass, Empty) { } 3013 3014 SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; } 3015 void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; } 3016 SourceLocation getLabelLoc() const { return LabelLoc; } 3017 void setLabelLoc(SourceLocation L) { LabelLoc = L; } 3018 3019 SourceRange getSourceRange() const { 3020 return SourceRange(AmpAmpLoc, LabelLoc); 3021 } 3022 3023 LabelDecl *getLabel() const { return Label; } 3024 void setLabel(LabelDecl *L) { Label = L; } 3025 3026 static bool classof(const Stmt *T) { 3027 return T->getStmtClass() == AddrLabelExprClass; 3028 } 3029 static bool classof(const AddrLabelExpr *) { return true; } 3030 3031 // Iterators 3032 child_range children() { return child_range(); } 3033}; 3034 3035/// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}). 3036/// The StmtExpr contains a single CompoundStmt node, which it evaluates and 3037/// takes the value of the last subexpression. 3038/// 3039/// A StmtExpr is always an r-value; values "returned" out of a 3040/// StmtExpr will be copied. 3041class StmtExpr : public Expr { 3042 Stmt *SubStmt; 3043 SourceLocation LParenLoc, RParenLoc; 3044public: 3045 // FIXME: Does type-dependence need to be computed differently? 3046 // FIXME: Do we need to compute instantiation instantiation-dependence for 3047 // statements? (ugh!) 3048 StmtExpr(CompoundStmt *substmt, QualType T, 3049 SourceLocation lp, SourceLocation rp) : 3050 Expr(StmtExprClass, T, VK_RValue, OK_Ordinary, 3051 T->isDependentType(), false, false, false), 3052 SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { } 3053 3054 /// \brief Build an empty statement expression. 3055 explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { } 3056 3057 CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); } 3058 const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); } 3059 void setSubStmt(CompoundStmt *S) { SubStmt = S; } 3060 3061 SourceRange getSourceRange() const { 3062 return SourceRange(LParenLoc, RParenLoc); 3063 } 3064 3065 SourceLocation getLParenLoc() const { return LParenLoc; } 3066 void setLParenLoc(SourceLocation L) { LParenLoc = L; } 3067 SourceLocation getRParenLoc() const { return RParenLoc; } 3068 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 3069 3070 static bool classof(const Stmt *T) { 3071 return T->getStmtClass() == StmtExprClass; 3072 } 3073 static bool classof(const StmtExpr *) { return true; } 3074 3075 // Iterators 3076 child_range children() { return child_range(&SubStmt, &SubStmt+1); } 3077}; 3078 3079 3080/// ShuffleVectorExpr - clang-specific builtin-in function 3081/// __builtin_shufflevector. 3082/// This AST node represents a operator that does a constant 3083/// shuffle, similar to LLVM's shufflevector instruction. It takes 3084/// two vectors and a variable number of constant indices, 3085/// and returns the appropriately shuffled vector. 3086class ShuffleVectorExpr : public Expr { 3087 SourceLocation BuiltinLoc, RParenLoc; 3088 3089 // SubExprs - the list of values passed to the __builtin_shufflevector 3090 // function. The first two are vectors, and the rest are constant 3091 // indices. The number of values in this list is always 3092 // 2+the number of indices in the vector type. 3093 Stmt **SubExprs; 3094 unsigned NumExprs; 3095 3096public: 3097 ShuffleVectorExpr(ASTContext &C, Expr **args, unsigned nexpr, 3098 QualType Type, SourceLocation BLoc, 3099 SourceLocation RP); 3100 3101 /// \brief Build an empty vector-shuffle expression. 3102 explicit ShuffleVectorExpr(EmptyShell Empty) 3103 : Expr(ShuffleVectorExprClass, Empty), SubExprs(0) { } 3104 3105 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 3106 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; } 3107 3108 SourceLocation getRParenLoc() const { return RParenLoc; } 3109 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 3110 3111 SourceRange getSourceRange() const { 3112 return SourceRange(BuiltinLoc, RParenLoc); 3113 } 3114 static bool classof(const Stmt *T) { 3115 return T->getStmtClass() == ShuffleVectorExprClass; 3116 } 3117 static bool classof(const ShuffleVectorExpr *) { return true; } 3118 3119 /// getNumSubExprs - Return the size of the SubExprs array. This includes the 3120 /// constant expression, the actual arguments passed in, and the function 3121 /// pointers. 3122 unsigned getNumSubExprs() const { return NumExprs; } 3123 3124 /// \brief Retrieve the array of expressions. 3125 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); } 3126 3127 /// getExpr - Return the Expr at the specified index. 3128 Expr *getExpr(unsigned Index) { 3129 assert((Index < NumExprs) && "Arg access out of range!"); 3130 return cast<Expr>(SubExprs[Index]); 3131 } 3132 const Expr *getExpr(unsigned Index) const { 3133 assert((Index < NumExprs) && "Arg access out of range!"); 3134 return cast<Expr>(SubExprs[Index]); 3135 } 3136 3137 void setExprs(ASTContext &C, Expr ** Exprs, unsigned NumExprs); 3138 3139 unsigned getShuffleMaskIdx(ASTContext &Ctx, unsigned N) { 3140 assert((N < NumExprs - 2) && "Shuffle idx out of range!"); 3141 return getExpr(N+2)->EvaluateKnownConstInt(Ctx).getZExtValue(); 3142 } 3143 3144 // Iterators 3145 child_range children() { 3146 return child_range(&SubExprs[0], &SubExprs[0]+NumExprs); 3147 } 3148}; 3149 3150/// ChooseExpr - GNU builtin-in function __builtin_choose_expr. 3151/// This AST node is similar to the conditional operator (?:) in C, with 3152/// the following exceptions: 3153/// - the test expression must be a integer constant expression. 3154/// - the expression returned acts like the chosen subexpression in every 3155/// visible way: the type is the same as that of the chosen subexpression, 3156/// and all predicates (whether it's an l-value, whether it's an integer 3157/// constant expression, etc.) return the same result as for the chosen 3158/// sub-expression. 3159class ChooseExpr : public Expr { 3160 enum { COND, LHS, RHS, END_EXPR }; 3161 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides. 3162 SourceLocation BuiltinLoc, RParenLoc; 3163public: 3164 ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs, 3165 QualType t, ExprValueKind VK, ExprObjectKind OK, 3166 SourceLocation RP, bool TypeDependent, bool ValueDependent) 3167 : Expr(ChooseExprClass, t, VK, OK, TypeDependent, ValueDependent, 3168 (cond->isInstantiationDependent() || 3169 lhs->isInstantiationDependent() || 3170 rhs->isInstantiationDependent()), 3171 (cond->containsUnexpandedParameterPack() || 3172 lhs->containsUnexpandedParameterPack() || 3173 rhs->containsUnexpandedParameterPack())), 3174 BuiltinLoc(BLoc), RParenLoc(RP) { 3175 SubExprs[COND] = cond; 3176 SubExprs[LHS] = lhs; 3177 SubExprs[RHS] = rhs; 3178 } 3179 3180 /// \brief Build an empty __builtin_choose_expr. 3181 explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { } 3182 3183 /// isConditionTrue - Return whether the condition is true (i.e. not 3184 /// equal to zero). 3185 bool isConditionTrue(const ASTContext &C) const; 3186 3187 /// getChosenSubExpr - Return the subexpression chosen according to the 3188 /// condition. 3189 Expr *getChosenSubExpr(const ASTContext &C) const { 3190 return isConditionTrue(C) ? getLHS() : getRHS(); 3191 } 3192 3193 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); } 3194 void setCond(Expr *E) { SubExprs[COND] = E; } 3195 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } 3196 void setLHS(Expr *E) { SubExprs[LHS] = E; } 3197 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } 3198 void setRHS(Expr *E) { SubExprs[RHS] = E; } 3199 3200 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 3201 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; } 3202 3203 SourceLocation getRParenLoc() const { return RParenLoc; } 3204 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 3205 3206 SourceRange getSourceRange() const { 3207 return SourceRange(BuiltinLoc, RParenLoc); 3208 } 3209 static bool classof(const Stmt *T) { 3210 return T->getStmtClass() == ChooseExprClass; 3211 } 3212 static bool classof(const ChooseExpr *) { return true; } 3213 3214 // Iterators 3215 child_range children() { 3216 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); 3217 } 3218}; 3219 3220/// GNUNullExpr - Implements the GNU __null extension, which is a name 3221/// for a null pointer constant that has integral type (e.g., int or 3222/// long) and is the same size and alignment as a pointer. The __null 3223/// extension is typically only used by system headers, which define 3224/// NULL as __null in C++ rather than using 0 (which is an integer 3225/// that may not match the size of a pointer). 3226class GNUNullExpr : public Expr { 3227 /// TokenLoc - The location of the __null keyword. 3228 SourceLocation TokenLoc; 3229 3230public: 3231 GNUNullExpr(QualType Ty, SourceLocation Loc) 3232 : Expr(GNUNullExprClass, Ty, VK_RValue, OK_Ordinary, false, false, false, 3233 false), 3234 TokenLoc(Loc) { } 3235 3236 /// \brief Build an empty GNU __null expression. 3237 explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { } 3238 3239 /// getTokenLocation - The location of the __null token. 3240 SourceLocation getTokenLocation() const { return TokenLoc; } 3241 void setTokenLocation(SourceLocation L) { TokenLoc = L; } 3242 3243 SourceRange getSourceRange() const { 3244 return SourceRange(TokenLoc); 3245 } 3246 static bool classof(const Stmt *T) { 3247 return T->getStmtClass() == GNUNullExprClass; 3248 } 3249 static bool classof(const GNUNullExpr *) { return true; } 3250 3251 // Iterators 3252 child_range children() { return child_range(); } 3253}; 3254 3255/// VAArgExpr, used for the builtin function __builtin_va_arg. 3256class VAArgExpr : public Expr { 3257 Stmt *Val; 3258 TypeSourceInfo *TInfo; 3259 SourceLocation BuiltinLoc, RParenLoc; 3260public: 3261 VAArgExpr(SourceLocation BLoc, Expr* e, TypeSourceInfo *TInfo, 3262 SourceLocation RPLoc, QualType t) 3263 : Expr(VAArgExprClass, t, VK_RValue, OK_Ordinary, 3264 t->isDependentType(), false, 3265 (TInfo->getType()->isInstantiationDependentType() || 3266 e->isInstantiationDependent()), 3267 (TInfo->getType()->containsUnexpandedParameterPack() || 3268 e->containsUnexpandedParameterPack())), 3269 Val(e), TInfo(TInfo), 3270 BuiltinLoc(BLoc), 3271 RParenLoc(RPLoc) { } 3272 3273 /// \brief Create an empty __builtin_va_arg expression. 3274 explicit VAArgExpr(EmptyShell Empty) : Expr(VAArgExprClass, Empty) { } 3275 3276 const Expr *getSubExpr() const { return cast<Expr>(Val); } 3277 Expr *getSubExpr() { return cast<Expr>(Val); } 3278 void setSubExpr(Expr *E) { Val = E; } 3279 3280 TypeSourceInfo *getWrittenTypeInfo() const { return TInfo; } 3281 void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo = TI; } 3282 3283 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 3284 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; } 3285 3286 SourceLocation getRParenLoc() const { return RParenLoc; } 3287 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 3288 3289 SourceRange getSourceRange() const { 3290 return SourceRange(BuiltinLoc, RParenLoc); 3291 } 3292 static bool classof(const Stmt *T) { 3293 return T->getStmtClass() == VAArgExprClass; 3294 } 3295 static bool classof(const VAArgExpr *) { return true; } 3296 3297 // Iterators 3298 child_range children() { return child_range(&Val, &Val+1); } 3299}; 3300 3301/// @brief Describes an C or C++ initializer list. 3302/// 3303/// InitListExpr describes an initializer list, which can be used to 3304/// initialize objects of different types, including 3305/// struct/class/union types, arrays, and vectors. For example: 3306/// 3307/// @code 3308/// struct foo x = { 1, { 2, 3 } }; 3309/// @endcode 3310/// 3311/// Prior to semantic analysis, an initializer list will represent the 3312/// initializer list as written by the user, but will have the 3313/// placeholder type "void". This initializer list is called the 3314/// syntactic form of the initializer, and may contain C99 designated 3315/// initializers (represented as DesignatedInitExprs), initializations 3316/// of subobject members without explicit braces, and so on. Clients 3317/// interested in the original syntax of the initializer list should 3318/// use the syntactic form of the initializer list. 3319/// 3320/// After semantic analysis, the initializer list will represent the 3321/// semantic form of the initializer, where the initializations of all 3322/// subobjects are made explicit with nested InitListExpr nodes and 3323/// C99 designators have been eliminated by placing the designated 3324/// initializations into the subobject they initialize. Additionally, 3325/// any "holes" in the initialization, where no initializer has been 3326/// specified for a particular subobject, will be replaced with 3327/// implicitly-generated ImplicitValueInitExpr expressions that 3328/// value-initialize the subobjects. Note, however, that the 3329/// initializer lists may still have fewer initializers than there are 3330/// elements to initialize within the object. 3331/// 3332/// Given the semantic form of the initializer list, one can retrieve 3333/// the original syntactic form of that initializer list (if it 3334/// exists) using getSyntacticForm(). Since many initializer lists 3335/// have the same syntactic and semantic forms, getSyntacticForm() may 3336/// return NULL, indicating that the current initializer list also 3337/// serves as its syntactic form. 3338class InitListExpr : public Expr { 3339 // FIXME: Eliminate this vector in favor of ASTContext allocation 3340 typedef ASTVector<Stmt *> InitExprsTy; 3341 InitExprsTy InitExprs; 3342 SourceLocation LBraceLoc, RBraceLoc; 3343 3344 /// Contains the initializer list that describes the syntactic form 3345 /// written in the source code. 3346 InitListExpr *SyntacticForm; 3347 3348 /// \brief Either: 3349 /// If this initializer list initializes an array with more elements than 3350 /// there are initializers in the list, specifies an expression to be used 3351 /// for value initialization of the rest of the elements. 3352 /// Or 3353 /// If this initializer list initializes a union, specifies which 3354 /// field within the union will be initialized. 3355 llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit; 3356 3357 /// Whether this initializer list originally had a GNU array-range 3358 /// designator in it. This is a temporary marker used by CodeGen. 3359 bool HadArrayRangeDesignator; 3360 3361public: 3362 InitListExpr(ASTContext &C, SourceLocation lbraceloc, 3363 Expr **initexprs, unsigned numinits, 3364 SourceLocation rbraceloc); 3365 3366 /// \brief Build an empty initializer list. 3367 explicit InitListExpr(ASTContext &C, EmptyShell Empty) 3368 : Expr(InitListExprClass, Empty), InitExprs(C) { } 3369 3370 unsigned getNumInits() const { return InitExprs.size(); } 3371 3372 /// \brief Retrieve the set of initializers. 3373 Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); } 3374 3375 const Expr *getInit(unsigned Init) const { 3376 assert(Init < getNumInits() && "Initializer access out of range!"); 3377 return cast_or_null<Expr>(InitExprs[Init]); 3378 } 3379 3380 Expr *getInit(unsigned Init) { 3381 assert(Init < getNumInits() && "Initializer access out of range!"); 3382 return cast_or_null<Expr>(InitExprs[Init]); 3383 } 3384 3385 void setInit(unsigned Init, Expr *expr) { 3386 assert(Init < getNumInits() && "Initializer access out of range!"); 3387 InitExprs[Init] = expr; 3388 } 3389 3390 /// \brief Reserve space for some number of initializers. 3391 void reserveInits(ASTContext &C, unsigned NumInits); 3392 3393 /// @brief Specify the number of initializers 3394 /// 3395 /// If there are more than @p NumInits initializers, the remaining 3396 /// initializers will be destroyed. If there are fewer than @p 3397 /// NumInits initializers, NULL expressions will be added for the 3398 /// unknown initializers. 3399 void resizeInits(ASTContext &Context, unsigned NumInits); 3400 3401 /// @brief Updates the initializer at index @p Init with the new 3402 /// expression @p expr, and returns the old expression at that 3403 /// location. 3404 /// 3405 /// When @p Init is out of range for this initializer list, the 3406 /// initializer list will be extended with NULL expressions to 3407 /// accommodate the new entry. 3408 Expr *updateInit(ASTContext &C, unsigned Init, Expr *expr); 3409 3410 /// \brief If this initializer list initializes an array with more elements 3411 /// than there are initializers in the list, specifies an expression to be 3412 /// used for value initialization of the rest of the elements. 3413 Expr *getArrayFiller() { 3414 return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>(); 3415 } 3416 const Expr *getArrayFiller() const { 3417 return const_cast<InitListExpr *>(this)->getArrayFiller(); 3418 } 3419 void setArrayFiller(Expr *filler); 3420 3421 /// \brief Return true if this is an array initializer and its array "filler" 3422 /// has been set. 3423 bool hasArrayFiller() const { return getArrayFiller(); } 3424 3425 /// \brief If this initializes a union, specifies which field in the 3426 /// union to initialize. 3427 /// 3428 /// Typically, this field is the first named field within the 3429 /// union. However, a designated initializer can specify the 3430 /// initialization of a different field within the union. 3431 FieldDecl *getInitializedFieldInUnion() { 3432 return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>(); 3433 } 3434 const FieldDecl *getInitializedFieldInUnion() const { 3435 return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion(); 3436 } 3437 void setInitializedFieldInUnion(FieldDecl *FD) { 3438 ArrayFillerOrUnionFieldInit = FD; 3439 } 3440 3441 // Explicit InitListExpr's originate from source code (and have valid source 3442 // locations). Implicit InitListExpr's are created by the semantic analyzer. 3443 bool isExplicit() { 3444 return LBraceLoc.isValid() && RBraceLoc.isValid(); 3445 } 3446 3447 SourceLocation getLBraceLoc() const { return LBraceLoc; } 3448 void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; } 3449 SourceLocation getRBraceLoc() const { return RBraceLoc; } 3450 void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; } 3451 3452 /// @brief Retrieve the initializer list that describes the 3453 /// syntactic form of the initializer. 3454 /// 3455 /// 3456 InitListExpr *getSyntacticForm() const { return SyntacticForm; } 3457 void setSyntacticForm(InitListExpr *Init) { SyntacticForm = Init; } 3458 3459 bool hadArrayRangeDesignator() const { return HadArrayRangeDesignator; } 3460 void sawArrayRangeDesignator(bool ARD = true) { 3461 HadArrayRangeDesignator = ARD; 3462 } 3463 3464 SourceRange getSourceRange() const; 3465 3466 static bool classof(const Stmt *T) { 3467 return T->getStmtClass() == InitListExprClass; 3468 } 3469 static bool classof(const InitListExpr *) { return true; } 3470 3471 // Iterators 3472 child_range children() { 3473 if (InitExprs.empty()) return child_range(); 3474 return child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size()); 3475 } 3476 3477 typedef InitExprsTy::iterator iterator; 3478 typedef InitExprsTy::const_iterator const_iterator; 3479 typedef InitExprsTy::reverse_iterator reverse_iterator; 3480 typedef InitExprsTy::const_reverse_iterator const_reverse_iterator; 3481 3482 iterator begin() { return InitExprs.begin(); } 3483 const_iterator begin() const { return InitExprs.begin(); } 3484 iterator end() { return InitExprs.end(); } 3485 const_iterator end() const { return InitExprs.end(); } 3486 reverse_iterator rbegin() { return InitExprs.rbegin(); } 3487 const_reverse_iterator rbegin() const { return InitExprs.rbegin(); } 3488 reverse_iterator rend() { return InitExprs.rend(); } 3489 const_reverse_iterator rend() const { return InitExprs.rend(); } 3490 3491 friend class ASTStmtReader; 3492 friend class ASTStmtWriter; 3493}; 3494 3495/// @brief Represents a C99 designated initializer expression. 3496/// 3497/// A designated initializer expression (C99 6.7.8) contains one or 3498/// more designators (which can be field designators, array 3499/// designators, or GNU array-range designators) followed by an 3500/// expression that initializes the field or element(s) that the 3501/// designators refer to. For example, given: 3502/// 3503/// @code 3504/// struct point { 3505/// double x; 3506/// double y; 3507/// }; 3508/// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 }; 3509/// @endcode 3510/// 3511/// The InitListExpr contains three DesignatedInitExprs, the first of 3512/// which covers @c [2].y=1.0. This DesignatedInitExpr will have two 3513/// designators, one array designator for @c [2] followed by one field 3514/// designator for @c .y. The initalization expression will be 1.0. 3515class DesignatedInitExpr : public Expr { 3516public: 3517 /// \brief Forward declaration of the Designator class. 3518 class Designator; 3519 3520private: 3521 /// The location of the '=' or ':' prior to the actual initializer 3522 /// expression. 3523 SourceLocation EqualOrColonLoc; 3524 3525 /// Whether this designated initializer used the GNU deprecated 3526 /// syntax rather than the C99 '=' syntax. 3527 bool GNUSyntax : 1; 3528 3529 /// The number of designators in this initializer expression. 3530 unsigned NumDesignators : 15; 3531 3532 /// \brief The designators in this designated initialization 3533 /// expression. 3534 Designator *Designators; 3535 3536 /// The number of subexpressions of this initializer expression, 3537 /// which contains both the initializer and any additional 3538 /// expressions used by array and array-range designators. 3539 unsigned NumSubExprs : 16; 3540 3541 3542 DesignatedInitExpr(ASTContext &C, QualType Ty, unsigned NumDesignators, 3543 const Designator *Designators, 3544 SourceLocation EqualOrColonLoc, bool GNUSyntax, 3545 Expr **IndexExprs, unsigned NumIndexExprs, 3546 Expr *Init); 3547 3548 explicit DesignatedInitExpr(unsigned NumSubExprs) 3549 : Expr(DesignatedInitExprClass, EmptyShell()), 3550 NumDesignators(0), Designators(0), NumSubExprs(NumSubExprs) { } 3551 3552public: 3553 /// A field designator, e.g., ".x". 3554 struct FieldDesignator { 3555 /// Refers to the field that is being initialized. The low bit 3556 /// of this field determines whether this is actually a pointer 3557 /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When 3558 /// initially constructed, a field designator will store an 3559 /// IdentifierInfo*. After semantic analysis has resolved that 3560 /// name, the field designator will instead store a FieldDecl*. 3561 uintptr_t NameOrField; 3562 3563 /// The location of the '.' in the designated initializer. 3564 unsigned DotLoc; 3565 3566 /// The location of the field name in the designated initializer. 3567 unsigned FieldLoc; 3568 }; 3569 3570 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]". 3571 struct ArrayOrRangeDesignator { 3572 /// Location of the first index expression within the designated 3573 /// initializer expression's list of subexpressions. 3574 unsigned Index; 3575 /// The location of the '[' starting the array range designator. 3576 unsigned LBracketLoc; 3577 /// The location of the ellipsis separating the start and end 3578 /// indices. Only valid for GNU array-range designators. 3579 unsigned EllipsisLoc; 3580 /// The location of the ']' terminating the array range designator. 3581 unsigned RBracketLoc; 3582 }; 3583 3584 /// @brief Represents a single C99 designator. 3585 /// 3586 /// @todo This class is infuriatingly similar to clang::Designator, 3587 /// but minor differences (storing indices vs. storing pointers) 3588 /// keep us from reusing it. Try harder, later, to rectify these 3589 /// differences. 3590 class Designator { 3591 /// @brief The kind of designator this describes. 3592 enum { 3593 FieldDesignator, 3594 ArrayDesignator, 3595 ArrayRangeDesignator 3596 } Kind; 3597 3598 union { 3599 /// A field designator, e.g., ".x". 3600 struct FieldDesignator Field; 3601 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]". 3602 struct ArrayOrRangeDesignator ArrayOrRange; 3603 }; 3604 friend class DesignatedInitExpr; 3605 3606 public: 3607 Designator() {} 3608 3609 /// @brief Initializes a field designator. 3610 Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc, 3611 SourceLocation FieldLoc) 3612 : Kind(FieldDesignator) { 3613 Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01; 3614 Field.DotLoc = DotLoc.getRawEncoding(); 3615 Field.FieldLoc = FieldLoc.getRawEncoding(); 3616 } 3617 3618 /// @brief Initializes an array designator. 3619 Designator(unsigned Index, SourceLocation LBracketLoc, 3620 SourceLocation RBracketLoc) 3621 : Kind(ArrayDesignator) { 3622 ArrayOrRange.Index = Index; 3623 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding(); 3624 ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding(); 3625 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding(); 3626 } 3627 3628 /// @brief Initializes a GNU array-range designator. 3629 Designator(unsigned Index, SourceLocation LBracketLoc, 3630 SourceLocation EllipsisLoc, SourceLocation RBracketLoc) 3631 : Kind(ArrayRangeDesignator) { 3632 ArrayOrRange.Index = Index; 3633 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding(); 3634 ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding(); 3635 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding(); 3636 } 3637 3638 bool isFieldDesignator() const { return Kind == FieldDesignator; } 3639 bool isArrayDesignator() const { return Kind == ArrayDesignator; } 3640 bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; } 3641 3642 IdentifierInfo *getFieldName() const; 3643 3644 FieldDecl *getField() const { 3645 assert(Kind == FieldDesignator && "Only valid on a field designator"); 3646 if (Field.NameOrField & 0x01) 3647 return 0; 3648 else 3649 return reinterpret_cast<FieldDecl *>(Field.NameOrField); 3650 } 3651 3652 void setField(FieldDecl *FD) { 3653 assert(Kind == FieldDesignator && "Only valid on a field designator"); 3654 Field.NameOrField = reinterpret_cast<uintptr_t>(FD); 3655 } 3656 3657 SourceLocation getDotLoc() const { 3658 assert(Kind == FieldDesignator && "Only valid on a field designator"); 3659 return SourceLocation::getFromRawEncoding(Field.DotLoc); 3660 } 3661 3662 SourceLocation getFieldLoc() const { 3663 assert(Kind == FieldDesignator && "Only valid on a field designator"); 3664 return SourceLocation::getFromRawEncoding(Field.FieldLoc); 3665 } 3666 3667 SourceLocation getLBracketLoc() const { 3668 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && 3669 "Only valid on an array or array-range designator"); 3670 return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc); 3671 } 3672 3673 SourceLocation getRBracketLoc() const { 3674 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && 3675 "Only valid on an array or array-range designator"); 3676 return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc); 3677 } 3678 3679 SourceLocation getEllipsisLoc() const { 3680 assert(Kind == ArrayRangeDesignator && 3681 "Only valid on an array-range designator"); 3682 return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc); 3683 } 3684 3685 unsigned getFirstExprIndex() const { 3686 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && 3687 "Only valid on an array or array-range designator"); 3688 return ArrayOrRange.Index; 3689 } 3690 3691 SourceLocation getStartLocation() const { 3692 if (Kind == FieldDesignator) 3693 return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc(); 3694 else 3695 return getLBracketLoc(); 3696 } 3697 SourceLocation getEndLocation() const { 3698 return Kind == FieldDesignator ? getFieldLoc() : getRBracketLoc(); 3699 } 3700 SourceRange getSourceRange() const { 3701 return SourceRange(getStartLocation(), getEndLocation()); 3702 } 3703 }; 3704 3705 static DesignatedInitExpr *Create(ASTContext &C, Designator *Designators, 3706 unsigned NumDesignators, 3707 Expr **IndexExprs, unsigned NumIndexExprs, 3708 SourceLocation EqualOrColonLoc, 3709 bool GNUSyntax, Expr *Init); 3710 3711 static DesignatedInitExpr *CreateEmpty(ASTContext &C, unsigned NumIndexExprs); 3712 3713 /// @brief Returns the number of designators in this initializer. 3714 unsigned size() const { return NumDesignators; } 3715 3716 // Iterator access to the designators. 3717 typedef Designator *designators_iterator; 3718 designators_iterator designators_begin() { return Designators; } 3719 designators_iterator designators_end() { 3720 return Designators + NumDesignators; 3721 } 3722 3723 typedef const Designator *const_designators_iterator; 3724 const_designators_iterator designators_begin() const { return Designators; } 3725 const_designators_iterator designators_end() const { 3726 return Designators + NumDesignators; 3727 } 3728 3729 typedef std::reverse_iterator<designators_iterator> 3730 reverse_designators_iterator; 3731 reverse_designators_iterator designators_rbegin() { 3732 return reverse_designators_iterator(designators_end()); 3733 } 3734 reverse_designators_iterator designators_rend() { 3735 return reverse_designators_iterator(designators_begin()); 3736 } 3737 3738 typedef std::reverse_iterator<const_designators_iterator> 3739 const_reverse_designators_iterator; 3740 const_reverse_designators_iterator designators_rbegin() const { 3741 return const_reverse_designators_iterator(designators_end()); 3742 } 3743 const_reverse_designators_iterator designators_rend() const { 3744 return const_reverse_designators_iterator(designators_begin()); 3745 } 3746 3747 Designator *getDesignator(unsigned Idx) { return &designators_begin()[Idx]; } 3748 3749 void setDesignators(ASTContext &C, const Designator *Desigs, 3750 unsigned NumDesigs); 3751 3752 Expr *getArrayIndex(const Designator& D); 3753 Expr *getArrayRangeStart(const Designator& D); 3754 Expr *getArrayRangeEnd(const Designator& D); 3755 3756 /// @brief Retrieve the location of the '=' that precedes the 3757 /// initializer value itself, if present. 3758 SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; } 3759 void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; } 3760 3761 /// @brief Determines whether this designated initializer used the 3762 /// deprecated GNU syntax for designated initializers. 3763 bool usesGNUSyntax() const { return GNUSyntax; } 3764 void setGNUSyntax(bool GNU) { GNUSyntax = GNU; } 3765 3766 /// @brief Retrieve the initializer value. 3767 Expr *getInit() const { 3768 return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin()); 3769 } 3770 3771 void setInit(Expr *init) { 3772 *child_begin() = init; 3773 } 3774 3775 /// \brief Retrieve the total number of subexpressions in this 3776 /// designated initializer expression, including the actual 3777 /// initialized value and any expressions that occur within array 3778 /// and array-range designators. 3779 unsigned getNumSubExprs() const { return NumSubExprs; } 3780 3781 Expr *getSubExpr(unsigned Idx) { 3782 assert(Idx < NumSubExprs && "Subscript out of range"); 3783 char* Ptr = static_cast<char*>(static_cast<void *>(this)); 3784 Ptr += sizeof(DesignatedInitExpr); 3785 return reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx]; 3786 } 3787 3788 void setSubExpr(unsigned Idx, Expr *E) { 3789 assert(Idx < NumSubExprs && "Subscript out of range"); 3790 char* Ptr = static_cast<char*>(static_cast<void *>(this)); 3791 Ptr += sizeof(DesignatedInitExpr); 3792 reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx] = E; 3793 } 3794 3795 /// \brief Replaces the designator at index @p Idx with the series 3796 /// of designators in [First, Last). 3797 void ExpandDesignator(ASTContext &C, unsigned Idx, const Designator *First, 3798 const Designator *Last); 3799 3800 SourceRange getDesignatorsSourceRange() const; 3801 3802 SourceRange getSourceRange() const; 3803 3804 static bool classof(const Stmt *T) { 3805 return T->getStmtClass() == DesignatedInitExprClass; 3806 } 3807 static bool classof(const DesignatedInitExpr *) { return true; } 3808 3809 // Iterators 3810 child_range children() { 3811 Stmt **begin = reinterpret_cast<Stmt**>(this + 1); 3812 return child_range(begin, begin + NumSubExprs); 3813 } 3814}; 3815 3816/// \brief Represents an implicitly-generated value initialization of 3817/// an object of a given type. 3818/// 3819/// Implicit value initializations occur within semantic initializer 3820/// list expressions (InitListExpr) as placeholders for subobject 3821/// initializations not explicitly specified by the user. 3822/// 3823/// \see InitListExpr 3824class ImplicitValueInitExpr : public Expr { 3825public: 3826 explicit ImplicitValueInitExpr(QualType ty) 3827 : Expr(ImplicitValueInitExprClass, ty, VK_RValue, OK_Ordinary, 3828 false, false, ty->isInstantiationDependentType(), false) { } 3829 3830 /// \brief Construct an empty implicit value initialization. 3831 explicit ImplicitValueInitExpr(EmptyShell Empty) 3832 : Expr(ImplicitValueInitExprClass, Empty) { } 3833 3834 static bool classof(const Stmt *T) { 3835 return T->getStmtClass() == ImplicitValueInitExprClass; 3836 } 3837 static bool classof(const ImplicitValueInitExpr *) { return true; } 3838 3839 SourceRange getSourceRange() const { 3840 return SourceRange(); 3841 } 3842 3843 // Iterators 3844 child_range children() { return child_range(); } 3845}; 3846 3847 3848class ParenListExpr : public Expr { 3849 Stmt **Exprs; 3850 unsigned NumExprs; 3851 SourceLocation LParenLoc, RParenLoc; 3852 3853public: 3854 ParenListExpr(ASTContext& C, SourceLocation lparenloc, Expr **exprs, 3855 unsigned numexprs, SourceLocation rparenloc, QualType T); 3856 3857 /// \brief Build an empty paren list. 3858 explicit ParenListExpr(EmptyShell Empty) : Expr(ParenListExprClass, Empty) { } 3859 3860 unsigned getNumExprs() const { return NumExprs; } 3861 3862 const Expr* getExpr(unsigned Init) const { 3863 assert(Init < getNumExprs() && "Initializer access out of range!"); 3864 return cast_or_null<Expr>(Exprs[Init]); 3865 } 3866 3867 Expr* getExpr(unsigned Init) { 3868 assert(Init < getNumExprs() && "Initializer access out of range!"); 3869 return cast_or_null<Expr>(Exprs[Init]); 3870 } 3871 3872 Expr **getExprs() { return reinterpret_cast<Expr **>(Exprs); } 3873 3874 SourceLocation getLParenLoc() const { return LParenLoc; } 3875 SourceLocation getRParenLoc() const { return RParenLoc; } 3876 3877 SourceRange getSourceRange() const { 3878 return SourceRange(LParenLoc, RParenLoc); 3879 } 3880 static bool classof(const Stmt *T) { 3881 return T->getStmtClass() == ParenListExprClass; 3882 } 3883 static bool classof(const ParenListExpr *) { return true; } 3884 3885 // Iterators 3886 child_range children() { 3887 return child_range(&Exprs[0], &Exprs[0]+NumExprs); 3888 } 3889 3890 friend class ASTStmtReader; 3891 friend class ASTStmtWriter; 3892}; 3893 3894 3895/// \brief Represents a C1X generic selection. 3896/// 3897/// A generic selection (C1X 6.5.1.1) contains an unevaluated controlling 3898/// expression, followed by one or more generic associations. Each generic 3899/// association specifies a type name and an expression, or "default" and an 3900/// expression (in which case it is known as a default generic association). 3901/// The type and value of the generic selection are identical to those of its 3902/// result expression, which is defined as the expression in the generic 3903/// association with a type name that is compatible with the type of the 3904/// controlling expression, or the expression in the default generic association 3905/// if no types are compatible. For example: 3906/// 3907/// @code 3908/// _Generic(X, double: 1, float: 2, default: 3) 3909/// @endcode 3910/// 3911/// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f 3912/// or 3 if "hello". 3913/// 3914/// As an extension, generic selections are allowed in C++, where the following 3915/// additional semantics apply: 3916/// 3917/// Any generic selection whose controlling expression is type-dependent or 3918/// which names a dependent type in its association list is result-dependent, 3919/// which means that the choice of result expression is dependent. 3920/// Result-dependent generic associations are both type- and value-dependent. 3921class GenericSelectionExpr : public Expr { 3922 enum { CONTROLLING, END_EXPR }; 3923 TypeSourceInfo **AssocTypes; 3924 Stmt **SubExprs; 3925 unsigned NumAssocs, ResultIndex; 3926 SourceLocation GenericLoc, DefaultLoc, RParenLoc; 3927 3928public: 3929 GenericSelectionExpr(ASTContext &Context, 3930 SourceLocation GenericLoc, Expr *ControllingExpr, 3931 TypeSourceInfo **AssocTypes, Expr **AssocExprs, 3932 unsigned NumAssocs, SourceLocation DefaultLoc, 3933 SourceLocation RParenLoc, 3934 bool ContainsUnexpandedParameterPack, 3935 unsigned ResultIndex); 3936 3937 /// This constructor is used in the result-dependent case. 3938 GenericSelectionExpr(ASTContext &Context, 3939 SourceLocation GenericLoc, Expr *ControllingExpr, 3940 TypeSourceInfo **AssocTypes, Expr **AssocExprs, 3941 unsigned NumAssocs, SourceLocation DefaultLoc, 3942 SourceLocation RParenLoc, 3943 bool ContainsUnexpandedParameterPack); 3944 3945 explicit GenericSelectionExpr(EmptyShell Empty) 3946 : Expr(GenericSelectionExprClass, Empty) { } 3947 3948 unsigned getNumAssocs() const { return NumAssocs; } 3949 3950 SourceLocation getGenericLoc() const { return GenericLoc; } 3951 SourceLocation getDefaultLoc() const { return DefaultLoc; } 3952 SourceLocation getRParenLoc() const { return RParenLoc; } 3953 3954 const Expr *getAssocExpr(unsigned i) const { 3955 return cast<Expr>(SubExprs[END_EXPR+i]); 3956 } 3957 Expr *getAssocExpr(unsigned i) { return cast<Expr>(SubExprs[END_EXPR+i]); } 3958 3959 const TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) const { 3960 return AssocTypes[i]; 3961 } 3962 TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) { return AssocTypes[i]; } 3963 3964 QualType getAssocType(unsigned i) const { 3965 if (const TypeSourceInfo *TS = getAssocTypeSourceInfo(i)) 3966 return TS->getType(); 3967 else 3968 return QualType(); 3969 } 3970 3971 const Expr *getControllingExpr() const { 3972 return cast<Expr>(SubExprs[CONTROLLING]); 3973 } 3974 Expr *getControllingExpr() { return cast<Expr>(SubExprs[CONTROLLING]); } 3975 3976 /// Whether this generic selection is result-dependent. 3977 bool isResultDependent() const { return ResultIndex == -1U; } 3978 3979 /// The zero-based index of the result expression's generic association in 3980 /// the generic selection's association list. Defined only if the 3981 /// generic selection is not result-dependent. 3982 unsigned getResultIndex() const { 3983 assert(!isResultDependent() && "Generic selection is result-dependent"); 3984 return ResultIndex; 3985 } 3986 3987 /// The generic selection's result expression. Defined only if the 3988 /// generic selection is not result-dependent. 3989 const Expr *getResultExpr() const { return getAssocExpr(getResultIndex()); } 3990 Expr *getResultExpr() { return getAssocExpr(getResultIndex()); } 3991 3992 SourceRange getSourceRange() const { 3993 return SourceRange(GenericLoc, RParenLoc); 3994 } 3995 static bool classof(const Stmt *T) { 3996 return T->getStmtClass() == GenericSelectionExprClass; 3997 } 3998 static bool classof(const GenericSelectionExpr *) { return true; } 3999 4000 child_range children() { 4001 return child_range(SubExprs, SubExprs+END_EXPR+NumAssocs); 4002 } 4003 4004 friend class ASTStmtReader; 4005}; 4006 4007//===----------------------------------------------------------------------===// 4008// Clang Extensions 4009//===----------------------------------------------------------------------===// 4010 4011 4012/// ExtVectorElementExpr - This represents access to specific elements of a 4013/// vector, and may occur on the left hand side or right hand side. For example 4014/// the following is legal: "V.xy = V.zw" if V is a 4 element extended vector. 4015/// 4016/// Note that the base may have either vector or pointer to vector type, just 4017/// like a struct field reference. 4018/// 4019class ExtVectorElementExpr : public Expr { 4020 Stmt *Base; 4021 IdentifierInfo *Accessor; 4022 SourceLocation AccessorLoc; 4023public: 4024 ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base, 4025 IdentifierInfo &accessor, SourceLocation loc) 4026 : Expr(ExtVectorElementExprClass, ty, VK, 4027 (VK == VK_RValue ? OK_Ordinary : OK_VectorComponent), 4028 base->isTypeDependent(), base->isValueDependent(), 4029 base->isInstantiationDependent(), 4030 base->containsUnexpandedParameterPack()), 4031 Base(base), Accessor(&accessor), AccessorLoc(loc) {} 4032 4033 /// \brief Build an empty vector element expression. 4034 explicit ExtVectorElementExpr(EmptyShell Empty) 4035 : Expr(ExtVectorElementExprClass, Empty) { } 4036 4037 const Expr *getBase() const { return cast<Expr>(Base); } 4038 Expr *getBase() { return cast<Expr>(Base); } 4039 void setBase(Expr *E) { Base = E; } 4040 4041 IdentifierInfo &getAccessor() const { return *Accessor; } 4042 void setAccessor(IdentifierInfo *II) { Accessor = II; } 4043 4044 SourceLocation getAccessorLoc() const { return AccessorLoc; } 4045 void setAccessorLoc(SourceLocation L) { AccessorLoc = L; } 4046 4047 /// getNumElements - Get the number of components being selected. 4048 unsigned getNumElements() const; 4049 4050 /// containsDuplicateElements - Return true if any element access is 4051 /// repeated. 4052 bool containsDuplicateElements() const; 4053 4054 /// getEncodedElementAccess - Encode the elements accessed into an llvm 4055 /// aggregate Constant of ConstantInt(s). 4056 void getEncodedElementAccess(SmallVectorImpl<unsigned> &Elts) const; 4057 4058 SourceRange getSourceRange() const { 4059 return SourceRange(getBase()->getLocStart(), AccessorLoc); 4060 } 4061 4062 /// isArrow - Return true if the base expression is a pointer to vector, 4063 /// return false if the base expression is a vector. 4064 bool isArrow() const; 4065 4066 static bool classof(const Stmt *T) { 4067 return T->getStmtClass() == ExtVectorElementExprClass; 4068 } 4069 static bool classof(const ExtVectorElementExpr *) { return true; } 4070 4071 // Iterators 4072 child_range children() { return child_range(&Base, &Base+1); } 4073}; 4074 4075 4076/// BlockExpr - Adaptor class for mixing a BlockDecl with expressions. 4077/// ^{ statement-body } or ^(int arg1, float arg2){ statement-body } 4078class BlockExpr : public Expr { 4079protected: 4080 BlockDecl *TheBlock; 4081public: 4082 BlockExpr(BlockDecl *BD, QualType ty) 4083 : Expr(BlockExprClass, ty, VK_RValue, OK_Ordinary, 4084 ty->isDependentType(), false, 4085 // FIXME: Check for instantiate-dependence in the statement? 4086 ty->isInstantiationDependentType(), 4087 false), 4088 TheBlock(BD) {} 4089 4090 /// \brief Build an empty block expression. 4091 explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { } 4092 4093 const BlockDecl *getBlockDecl() const { return TheBlock; } 4094 BlockDecl *getBlockDecl() { return TheBlock; } 4095 void setBlockDecl(BlockDecl *BD) { TheBlock = BD; } 4096 4097 // Convenience functions for probing the underlying BlockDecl. 4098 SourceLocation getCaretLocation() const; 4099 const Stmt *getBody() const; 4100 Stmt *getBody(); 4101 4102 SourceRange getSourceRange() const { 4103 return SourceRange(getCaretLocation(), getBody()->getLocEnd()); 4104 } 4105 4106 /// getFunctionType - Return the underlying function type for this block. 4107 const FunctionType *getFunctionType() const; 4108 4109 static bool classof(const Stmt *T) { 4110 return T->getStmtClass() == BlockExprClass; 4111 } 4112 static bool classof(const BlockExpr *) { return true; } 4113 4114 // Iterators 4115 child_range children() { return child_range(); } 4116}; 4117 4118/// BlockDeclRefExpr - A reference to a local variable declared in an 4119/// enclosing scope. 4120class BlockDeclRefExpr : public Expr { 4121 VarDecl *D; 4122 SourceLocation Loc; 4123 bool IsByRef : 1; 4124 bool ConstQualAdded : 1; 4125public: 4126 BlockDeclRefExpr(VarDecl *d, QualType t, ExprValueKind VK, 4127 SourceLocation l, bool ByRef, bool constAdded = false); 4128 4129 // \brief Build an empty reference to a declared variable in a 4130 // block. 4131 explicit BlockDeclRefExpr(EmptyShell Empty) 4132 : Expr(BlockDeclRefExprClass, Empty) { } 4133 4134 VarDecl *getDecl() { return D; } 4135 const VarDecl *getDecl() const { return D; } 4136 void setDecl(VarDecl *VD) { D = VD; } 4137 4138 SourceLocation getLocation() const { return Loc; } 4139 void setLocation(SourceLocation L) { Loc = L; } 4140 4141 SourceRange getSourceRange() const { return SourceRange(Loc); } 4142 4143 bool isByRef() const { return IsByRef; } 4144 void setByRef(bool BR) { IsByRef = BR; } 4145 4146 bool isConstQualAdded() const { return ConstQualAdded; } 4147 void setConstQualAdded(bool C) { ConstQualAdded = C; } 4148 4149 static bool classof(const Stmt *T) { 4150 return T->getStmtClass() == BlockDeclRefExprClass; 4151 } 4152 static bool classof(const BlockDeclRefExpr *) { return true; } 4153 4154 // Iterators 4155 child_range children() { return child_range(); } 4156}; 4157 4158/// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2] 4159/// This AST node provides support for reinterpreting a type to another 4160/// type of the same size. 4161class AsTypeExpr : public Expr { // Should this be an ExplicitCastExpr? 4162private: 4163 Stmt *SrcExpr; 4164 SourceLocation BuiltinLoc, RParenLoc; 4165 4166 friend class ASTReader; 4167 friend class ASTStmtReader; 4168 explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {} 4169 4170public: 4171 AsTypeExpr(Expr* SrcExpr, QualType DstType, 4172 ExprValueKind VK, ExprObjectKind OK, 4173 SourceLocation BuiltinLoc, SourceLocation RParenLoc) 4174 : Expr(AsTypeExprClass, DstType, VK, OK, 4175 DstType->isDependentType(), 4176 DstType->isDependentType() || SrcExpr->isValueDependent(), 4177 (DstType->isInstantiationDependentType() || 4178 SrcExpr->isInstantiationDependent()), 4179 (DstType->containsUnexpandedParameterPack() || 4180 SrcExpr->containsUnexpandedParameterPack())), 4181 SrcExpr(SrcExpr), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {} 4182 4183 /// getSrcExpr - Return the Expr to be converted. 4184 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); } 4185 4186 /// getBuiltinLoc - Return the location of the __builtin_astype token. 4187 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 4188 4189 /// getRParenLoc - Return the location of final right parenthesis. 4190 SourceLocation getRParenLoc() const { return RParenLoc; } 4191 4192 SourceRange getSourceRange() const { 4193 return SourceRange(BuiltinLoc, RParenLoc); 4194 } 4195 4196 static bool classof(const Stmt *T) { 4197 return T->getStmtClass() == AsTypeExprClass; 4198 } 4199 static bool classof(const AsTypeExpr *) { return true; } 4200 4201 // Iterators 4202 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); } 4203}; 4204 4205/// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, 4206/// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the 4207/// similarly-named C++0x instructions. All of these instructions take one 4208/// primary pointer and at least one memory order. 4209class AtomicExpr : public Expr { 4210public: 4211 enum AtomicOp { Load, Store, CmpXchgStrong, CmpXchgWeak, Xchg, 4212 Add, Sub, And, Or, Xor }; 4213private: 4214 enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, END_EXPR }; 4215 Stmt* SubExprs[END_EXPR]; 4216 unsigned NumSubExprs; 4217 SourceLocation BuiltinLoc, RParenLoc; 4218 AtomicOp Op; 4219 4220public: 4221 AtomicExpr(SourceLocation BLoc, Expr **args, unsigned nexpr, QualType t, 4222 AtomicOp op, SourceLocation RP); 4223 4224 /// \brief Build an empty AtomicExpr. 4225 explicit AtomicExpr(EmptyShell Empty) : Expr(AtomicExprClass, Empty) { } 4226 4227 Expr *getPtr() const { 4228 return cast<Expr>(SubExprs[PTR]); 4229 } 4230 void setPtr(Expr *E) { 4231 SubExprs[PTR] = E; 4232 } 4233 Expr *getOrder() const { 4234 return cast<Expr>(SubExprs[ORDER]); 4235 } 4236 void setOrder(Expr *E) { 4237 SubExprs[ORDER] = E; 4238 } 4239 Expr *getVal1() const { 4240 assert(NumSubExprs >= 3); 4241 return cast<Expr>(SubExprs[VAL1]); 4242 } 4243 void setVal1(Expr *E) { 4244 assert(NumSubExprs >= 3); 4245 SubExprs[VAL1] = E; 4246 } 4247 Expr *getOrderFail() const { 4248 assert(NumSubExprs == 5); 4249 return cast<Expr>(SubExprs[ORDER_FAIL]); 4250 } 4251 void setOrderFail(Expr *E) { 4252 assert(NumSubExprs == 5); 4253 SubExprs[ORDER_FAIL] = E; 4254 } 4255 Expr *getVal2() const { 4256 assert(NumSubExprs == 5); 4257 return cast<Expr>(SubExprs[VAL2]); 4258 } 4259 void setVal2(Expr *E) { 4260 assert(NumSubExprs == 5); 4261 SubExprs[VAL2] = E; 4262 } 4263 4264 AtomicOp getOp() const { return Op; } 4265 void setOp(AtomicOp op) { Op = op; } 4266 unsigned getNumSubExprs() { return NumSubExprs; } 4267 void setNumSubExprs(unsigned num) { NumSubExprs = num; } 4268 4269 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); } 4270 4271 bool isVolatile() const { 4272 return getPtr()->getType()->getPointeeType().isVolatileQualified(); 4273 } 4274 4275 bool isCmpXChg() const { 4276 return getOp() == AtomicExpr::CmpXchgStrong || 4277 getOp() == AtomicExpr::CmpXchgWeak; 4278 } 4279 4280 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 4281 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; } 4282 4283 SourceLocation getRParenLoc() const { return RParenLoc; } 4284 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 4285 4286 SourceRange getSourceRange() const { 4287 return SourceRange(BuiltinLoc, RParenLoc); 4288 } 4289 static bool classof(const Stmt *T) { 4290 return T->getStmtClass() == AtomicExprClass; 4291 } 4292 static bool classof(const AtomicExpr *) { return true; } 4293 4294 // Iterators 4295 child_range children() { 4296 return child_range(SubExprs, SubExprs+NumSubExprs); 4297 } 4298}; 4299} // end namespace clang 4300 4301#endif 4302