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