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