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