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