Expr.h revision bc736fceca6f0bca31d16003a7587857190408fb
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 "llvm/ADT/APSInt.h" 21#include "llvm/ADT/APFloat.h" 22#include "llvm/ADT/SmallVector.h" 23#include <vector> 24 25namespace clang { 26 class ASTContext; 27 class APValue; 28 class Decl; 29 class IdentifierInfo; 30 class ParmVarDecl; 31 class NamedDecl; 32 class ValueDecl; 33 class BlockDecl; 34 class CXXOperatorCallExpr; 35 class CXXMemberCallExpr; 36 37/// Expr - This represents one expression. Note that Expr's are subclasses of 38/// Stmt. This allows an expression to be transparently used any place a Stmt 39/// is required. 40/// 41class Expr : public Stmt { 42 QualType TR; 43 44 /// TypeDependent - Whether this expression is type-dependent 45 /// (C++ [temp.dep.expr]). 46 bool TypeDependent : 1; 47 48 /// ValueDependent - Whether this expression is value-dependent 49 /// (C++ [temp.dep.constexpr]). 50 bool ValueDependent : 1; 51 52protected: 53 // FIXME: Eventually, this constructor should go away and we should 54 // require every subclass to provide type/value-dependence 55 // information. 56 Expr(StmtClass SC, QualType T) 57 : Stmt(SC), TypeDependent(false), ValueDependent(false) { 58 setType(T); 59 } 60 61 Expr(StmtClass SC, QualType T, bool TD, bool VD) 62 : Stmt(SC), TypeDependent(TD), ValueDependent(VD) { 63 setType(T); 64 } 65 66public: 67 QualType getType() const { return TR; } 68 void setType(QualType t) { 69 // In C++, the type of an expression is always adjusted so that it 70 // will not have reference type an expression will never have 71 // reference type (C++ [expr]p6). Use 72 // QualType::getNonReferenceType() to retrieve the non-reference 73 // type. Additionally, inspect Expr::isLvalue to determine whether 74 // an expression that is adjusted in this manner should be 75 // considered an lvalue. 76 assert((TR.isNull() || !TR->isReferenceType()) && 77 "Expressions can't have reference type"); 78 79 TR = t; 80 } 81 82 /// isValueDependent - Determines whether this expression is 83 /// value-dependent (C++ [temp.dep.constexpr]). For example, the 84 /// array bound of "Chars" in the following example is 85 /// value-dependent. 86 /// @code 87 /// template<int Size, char (&Chars)[Size]> struct meta_string; 88 /// @endcode 89 bool isValueDependent() const { return ValueDependent; } 90 91 /// isTypeDependent - Determines whether this expression is 92 /// type-dependent (C++ [temp.dep.expr]), which means that its type 93 /// could change from one template instantiation to the next. For 94 /// example, the expressions "x" and "x + y" are type-dependent in 95 /// the following code, but "y" is not type-dependent: 96 /// @code 97 /// template<typename T> 98 /// void add(T x, int y) { 99 /// x + y; 100 /// } 101 /// @endcode 102 bool isTypeDependent() const { return TypeDependent; } 103 104 /// SourceLocation tokens are not useful in isolation - they are low level 105 /// value objects created/interpreted by SourceManager. We assume AST 106 /// clients will have a pointer to the respective SourceManager. 107 virtual SourceRange getSourceRange() const = 0; 108 109 /// getExprLoc - Return the preferred location for the arrow when diagnosing 110 /// a problem with a generic expression. 111 virtual SourceLocation getExprLoc() const { return getLocStart(); } 112 113 /// isUnusedResultAWarning - Return true if this immediate expression should 114 /// be warned about if the result is unused. If so, fill in Loc and Ranges 115 /// with location to warn on and the source range[s] to report with the 116 /// warning. 117 bool isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1, 118 SourceRange &R2) const; 119 120 /// isLvalue - C99 6.3.2.1: an lvalue is an expression with an object type or 121 /// incomplete type other than void. Nonarray expressions that can be lvalues: 122 /// - name, where name must be a variable 123 /// - e[i] 124 /// - (e), where e must be an lvalue 125 /// - e.name, where e must be an lvalue 126 /// - e->name 127 /// - *e, the type of e cannot be a function type 128 /// - string-constant 129 /// - reference type [C++ [expr]] 130 /// 131 enum isLvalueResult { 132 LV_Valid, 133 LV_NotObjectType, 134 LV_IncompleteVoidType, 135 LV_DuplicateVectorComponents, 136 LV_InvalidExpression, 137 LV_MemberFunction 138 }; 139 isLvalueResult isLvalue(ASTContext &Ctx) const; 140 141 /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type, 142 /// does not have an incomplete type, does not have a const-qualified type, 143 /// and if it is a structure or union, does not have any member (including, 144 /// recursively, any member or element of all contained aggregates or unions) 145 /// with a const-qualified type. 146 enum isModifiableLvalueResult { 147 MLV_Valid, 148 MLV_NotObjectType, 149 MLV_IncompleteVoidType, 150 MLV_DuplicateVectorComponents, 151 MLV_InvalidExpression, 152 MLV_LValueCast, // Specialized form of MLV_InvalidExpression. 153 MLV_IncompleteType, 154 MLV_ConstQualified, 155 MLV_ArrayType, 156 MLV_NotBlockQualified, 157 MLV_ReadonlyProperty, 158 MLV_NoSetterProperty, 159 MLV_MemberFunction 160 }; 161 isModifiableLvalueResult isModifiableLvalue(ASTContext &Ctx) const; 162 163 bool isBitField(); 164 165 /// getIntegerConstantExprValue() - Return the value of an integer 166 /// constant expression. The expression must be a valid integer 167 /// constant expression as determined by isIntegerConstantExpr. 168 llvm::APSInt getIntegerConstantExprValue(ASTContext &Ctx) const { 169 llvm::APSInt X; 170 bool success = isIntegerConstantExpr(X, Ctx); 171 success = success; 172 assert(success && "Illegal argument to getIntegerConstantExpr"); 173 return X; 174 } 175 176 /// isIntegerConstantExpr - Return true if this expression is a valid integer 177 /// constant expression, and, if so, return its value in Result. If not a 178 /// valid i-c-e, return false and fill in Loc (if specified) with the location 179 /// of the invalid expression. 180 bool isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx, 181 SourceLocation *Loc = 0, 182 bool isEvaluated = true) const; 183 bool isIntegerConstantExprInternal(llvm::APSInt &Result, ASTContext &Ctx, 184 SourceLocation *Loc = 0, 185 bool isEvaluated = true) const; 186 bool isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc = 0) const { 187 llvm::APSInt X; 188 return isIntegerConstantExpr(X, Ctx, Loc); 189 } 190 /// isConstantInitializer - Returns true if this expression is a constant 191 /// initializer, which can be emitted at compile-time. 192 bool isConstantInitializer(ASTContext &Ctx) const; 193 194 /// EvalResult is a struct with detailed info about an evaluated expression. 195 struct EvalResult { 196 /// Val - This is the value the expression can be folded to. 197 APValue Val; 198 199 /// HasSideEffects - Whether the evaluated expression has side effects. 200 /// For example, (f() && 0) can be folded, but it still has side effects. 201 bool HasSideEffects; 202 203 /// Diag - If the expression is unfoldable, then Diag contains a note 204 /// diagnostic indicating why it's not foldable. DiagLoc indicates a caret 205 /// position for the error, and DiagExpr is the expression that caused 206 /// the error. 207 /// If the expression is foldable, but not an integer constant expression, 208 /// Diag contains a note diagnostic that describes why it isn't an integer 209 /// constant expression. If the expression *is* an integer constant 210 /// expression, then Diag will be zero. 211 unsigned Diag; 212 const Expr *DiagExpr; 213 SourceLocation DiagLoc; 214 215 EvalResult() : HasSideEffects(false), Diag(0), DiagExpr(0) {} 216 }; 217 218 /// Evaluate - Return true if this is a constant which we can fold using 219 /// any crazy technique (that has nothing to do with language standards) that 220 /// we want to. If this function returns true, it returns the folded constant 221 /// in Result. 222 bool Evaluate(EvalResult &Result, ASTContext &Ctx) const; 223 224 /// isEvaluatable - Call Evaluate to see if this expression can be constant 225 /// folded, but discard the result. 226 bool isEvaluatable(ASTContext &Ctx) const; 227 228 /// EvaluateAsInt - Call Evaluate and return the folded integer. This 229 /// must be called on an expression that constant folds to an integer. 230 llvm::APSInt EvaluateAsInt(ASTContext &Ctx) const; 231 232 /// isNullPointerConstant - C99 6.3.2.3p3 - Return true if this is either an 233 /// integer constant expression with the value zero, or if this is one that is 234 /// cast to void*. 235 bool isNullPointerConstant(ASTContext &Ctx) const; 236 237 /// hasGlobalStorage - Return true if this expression has static storage 238 /// duration. This means that the address of this expression is a link-time 239 /// constant. 240 bool hasGlobalStorage() const; 241 242 /// isOBJCGCCandidate - Return true if this expression may be used in a read/ 243 /// write barrier. 244 bool isOBJCGCCandidate() const; 245 246 /// IgnoreParens - Ignore parentheses. If this Expr is a ParenExpr, return 247 /// its subexpression. If that subexpression is also a ParenExpr, 248 /// then this method recursively returns its subexpression, and so forth. 249 /// Otherwise, the method returns the current Expr. 250 Expr* IgnoreParens(); 251 252 /// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr 253 /// or CastExprs, returning their operand. 254 Expr *IgnoreParenCasts(); 255 256 /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the 257 /// value (including ptr->int casts of the same size). Strip off any 258 /// ParenExpr or CastExprs, returning their operand. 259 Expr *IgnoreParenNoopCasts(ASTContext &Ctx); 260 261 const Expr* IgnoreParens() const { 262 return const_cast<Expr*>(this)->IgnoreParens(); 263 } 264 const Expr *IgnoreParenCasts() const { 265 return const_cast<Expr*>(this)->IgnoreParenCasts(); 266 } 267 const Expr *IgnoreParenNoopCasts(ASTContext &Ctx) const { 268 return const_cast<Expr*>(this)->IgnoreParenNoopCasts(Ctx); 269 } 270 271 static bool hasAnyTypeDependentArguments(Expr** Exprs, unsigned NumExprs); 272 static bool hasAnyValueDependentArguments(Expr** Exprs, unsigned NumExprs); 273 274 static bool classof(const Stmt *T) { 275 return T->getStmtClass() >= firstExprConstant && 276 T->getStmtClass() <= lastExprConstant; 277 } 278 static bool classof(const Expr *) { return true; } 279 280 static inline Expr* Create(llvm::Deserializer& D, ASTContext& C) { 281 return cast<Expr>(Stmt::Create(D, C)); 282 } 283}; 284 285 286//===----------------------------------------------------------------------===// 287// Primary Expressions. 288//===----------------------------------------------------------------------===// 289 290/// DeclRefExpr - [C99 6.5.1p2] - A reference to a declared variable, function, 291/// enum, etc. 292class DeclRefExpr : public Expr { 293 NamedDecl *D; 294 SourceLocation Loc; 295 296protected: 297 // FIXME: Eventually, this constructor will go away and all subclasses 298 // will have to provide the type- and value-dependent flags. 299 DeclRefExpr(StmtClass SC, NamedDecl *d, QualType t, SourceLocation l) : 300 Expr(SC, t), D(d), Loc(l) {} 301 302 DeclRefExpr(StmtClass SC, NamedDecl *d, QualType t, SourceLocation l, bool TD, 303 bool VD) : 304 Expr(SC, t, TD, VD), D(d), Loc(l) {} 305 306public: 307 // FIXME: Eventually, this constructor will go away and all clients 308 // will have to provide the type- and value-dependent flags. 309 DeclRefExpr(NamedDecl *d, QualType t, SourceLocation l) : 310 Expr(DeclRefExprClass, t), D(d), Loc(l) {} 311 312 DeclRefExpr(NamedDecl *d, QualType t, SourceLocation l, bool TD, bool VD) : 313 Expr(DeclRefExprClass, t, TD, VD), D(d), Loc(l) {} 314 315 NamedDecl *getDecl() { return D; } 316 const NamedDecl *getDecl() const { return D; } 317 void setDecl(NamedDecl *NewD) { D = NewD; } 318 319 SourceLocation getLocation() const { return Loc; } 320 virtual SourceRange getSourceRange() const { return SourceRange(Loc); } 321 322 static bool classof(const Stmt *T) { 323 return T->getStmtClass() == DeclRefExprClass || 324 T->getStmtClass() == CXXConditionDeclExprClass || 325 T->getStmtClass() == QualifiedDeclRefExprClass; 326 } 327 static bool classof(const DeclRefExpr *) { return true; } 328 329 // Iterators 330 virtual child_iterator child_begin(); 331 virtual child_iterator child_end(); 332 333 virtual void EmitImpl(llvm::Serializer& S) const; 334 static DeclRefExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C); 335}; 336 337/// PredefinedExpr - [C99 6.4.2.2] - A predefined identifier such as __func__. 338class PredefinedExpr : public Expr { 339public: 340 enum IdentType { 341 Func, 342 Function, 343 PrettyFunction 344 }; 345 346private: 347 SourceLocation Loc; 348 IdentType Type; 349public: 350 PredefinedExpr(SourceLocation l, QualType type, IdentType IT) 351 : Expr(PredefinedExprClass, type), Loc(l), Type(IT) {} 352 353 IdentType getIdentType() const { return Type; } 354 355 virtual SourceRange getSourceRange() const { return SourceRange(Loc); } 356 357 static bool classof(const Stmt *T) { 358 return T->getStmtClass() == PredefinedExprClass; 359 } 360 static bool classof(const PredefinedExpr *) { return true; } 361 362 // Iterators 363 virtual child_iterator child_begin(); 364 virtual child_iterator child_end(); 365 366 virtual void EmitImpl(llvm::Serializer& S) const; 367 static PredefinedExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C); 368}; 369 370class IntegerLiteral : public Expr { 371 llvm::APInt Value; 372 SourceLocation Loc; 373public: 374 // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy, 375 // or UnsignedLongLongTy 376 IntegerLiteral(const llvm::APInt &V, QualType type, SourceLocation l) 377 : Expr(IntegerLiteralClass, type), Value(V), Loc(l) { 378 assert(type->isIntegerType() && "Illegal type in IntegerLiteral"); 379 } 380 const llvm::APInt &getValue() const { return Value; } 381 virtual SourceRange getSourceRange() const { return SourceRange(Loc); } 382 383 /// \brief Retrieve the location of the literal. 384 SourceLocation getLocation() const { return Loc; } 385 386 static bool classof(const Stmt *T) { 387 return T->getStmtClass() == IntegerLiteralClass; 388 } 389 static bool classof(const IntegerLiteral *) { return true; } 390 391 // Iterators 392 virtual child_iterator child_begin(); 393 virtual child_iterator child_end(); 394 395 virtual void EmitImpl(llvm::Serializer& S) const; 396 static IntegerLiteral* CreateImpl(llvm::Deserializer& D, ASTContext& C); 397}; 398 399class CharacterLiteral : public Expr { 400 unsigned Value; 401 SourceLocation Loc; 402 bool IsWide; 403public: 404 // type should be IntTy 405 CharacterLiteral(unsigned value, bool iswide, QualType type, SourceLocation l) 406 : Expr(CharacterLiteralClass, type), Value(value), Loc(l), IsWide(iswide) { 407 } 408 SourceLocation getLoc() const { return Loc; } 409 bool isWide() const { return IsWide; } 410 411 virtual SourceRange getSourceRange() const { return SourceRange(Loc); } 412 413 unsigned getValue() const { return Value; } 414 415 static bool classof(const Stmt *T) { 416 return T->getStmtClass() == CharacterLiteralClass; 417 } 418 static bool classof(const CharacterLiteral *) { return true; } 419 420 // Iterators 421 virtual child_iterator child_begin(); 422 virtual child_iterator child_end(); 423 424 virtual void EmitImpl(llvm::Serializer& S) const; 425 static CharacterLiteral* CreateImpl(llvm::Deserializer& D, ASTContext& C); 426}; 427 428class FloatingLiteral : public Expr { 429 llvm::APFloat Value; 430 bool IsExact : 1; 431 SourceLocation Loc; 432public: 433 FloatingLiteral(const llvm::APFloat &V, bool* isexact, 434 QualType Type, SourceLocation L) 435 : Expr(FloatingLiteralClass, Type), Value(V), IsExact(*isexact), Loc(L) {} 436 437 const llvm::APFloat &getValue() const { return Value; } 438 439 bool isExact() const { return IsExact; } 440 441 /// getValueAsApproximateDouble - This returns the value as an inaccurate 442 /// double. Note that this may cause loss of precision, but is useful for 443 /// debugging dumps, etc. 444 double getValueAsApproximateDouble() const; 445 446 virtual SourceRange getSourceRange() const { return SourceRange(Loc); } 447 448 static bool classof(const Stmt *T) { 449 return T->getStmtClass() == FloatingLiteralClass; 450 } 451 static bool classof(const FloatingLiteral *) { return true; } 452 453 // Iterators 454 virtual child_iterator child_begin(); 455 virtual child_iterator child_end(); 456 457 virtual void EmitImpl(llvm::Serializer& S) const; 458 static FloatingLiteral* CreateImpl(llvm::Deserializer& D, ASTContext& C); 459}; 460 461/// ImaginaryLiteral - We support imaginary integer and floating point literals, 462/// like "1.0i". We represent these as a wrapper around FloatingLiteral and 463/// IntegerLiteral classes. Instances of this class always have a Complex type 464/// whose element type matches the subexpression. 465/// 466class ImaginaryLiteral : public Expr { 467 Stmt *Val; 468public: 469 ImaginaryLiteral(Expr *val, QualType Ty) 470 : Expr(ImaginaryLiteralClass, Ty), Val(val) {} 471 472 const Expr *getSubExpr() const { return cast<Expr>(Val); } 473 Expr *getSubExpr() { return cast<Expr>(Val); } 474 475 virtual SourceRange getSourceRange() const { return Val->getSourceRange(); } 476 static bool classof(const Stmt *T) { 477 return T->getStmtClass() == ImaginaryLiteralClass; 478 } 479 static bool classof(const ImaginaryLiteral *) { return true; } 480 481 // Iterators 482 virtual child_iterator child_begin(); 483 virtual child_iterator child_end(); 484 485 virtual void EmitImpl(llvm::Serializer& S) const; 486 static ImaginaryLiteral* CreateImpl(llvm::Deserializer& D, ASTContext& C); 487}; 488 489/// StringLiteral - This represents a string literal expression, e.g. "foo" 490/// or L"bar" (wide strings). The actual string is returned by getStrData() 491/// is NOT null-terminated, and the length of the string is determined by 492/// calling getByteLength(). The C type for a string is always a 493/// ConstantArrayType. In C++, the char type is const qualified, in C it is 494/// not. 495/// 496/// Note that strings in C can be formed by concatenation of multiple string 497/// literal pptokens in translation phase #6. This keeps track of the locations 498/// of each of these pieces. 499/// 500/// Strings in C can also be truncated and extended by assigning into arrays, 501/// e.g. with constructs like: 502/// char X[2] = "foobar"; 503/// In this case, getByteLength() will return 6, but the string literal will 504/// have type "char[2]". 505class StringLiteral : public Expr { 506 const char *StrData; 507 unsigned ByteLength; 508 bool IsWide; 509 unsigned NumConcatenated; 510 SourceLocation TokLocs[1]; 511 512 StringLiteral(QualType Ty) : Expr(StringLiteralClass, Ty) {} 513public: 514 /// This is the "fully general" constructor that allows representation of 515 /// strings formed from multiple concatenated tokens. 516 static StringLiteral *Create(ASTContext &C, const char *StrData, 517 unsigned ByteLength, bool Wide, QualType Ty, 518 SourceLocation *Loc, unsigned NumStrs); 519 520 /// Simple constructor for string literals made from one token. 521 static StringLiteral *Create(ASTContext &C, const char *StrData, 522 unsigned ByteLength, 523 bool Wide, QualType Ty, SourceLocation Loc) { 524 return Create(C, StrData, ByteLength, Wide, Ty, &Loc, 1); 525 } 526 527 void Destroy(ASTContext &C); 528 529 const char *getStrData() const { return StrData; } 530 unsigned getByteLength() const { return ByteLength; } 531 bool isWide() const { return IsWide; } 532 533 /// getNumConcatenated - Get the number of string literal tokens that were 534 /// concatenated in translation phase #6 to form this string literal. 535 unsigned getNumConcatenated() const { return NumConcatenated; } 536 537 SourceLocation getStrTokenLoc(unsigned TokNum) const { 538 assert(TokNum < NumConcatenated && "Invalid tok number"); 539 return TokLocs[TokNum]; 540 } 541 542 typedef const SourceLocation *tokloc_iterator; 543 tokloc_iterator tokloc_begin() const { return TokLocs; } 544 tokloc_iterator tokloc_end() const { return TokLocs+NumConcatenated; } 545 546 virtual SourceRange getSourceRange() const { 547 return SourceRange(TokLocs[0], TokLocs[NumConcatenated-1]); 548 } 549 static bool classof(const Stmt *T) { 550 return T->getStmtClass() == StringLiteralClass; 551 } 552 static bool classof(const StringLiteral *) { return true; } 553 554 // Iterators 555 virtual child_iterator child_begin(); 556 virtual child_iterator child_end(); 557 558 virtual void EmitImpl(llvm::Serializer& S) const; 559 static StringLiteral* CreateImpl(llvm::Deserializer& D, ASTContext& C); 560}; 561 562/// ParenExpr - This represents a parethesized expression, e.g. "(1)". This 563/// AST node is only formed if full location information is requested. 564class ParenExpr : public Expr { 565 SourceLocation L, R; 566 Stmt *Val; 567public: 568 ParenExpr(SourceLocation l, SourceLocation r, Expr *val) 569 : Expr(ParenExprClass, val->getType(), 570 val->isTypeDependent(), val->isValueDependent()), 571 L(l), R(r), Val(val) {} 572 573 const Expr *getSubExpr() const { return cast<Expr>(Val); } 574 Expr *getSubExpr() { return cast<Expr>(Val); } 575 virtual SourceRange getSourceRange() const { return SourceRange(L, R); } 576 577 /// \brief Get the location of the left parentheses '('. 578 SourceLocation getLParen() const { return L; } 579 580 /// \brief Get the location of the right parentheses ')'. 581 SourceLocation getRParen() const { return R; } 582 583 static bool classof(const Stmt *T) { 584 return T->getStmtClass() == ParenExprClass; 585 } 586 static bool classof(const ParenExpr *) { return true; } 587 588 // Iterators 589 virtual child_iterator child_begin(); 590 virtual child_iterator child_end(); 591 592 virtual void EmitImpl(llvm::Serializer& S) const; 593 static ParenExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C); 594}; 595 596 597/// UnaryOperator - This represents the unary-expression's (except sizeof and 598/// alignof), the postinc/postdec operators from postfix-expression, and various 599/// extensions. 600/// 601/// Notes on various nodes: 602/// 603/// Real/Imag - These return the real/imag part of a complex operand. If 604/// applied to a non-complex value, the former returns its operand and the 605/// later returns zero in the type of the operand. 606/// 607/// __builtin_offsetof(type, a.b[10]) is represented as a unary operator whose 608/// subexpression is a compound literal with the various MemberExpr and 609/// ArraySubscriptExpr's applied to it. 610/// 611class UnaryOperator : public Expr { 612public: 613 // Note that additions to this should also update the StmtVisitor class. 614 enum Opcode { 615 PostInc, PostDec, // [C99 6.5.2.4] Postfix increment and decrement operators 616 PreInc, PreDec, // [C99 6.5.3.1] Prefix increment and decrement operators. 617 AddrOf, Deref, // [C99 6.5.3.2] Address and indirection operators. 618 Plus, Minus, // [C99 6.5.3.3] Unary arithmetic operators. 619 Not, LNot, // [C99 6.5.3.3] Unary arithmetic operators. 620 Real, Imag, // "__real expr"/"__imag expr" Extension. 621 Extension, // __extension__ marker. 622 OffsetOf // __builtin_offsetof 623 }; 624private: 625 Stmt *Val; 626 Opcode Opc; 627 SourceLocation Loc; 628public: 629 630 UnaryOperator(Expr *input, Opcode opc, QualType type, SourceLocation l) 631 : Expr(UnaryOperatorClass, type, 632 input->isTypeDependent() && opc != OffsetOf, 633 input->isValueDependent()), 634 Val(input), Opc(opc), Loc(l) {} 635 636 Opcode getOpcode() const { return Opc; } 637 Expr *getSubExpr() const { return cast<Expr>(Val); } 638 639 /// getOperatorLoc - Return the location of the operator. 640 SourceLocation getOperatorLoc() const { return Loc; } 641 642 /// isPostfix - Return true if this is a postfix operation, like x++. 643 static bool isPostfix(Opcode Op) { 644 return Op == PostInc || Op == PostDec; 645 } 646 647 /// isPostfix - Return true if this is a prefix operation, like --x. 648 static bool isPrefix(Opcode Op) { 649 return Op == PreInc || Op == PreDec; 650 } 651 652 bool isPrefix() const { return isPrefix(Opc); } 653 bool isPostfix() const { return isPostfix(Opc); } 654 bool isIncrementOp() const {return Opc==PreInc || Opc==PostInc; } 655 bool isIncrementDecrementOp() const { return Opc>=PostInc && Opc<=PreDec; } 656 bool isOffsetOfOp() const { return Opc == OffsetOf; } 657 static bool isArithmeticOp(Opcode Op) { return Op >= Plus && Op <= LNot; } 658 659 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it 660 /// corresponds to, e.g. "sizeof" or "[pre]++" 661 static const char *getOpcodeStr(Opcode Op); 662 663 /// \brief Retrieve the unary opcode that corresponds to the given 664 /// overloaded operator. 665 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix); 666 667 /// \brief Retrieve the overloaded operator kind that corresponds to 668 /// the given unary opcode. 669 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc); 670 671 virtual SourceRange getSourceRange() const { 672 if (isPostfix()) 673 return SourceRange(Val->getLocStart(), Loc); 674 else 675 return SourceRange(Loc, Val->getLocEnd()); 676 } 677 virtual SourceLocation getExprLoc() const { return Loc; } 678 679 static bool classof(const Stmt *T) { 680 return T->getStmtClass() == UnaryOperatorClass; 681 } 682 static bool classof(const UnaryOperator *) { return true; } 683 684 // Iterators 685 virtual child_iterator child_begin(); 686 virtual child_iterator child_end(); 687 688 virtual void EmitImpl(llvm::Serializer& S) const; 689 static UnaryOperator* CreateImpl(llvm::Deserializer& D, ASTContext& C); 690}; 691 692/// SizeOfAlignOfExpr - [C99 6.5.3.4] - This is for sizeof/alignof, both of 693/// types and expressions. 694class SizeOfAlignOfExpr : public Expr { 695 bool isSizeof : 1; // true if sizeof, false if alignof. 696 bool isType : 1; // true if operand is a type, false if an expression 697 union { 698 void *Ty; 699 Stmt *Ex; 700 } Argument; 701 SourceLocation OpLoc, RParenLoc; 702public: 703 SizeOfAlignOfExpr(bool issizeof, QualType T, 704 QualType resultType, SourceLocation op, 705 SourceLocation rp) : 706 Expr(SizeOfAlignOfExprClass, resultType, 707 false, // Never type-dependent (C++ [temp.dep.expr]p3). 708 // Value-dependent if the argument is type-dependent. 709 T->isDependentType()), 710 isSizeof(issizeof), isType(true), OpLoc(op), RParenLoc(rp) { 711 Argument.Ty = T.getAsOpaquePtr(); 712 } 713 714 SizeOfAlignOfExpr(bool issizeof, Expr *E, 715 QualType resultType, SourceLocation op, 716 SourceLocation rp) : 717 Expr(SizeOfAlignOfExprClass, resultType, 718 false, // Never type-dependent (C++ [temp.dep.expr]p3). 719 // Value-dependent if the argument is type-dependent. 720 E->isTypeDependent()), 721 isSizeof(issizeof), isType(false), OpLoc(op), RParenLoc(rp) { 722 Argument.Ex = E; 723 } 724 725 virtual void Destroy(ASTContext& C); 726 727 bool isSizeOf() const { return isSizeof; } 728 bool isArgumentType() const { return isType; } 729 QualType getArgumentType() const { 730 assert(isArgumentType() && "calling getArgumentType() when arg is expr"); 731 return QualType::getFromOpaquePtr(Argument.Ty); 732 } 733 Expr *getArgumentExpr() { 734 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type"); 735 return static_cast<Expr*>(Argument.Ex); 736 } 737 const Expr *getArgumentExpr() const { 738 return const_cast<SizeOfAlignOfExpr*>(this)->getArgumentExpr(); 739 } 740 741 /// Gets the argument type, or the type of the argument expression, whichever 742 /// is appropriate. 743 QualType getTypeOfArgument() const { 744 return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType(); 745 } 746 747 SourceLocation getOperatorLoc() const { return OpLoc; } 748 749 virtual SourceRange getSourceRange() const { 750 return SourceRange(OpLoc, RParenLoc); 751 } 752 753 static bool classof(const Stmt *T) { 754 return T->getStmtClass() == SizeOfAlignOfExprClass; 755 } 756 static bool classof(const SizeOfAlignOfExpr *) { return true; } 757 758 // Iterators 759 virtual child_iterator child_begin(); 760 virtual child_iterator child_end(); 761 762 virtual void EmitImpl(llvm::Serializer& S) const; 763 static SizeOfAlignOfExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C); 764}; 765 766//===----------------------------------------------------------------------===// 767// Postfix Operators. 768//===----------------------------------------------------------------------===// 769 770/// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting. 771class ArraySubscriptExpr : public Expr { 772 enum { LHS, RHS, END_EXPR=2 }; 773 Stmt* SubExprs[END_EXPR]; 774 SourceLocation RBracketLoc; 775public: 776 ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t, 777 SourceLocation rbracketloc) 778 : Expr(ArraySubscriptExprClass, t, 779 lhs->isTypeDependent() || rhs->isTypeDependent(), 780 lhs->isValueDependent() || rhs->isValueDependent()), 781 RBracketLoc(rbracketloc) { 782 SubExprs[LHS] = lhs; 783 SubExprs[RHS] = rhs; 784 } 785 786 /// An array access can be written A[4] or 4[A] (both are equivalent). 787 /// - getBase() and getIdx() always present the normalized view: A[4]. 788 /// In this case getBase() returns "A" and getIdx() returns "4". 789 /// - getLHS() and getRHS() present the syntactic view. e.g. for 790 /// 4[A] getLHS() returns "4". 791 /// Note: Because vector element access is also written A[4] we must 792 /// predicate the format conversion in getBase and getIdx only on the 793 /// the type of the RHS, as it is possible for the LHS to be a vector of 794 /// integer type 795 Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); } 796 const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } 797 798 Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); } 799 const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } 800 801 Expr *getBase() { 802 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS()); 803 } 804 805 const Expr *getBase() const { 806 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS()); 807 } 808 809 Expr *getIdx() { 810 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS()); 811 } 812 813 const Expr *getIdx() const { 814 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS()); 815 } 816 817 virtual SourceRange getSourceRange() const { 818 return SourceRange(getLHS()->getLocStart(), RBracketLoc); 819 } 820 821 SourceLocation getRBracketLoc() const { return RBracketLoc; } 822 virtual SourceLocation getExprLoc() const { return getBase()->getExprLoc(); } 823 824 static bool classof(const Stmt *T) { 825 return T->getStmtClass() == ArraySubscriptExprClass; 826 } 827 static bool classof(const ArraySubscriptExpr *) { return true; } 828 829 // Iterators 830 virtual child_iterator child_begin(); 831 virtual child_iterator child_end(); 832 833 virtual void EmitImpl(llvm::Serializer& S) const; 834 static ArraySubscriptExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C); 835}; 836 837 838/// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]). 839/// CallExpr itself represents a normal function call, e.g., "f(x, 2)", 840/// while its subclasses may represent alternative syntax that (semantically) 841/// results in a function call. For example, CXXOperatorCallExpr is 842/// a subclass for overloaded operator calls that use operator syntax, e.g., 843/// "str1 + str2" to resolve to a function call. 844class CallExpr : public Expr { 845 enum { FN=0, ARGS_START=1 }; 846 Stmt **SubExprs; 847 unsigned NumArgs; 848 SourceLocation RParenLoc; 849 850 // This version of the ctor is for deserialization. 851 CallExpr(StmtClass SC, Stmt** subexprs, unsigned numargs, QualType t, 852 SourceLocation rparenloc) 853 : Expr(SC,t), SubExprs(subexprs), 854 NumArgs(numargs), RParenLoc(rparenloc) {} 855 856protected: 857 // This version of the constructor is for derived classes. 858 CallExpr(ASTContext& C, StmtClass SC, Expr *fn, Expr **args, unsigned numargs, 859 QualType t, SourceLocation rparenloc); 860 861public: 862 CallExpr(ASTContext& C, Expr *fn, Expr **args, unsigned numargs, QualType t, 863 SourceLocation rparenloc); 864 865 ~CallExpr() {} 866 867 void Destroy(ASTContext& C); 868 869 const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); } 870 Expr *getCallee() { return cast<Expr>(SubExprs[FN]); } 871 void setCallee(Expr *F) { SubExprs[FN] = F; } 872 873 /// getNumArgs - Return the number of actual arguments to this call. 874 /// 875 unsigned getNumArgs() const { return NumArgs; } 876 877 /// getArg - Return the specified argument. 878 Expr *getArg(unsigned Arg) { 879 assert(Arg < NumArgs && "Arg access out of range!"); 880 return cast<Expr>(SubExprs[Arg+ARGS_START]); 881 } 882 const Expr *getArg(unsigned Arg) const { 883 assert(Arg < NumArgs && "Arg access out of range!"); 884 return cast<Expr>(SubExprs[Arg+ARGS_START]); 885 } 886 887 // FIXME: Why is this needed? Why not just create the CallExpr with the 888 // corect number of arguments? It makes the ASTs less brittle. 889 /// setArg - Set the specified argument. 890 void setArg(unsigned Arg, Expr *ArgExpr) { 891 assert(Arg < NumArgs && "Arg access out of range!"); 892 SubExprs[Arg+ARGS_START] = ArgExpr; 893 } 894 895 // FIXME: It would be great to just get rid of this. There is only one 896 // callee of this method, and it probably could be refactored to not use 897 // this method and instead just create a CallExpr with the right number of 898 // arguments. 899 /// setNumArgs - This changes the number of arguments present in this call. 900 /// Any orphaned expressions are deleted by this, and any new operands are set 901 /// to null. 902 void setNumArgs(ASTContext& C, unsigned NumArgs); 903 904 typedef ExprIterator arg_iterator; 905 typedef ConstExprIterator const_arg_iterator; 906 907 arg_iterator arg_begin() { return SubExprs+ARGS_START; } 908 arg_iterator arg_end() { return SubExprs+ARGS_START+getNumArgs(); } 909 const_arg_iterator arg_begin() const { return SubExprs+ARGS_START; } 910 const_arg_iterator arg_end() const { return SubExprs+ARGS_START+getNumArgs();} 911 912 /// getNumCommas - Return the number of commas that must have been present in 913 /// this function call. 914 unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; } 915 916 /// isBuiltinCall - If this is a call to a builtin, return the builtin ID. If 917 /// not, return 0. 918 unsigned isBuiltinCall(ASTContext &Context) const; 919 920 SourceLocation getRParenLoc() const { return RParenLoc; } 921 922 virtual SourceRange getSourceRange() const { 923 return SourceRange(getCallee()->getLocStart(), RParenLoc); 924 } 925 926 static bool classof(const Stmt *T) { 927 return T->getStmtClass() == CallExprClass || 928 T->getStmtClass() == CXXOperatorCallExprClass || 929 T->getStmtClass() == CXXMemberCallExprClass; 930 } 931 static bool classof(const CallExpr *) { return true; } 932 static bool classof(const CXXOperatorCallExpr *) { return true; } 933 static bool classof(const CXXMemberCallExpr *) { return true; } 934 935 // Iterators 936 virtual child_iterator child_begin(); 937 virtual child_iterator child_end(); 938 939 virtual void EmitImpl(llvm::Serializer& S) const; 940 static CallExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C, 941 StmtClass SC); 942}; 943 944/// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F. 945/// 946class MemberExpr : public Expr { 947 /// Base - the expression for the base pointer or structure references. In 948 /// X.F, this is "X". 949 Stmt *Base; 950 951 /// MemberDecl - This is the decl being referenced by the field/member name. 952 /// In X.F, this is the decl referenced by F. 953 NamedDecl *MemberDecl; 954 955 /// MemberLoc - This is the location of the member name. 956 SourceLocation MemberLoc; 957 958 /// IsArrow - True if this is "X->F", false if this is "X.F". 959 bool IsArrow; 960public: 961 MemberExpr(Expr *base, bool isarrow, NamedDecl *memberdecl, SourceLocation l, 962 QualType ty) 963 : Expr(MemberExprClass, ty), 964 Base(base), MemberDecl(memberdecl), MemberLoc(l), IsArrow(isarrow) {} 965 966 void setBase(Expr *E) { Base = E; } 967 Expr *getBase() const { return cast<Expr>(Base); } 968 NamedDecl *getMemberDecl() const { return MemberDecl; } 969 void setMemberDecl(NamedDecl *D) { MemberDecl = D; } 970 bool isArrow() const { return IsArrow; } 971 972 /// getMemberLoc - Return the location of the "member", in X->F, it is the 973 /// location of 'F'. 974 SourceLocation getMemberLoc() const { return MemberLoc; } 975 976 virtual SourceRange getSourceRange() const { 977 return SourceRange(getBase()->getLocStart(), MemberLoc); 978 } 979 980 virtual SourceLocation getExprLoc() const { return MemberLoc; } 981 982 static bool classof(const Stmt *T) { 983 return T->getStmtClass() == MemberExprClass; 984 } 985 static bool classof(const MemberExpr *) { return true; } 986 987 // Iterators 988 virtual child_iterator child_begin(); 989 virtual child_iterator child_end(); 990 991 virtual void EmitImpl(llvm::Serializer& S) const; 992 static MemberExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C); 993}; 994 995/// CompoundLiteralExpr - [C99 6.5.2.5] 996/// 997class CompoundLiteralExpr : public Expr { 998 /// LParenLoc - If non-null, this is the location of the left paren in a 999 /// compound literal like "(int){4}". This can be null if this is a 1000 /// synthesized compound expression. 1001 SourceLocation LParenLoc; 1002 Stmt *Init; 1003 bool FileScope; 1004public: 1005 CompoundLiteralExpr(SourceLocation lparenloc, QualType ty, Expr *init, 1006 bool fileScope) 1007 : Expr(CompoundLiteralExprClass, ty), LParenLoc(lparenloc), Init(init), 1008 FileScope(fileScope) {} 1009 1010 const Expr *getInitializer() const { return cast<Expr>(Init); } 1011 Expr *getInitializer() { return cast<Expr>(Init); } 1012 1013 bool isFileScope() const { return FileScope; } 1014 1015 SourceLocation getLParenLoc() const { return LParenLoc; } 1016 1017 virtual SourceRange getSourceRange() const { 1018 // FIXME: Init should never be null. 1019 if (!Init) 1020 return SourceRange(); 1021 if (LParenLoc.isInvalid()) 1022 return Init->getSourceRange(); 1023 return SourceRange(LParenLoc, Init->getLocEnd()); 1024 } 1025 1026 static bool classof(const Stmt *T) { 1027 return T->getStmtClass() == CompoundLiteralExprClass; 1028 } 1029 static bool classof(const CompoundLiteralExpr *) { return true; } 1030 1031 // Iterators 1032 virtual child_iterator child_begin(); 1033 virtual child_iterator child_end(); 1034 1035 virtual void EmitImpl(llvm::Serializer& S) const; 1036 static CompoundLiteralExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C); 1037}; 1038 1039/// CastExpr - Base class for type casts, including both implicit 1040/// casts (ImplicitCastExpr) and explicit casts that have some 1041/// representation in the source code (ExplicitCastExpr's derived 1042/// classes). 1043class CastExpr : public Expr { 1044 Stmt *Op; 1045protected: 1046 CastExpr(StmtClass SC, QualType ty, Expr *op) : 1047 Expr(SC, ty, 1048 // Cast expressions are type-dependent if the type is 1049 // dependent (C++ [temp.dep.expr]p3). 1050 ty->isDependentType(), 1051 // Cast expressions are value-dependent if the type is 1052 // dependent or if the subexpression is value-dependent. 1053 ty->isDependentType() || (op && op->isValueDependent())), 1054 Op(op) {} 1055 1056public: 1057 Expr *getSubExpr() { return cast<Expr>(Op); } 1058 const Expr *getSubExpr() const { return cast<Expr>(Op); } 1059 1060 static bool classof(const Stmt *T) { 1061 StmtClass SC = T->getStmtClass(); 1062 if (SC >= CXXNamedCastExprClass && SC <= CXXFunctionalCastExprClass) 1063 return true; 1064 1065 if (SC >= ImplicitCastExprClass && SC <= CStyleCastExprClass) 1066 return true; 1067 1068 return false; 1069 } 1070 static bool classof(const CastExpr *) { return true; } 1071 1072 // Iterators 1073 virtual child_iterator child_begin(); 1074 virtual child_iterator child_end(); 1075}; 1076 1077/// ImplicitCastExpr - Allows us to explicitly represent implicit type 1078/// conversions, which have no direct representation in the original 1079/// source code. For example: converting T[]->T*, void f()->void 1080/// (*f)(), float->double, short->int, etc. 1081/// 1082/// In C, implicit casts always produce rvalues. However, in C++, an 1083/// implicit cast whose result is being bound to a reference will be 1084/// an lvalue. For example: 1085/// 1086/// @code 1087/// class Base { }; 1088/// class Derived : public Base { }; 1089/// void f(Derived d) { 1090/// Base& b = d; // initializer is an ImplicitCastExpr to an lvalue of type Base 1091/// } 1092/// @endcode 1093class ImplicitCastExpr : public CastExpr { 1094 /// LvalueCast - Whether this cast produces an lvalue. 1095 bool LvalueCast; 1096 1097public: 1098 ImplicitCastExpr(QualType ty, Expr *op, bool Lvalue) : 1099 CastExpr(ImplicitCastExprClass, ty, op), LvalueCast(Lvalue) { } 1100 1101 virtual SourceRange getSourceRange() const { 1102 return getSubExpr()->getSourceRange(); 1103 } 1104 1105 /// isLvalueCast - Whether this cast produces an lvalue. 1106 bool isLvalueCast() const { return LvalueCast; } 1107 1108 /// setLvalueCast - Set whether this cast produces an lvalue. 1109 void setLvalueCast(bool Lvalue) { LvalueCast = Lvalue; } 1110 1111 static bool classof(const Stmt *T) { 1112 return T->getStmtClass() == ImplicitCastExprClass; 1113 } 1114 static bool classof(const ImplicitCastExpr *) { return true; } 1115 1116 virtual void EmitImpl(llvm::Serializer& S) const; 1117 static ImplicitCastExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C); 1118}; 1119 1120/// ExplicitCastExpr - An explicit cast written in the source 1121/// code. 1122/// 1123/// This class is effectively an abstract class, because it provides 1124/// the basic representation of an explicitly-written cast without 1125/// specifying which kind of cast (C cast, functional cast, static 1126/// cast, etc.) was written; specific derived classes represent the 1127/// particular style of cast and its location information. 1128/// 1129/// Unlike implicit casts, explicit cast nodes have two different 1130/// types: the type that was written into the source code, and the 1131/// actual type of the expression as determined by semantic 1132/// analysis. These types may differ slightly. For example, in C++ one 1133/// can cast to a reference type, which indicates that the resulting 1134/// expression will be an lvalue. The reference type, however, will 1135/// not be used as the type of the expression. 1136class ExplicitCastExpr : public CastExpr { 1137 /// TypeAsWritten - The type that this expression is casting to, as 1138 /// written in the source code. 1139 QualType TypeAsWritten; 1140 1141protected: 1142 ExplicitCastExpr(StmtClass SC, QualType exprTy, Expr *op, QualType writtenTy) 1143 : CastExpr(SC, exprTy, op), TypeAsWritten(writtenTy) {} 1144 1145public: 1146 /// getTypeAsWritten - Returns the type that this expression is 1147 /// casting to, as written in the source code. 1148 QualType getTypeAsWritten() const { return TypeAsWritten; } 1149 1150 static bool classof(const Stmt *T) { 1151 StmtClass SC = T->getStmtClass(); 1152 if (SC >= ExplicitCastExprClass && SC <= CStyleCastExprClass) 1153 return true; 1154 if (SC >= CXXNamedCastExprClass && SC <= CXXFunctionalCastExprClass) 1155 return true; 1156 1157 return false; 1158 } 1159 static bool classof(const ExplicitCastExpr *) { return true; } 1160}; 1161 1162/// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style 1163/// cast in C++ (C++ [expr.cast]), which uses the syntax 1164/// (Type)expr. For example: @c (int)f. 1165class CStyleCastExpr : public ExplicitCastExpr { 1166 SourceLocation LPLoc; // the location of the left paren 1167 SourceLocation RPLoc; // the location of the right paren 1168public: 1169 CStyleCastExpr(QualType exprTy, Expr *op, QualType writtenTy, 1170 SourceLocation l, SourceLocation r) : 1171 ExplicitCastExpr(CStyleCastExprClass, exprTy, op, writtenTy), 1172 LPLoc(l), RPLoc(r) {} 1173 1174 SourceLocation getLParenLoc() const { return LPLoc; } 1175 SourceLocation getRParenLoc() const { return RPLoc; } 1176 1177 virtual SourceRange getSourceRange() const { 1178 return SourceRange(LPLoc, getSubExpr()->getSourceRange().getEnd()); 1179 } 1180 static bool classof(const Stmt *T) { 1181 return T->getStmtClass() == CStyleCastExprClass; 1182 } 1183 static bool classof(const CStyleCastExpr *) { return true; } 1184 1185 virtual void EmitImpl(llvm::Serializer& S) const; 1186 static CStyleCastExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C); 1187}; 1188 1189/// \brief A builtin binary operation expression such as "x + y" or "x <= y". 1190/// 1191/// This expression node kind describes a builtin binary operation, 1192/// such as "x + y" for integer values "x" and "y". The operands will 1193/// already have been converted to appropriate types (e.g., by 1194/// performing promotions or conversions). 1195/// 1196/// In C++, where operators may be overloaded, a different kind of 1197/// expression node (CXXOperatorCallExpr) is used to express the 1198/// invocation of an overloaded operator with operator syntax. Within 1199/// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is 1200/// used to store an expression "x + y" depends on the subexpressions 1201/// for x and y. If neither x or y is type-dependent, and the "+" 1202/// operator resolves to a built-in operation, BinaryOperator will be 1203/// used to express the computation (x and y may still be 1204/// value-dependent). If either x or y is type-dependent, or if the 1205/// "+" resolves to an overloaded operator, CXXOperatorCallExpr will 1206/// be used to express the computation. 1207class BinaryOperator : public Expr { 1208public: 1209 enum Opcode { 1210 // Operators listed in order of precedence. 1211 // Note that additions to this should also update the StmtVisitor class. 1212 PtrMemD, PtrMemI, // [C++ 5.5] Pointer-to-member operators. 1213 Mul, Div, Rem, // [C99 6.5.5] Multiplicative operators. 1214 Add, Sub, // [C99 6.5.6] Additive operators. 1215 Shl, Shr, // [C99 6.5.7] Bitwise shift operators. 1216 LT, GT, LE, GE, // [C99 6.5.8] Relational operators. 1217 EQ, NE, // [C99 6.5.9] Equality operators. 1218 And, // [C99 6.5.10] Bitwise AND operator. 1219 Xor, // [C99 6.5.11] Bitwise XOR operator. 1220 Or, // [C99 6.5.12] Bitwise OR operator. 1221 LAnd, // [C99 6.5.13] Logical AND operator. 1222 LOr, // [C99 6.5.14] Logical OR operator. 1223 Assign, MulAssign,// [C99 6.5.16] Assignment operators. 1224 DivAssign, RemAssign, 1225 AddAssign, SubAssign, 1226 ShlAssign, ShrAssign, 1227 AndAssign, XorAssign, 1228 OrAssign, 1229 Comma // [C99 6.5.17] Comma operator. 1230 }; 1231private: 1232 enum { LHS, RHS, END_EXPR }; 1233 Stmt* SubExprs[END_EXPR]; 1234 Opcode Opc; 1235 SourceLocation OpLoc; 1236public: 1237 1238 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, 1239 SourceLocation opLoc) 1240 : Expr(BinaryOperatorClass, ResTy, 1241 lhs->isTypeDependent() || rhs->isTypeDependent(), 1242 lhs->isValueDependent() || rhs->isValueDependent()), 1243 Opc(opc), OpLoc(opLoc) { 1244 SubExprs[LHS] = lhs; 1245 SubExprs[RHS] = rhs; 1246 assert(!isCompoundAssignmentOp() && 1247 "Use ArithAssignBinaryOperator for compound assignments"); 1248 } 1249 1250 SourceLocation getOperatorLoc() const { return OpLoc; } 1251 Opcode getOpcode() const { return Opc; } 1252 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } 1253 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } 1254 virtual SourceRange getSourceRange() const { 1255 return SourceRange(getLHS()->getLocStart(), getRHS()->getLocEnd()); 1256 } 1257 1258 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it 1259 /// corresponds to, e.g. "<<=". 1260 static const char *getOpcodeStr(Opcode Op); 1261 1262 /// \brief Retrieve the binary opcode that corresponds to the given 1263 /// overloaded operator. 1264 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO); 1265 1266 /// \brief Retrieve the overloaded operator kind that corresponds to 1267 /// the given binary opcode. 1268 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc); 1269 1270 /// predicates to categorize the respective opcodes. 1271 bool isMultiplicativeOp() const { return Opc >= Mul && Opc <= Rem; } 1272 bool isAdditiveOp() const { return Opc == Add || Opc == Sub; } 1273 bool isShiftOp() const { return Opc == Shl || Opc == Shr; } 1274 bool isBitwiseOp() const { return Opc >= And && Opc <= Or; } 1275 1276 static bool isRelationalOp(Opcode Opc) { return Opc >= LT && Opc <= GE; } 1277 bool isRelationalOp() const { return isRelationalOp(Opc); } 1278 1279 static bool isEqualityOp(Opcode Opc) { return Opc == EQ || Opc == NE; } 1280 bool isEqualityOp() const { return isEqualityOp(Opc); } 1281 1282 static bool isLogicalOp(Opcode Opc) { return Opc == LAnd || Opc == LOr; } 1283 bool isLogicalOp() const { return isLogicalOp(Opc); } 1284 1285 bool isAssignmentOp() const { return Opc >= Assign && Opc <= OrAssign; } 1286 bool isCompoundAssignmentOp() const { return Opc > Assign && Opc <= OrAssign;} 1287 bool isShiftAssignOp() const { return Opc == ShlAssign || Opc == ShrAssign; } 1288 1289 static bool classof(const Stmt *S) { 1290 return S->getStmtClass() == BinaryOperatorClass || 1291 S->getStmtClass() == CompoundAssignOperatorClass; 1292 } 1293 static bool classof(const BinaryOperator *) { return true; } 1294 1295 // Iterators 1296 virtual child_iterator child_begin(); 1297 virtual child_iterator child_end(); 1298 1299 virtual void EmitImpl(llvm::Serializer& S) const; 1300 static BinaryOperator* CreateImpl(llvm::Deserializer& D, ASTContext& C); 1301 1302protected: 1303 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, 1304 SourceLocation oploc, bool dead) 1305 : Expr(CompoundAssignOperatorClass, ResTy), Opc(opc), OpLoc(oploc) { 1306 SubExprs[LHS] = lhs; 1307 SubExprs[RHS] = rhs; 1308 } 1309}; 1310 1311/// CompoundAssignOperator - For compound assignments (e.g. +=), we keep 1312/// track of the type the operation is performed in. Due to the semantics of 1313/// these operators, the operands are promoted, the aritmetic performed, an 1314/// implicit conversion back to the result type done, then the assignment takes 1315/// place. This captures the intermediate type which the computation is done 1316/// in. 1317class CompoundAssignOperator : public BinaryOperator { 1318 QualType ComputationType; 1319public: 1320 CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc, 1321 QualType ResType, QualType CompType, 1322 SourceLocation OpLoc) 1323 : BinaryOperator(lhs, rhs, opc, ResType, OpLoc, true), 1324 ComputationType(CompType) { 1325 assert(isCompoundAssignmentOp() && 1326 "Only should be used for compound assignments"); 1327 } 1328 1329 QualType getComputationType() const { return ComputationType; } 1330 1331 static bool classof(const CompoundAssignOperator *) { return true; } 1332 static bool classof(const Stmt *S) { 1333 return S->getStmtClass() == CompoundAssignOperatorClass; 1334 } 1335 1336 virtual void EmitImpl(llvm::Serializer& S) const; 1337 static CompoundAssignOperator* CreateImpl(llvm::Deserializer& D, 1338 ASTContext& C); 1339}; 1340 1341/// ConditionalOperator - The ?: operator. Note that LHS may be null when the 1342/// GNU "missing LHS" extension is in use. 1343/// 1344class ConditionalOperator : public Expr { 1345 enum { COND, LHS, RHS, END_EXPR }; 1346 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides. 1347public: 1348 ConditionalOperator(Expr *cond, Expr *lhs, Expr *rhs, QualType t) 1349 : Expr(ConditionalOperatorClass, t, 1350 // FIXME: the type of the conditional operator doesn't 1351 // depend on the type of the conditional, but the standard 1352 // seems to imply that it could. File a bug! 1353 ((lhs && lhs->isTypeDependent()) || (rhs && rhs->isTypeDependent())), 1354 (cond->isValueDependent() || 1355 (lhs && lhs->isValueDependent()) || 1356 (rhs && rhs->isValueDependent()))) { 1357 SubExprs[COND] = cond; 1358 SubExprs[LHS] = lhs; 1359 SubExprs[RHS] = rhs; 1360 } 1361 1362 // getCond - Return the expression representing the condition for 1363 // the ?: operator. 1364 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); } 1365 1366 // getTrueExpr - Return the subexpression representing the value of the ?: 1367 // expression if the condition evaluates to true. In most cases this value 1368 // will be the same as getLHS() except a GCC extension allows the left 1369 // subexpression to be omitted, and instead of the condition be returned. 1370 // e.g: x ?: y is shorthand for x ? x : y, except that the expression "x" 1371 // is only evaluated once. 1372 Expr *getTrueExpr() const { 1373 return cast<Expr>(SubExprs[LHS] ? SubExprs[LHS] : SubExprs[COND]); 1374 } 1375 1376 // getTrueExpr - Return the subexpression representing the value of the ?: 1377 // expression if the condition evaluates to false. This is the same as getRHS. 1378 Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); } 1379 1380 Expr *getLHS() const { return cast_or_null<Expr>(SubExprs[LHS]); } 1381 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } 1382 1383 virtual SourceRange getSourceRange() const { 1384 return SourceRange(getCond()->getLocStart(), getRHS()->getLocEnd()); 1385 } 1386 static bool classof(const Stmt *T) { 1387 return T->getStmtClass() == ConditionalOperatorClass; 1388 } 1389 static bool classof(const ConditionalOperator *) { return true; } 1390 1391 // Iterators 1392 virtual child_iterator child_begin(); 1393 virtual child_iterator child_end(); 1394 1395 virtual void EmitImpl(llvm::Serializer& S) const; 1396 static ConditionalOperator* CreateImpl(llvm::Deserializer& D, ASTContext& C); 1397}; 1398 1399/// AddrLabelExpr - The GNU address of label extension, representing &&label. 1400class AddrLabelExpr : public Expr { 1401 SourceLocation AmpAmpLoc, LabelLoc; 1402 LabelStmt *Label; 1403public: 1404 AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelStmt *L, 1405 QualType t) 1406 : Expr(AddrLabelExprClass, t), AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {} 1407 1408 virtual SourceRange getSourceRange() const { 1409 return SourceRange(AmpAmpLoc, LabelLoc); 1410 } 1411 1412 LabelStmt *getLabel() const { return Label; } 1413 1414 static bool classof(const Stmt *T) { 1415 return T->getStmtClass() == AddrLabelExprClass; 1416 } 1417 static bool classof(const AddrLabelExpr *) { return true; } 1418 1419 // Iterators 1420 virtual child_iterator child_begin(); 1421 virtual child_iterator child_end(); 1422 1423 virtual void EmitImpl(llvm::Serializer& S) const; 1424 static AddrLabelExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C); 1425}; 1426 1427/// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}). 1428/// The StmtExpr contains a single CompoundStmt node, which it evaluates and 1429/// takes the value of the last subexpression. 1430class StmtExpr : public Expr { 1431 Stmt *SubStmt; 1432 SourceLocation LParenLoc, RParenLoc; 1433public: 1434 StmtExpr(CompoundStmt *substmt, QualType T, 1435 SourceLocation lp, SourceLocation rp) : 1436 Expr(StmtExprClass, T), SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { } 1437 1438 CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); } 1439 const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); } 1440 1441 virtual SourceRange getSourceRange() const { 1442 return SourceRange(LParenLoc, RParenLoc); 1443 } 1444 1445 SourceLocation getLParenLoc() const { return LParenLoc; } 1446 SourceLocation getRParenLoc() const { return RParenLoc; } 1447 1448 static bool classof(const Stmt *T) { 1449 return T->getStmtClass() == StmtExprClass; 1450 } 1451 static bool classof(const StmtExpr *) { return true; } 1452 1453 // Iterators 1454 virtual child_iterator child_begin(); 1455 virtual child_iterator child_end(); 1456 1457 virtual void EmitImpl(llvm::Serializer& S) const; 1458 static StmtExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C); 1459}; 1460 1461/// TypesCompatibleExpr - GNU builtin-in function __builtin_type_compatible_p. 1462/// This AST node represents a function that returns 1 if two *types* (not 1463/// expressions) are compatible. The result of this built-in function can be 1464/// used in integer constant expressions. 1465class TypesCompatibleExpr : public Expr { 1466 QualType Type1; 1467 QualType Type2; 1468 SourceLocation BuiltinLoc, RParenLoc; 1469public: 1470 TypesCompatibleExpr(QualType ReturnType, SourceLocation BLoc, 1471 QualType t1, QualType t2, SourceLocation RP) : 1472 Expr(TypesCompatibleExprClass, ReturnType), Type1(t1), Type2(t2), 1473 BuiltinLoc(BLoc), RParenLoc(RP) {} 1474 1475 QualType getArgType1() const { return Type1; } 1476 QualType getArgType2() const { return Type2; } 1477 1478 virtual SourceRange getSourceRange() const { 1479 return SourceRange(BuiltinLoc, RParenLoc); 1480 } 1481 static bool classof(const Stmt *T) { 1482 return T->getStmtClass() == TypesCompatibleExprClass; 1483 } 1484 static bool classof(const TypesCompatibleExpr *) { return true; } 1485 1486 // Iterators 1487 virtual child_iterator child_begin(); 1488 virtual child_iterator child_end(); 1489 1490 virtual void EmitImpl(llvm::Serializer& S) const; 1491 static TypesCompatibleExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C); 1492}; 1493 1494/// ShuffleVectorExpr - clang-specific builtin-in function 1495/// __builtin_shufflevector. 1496/// This AST node represents a operator that does a constant 1497/// shuffle, similar to LLVM's shufflevector instruction. It takes 1498/// two vectors and a variable number of constant indices, 1499/// and returns the appropriately shuffled vector. 1500class ShuffleVectorExpr : public Expr { 1501 SourceLocation BuiltinLoc, RParenLoc; 1502 1503 // SubExprs - the list of values passed to the __builtin_shufflevector 1504 // function. The first two are vectors, and the rest are constant 1505 // indices. The number of values in this list is always 1506 // 2+the number of indices in the vector type. 1507 Stmt **SubExprs; 1508 unsigned NumExprs; 1509 1510public: 1511 ShuffleVectorExpr(Expr **args, unsigned nexpr, 1512 QualType Type, SourceLocation BLoc, 1513 SourceLocation RP) : 1514 Expr(ShuffleVectorExprClass, Type), BuiltinLoc(BLoc), 1515 RParenLoc(RP), NumExprs(nexpr) { 1516 1517 SubExprs = new Stmt*[nexpr]; 1518 for (unsigned i = 0; i < nexpr; i++) 1519 SubExprs[i] = args[i]; 1520 } 1521 1522 virtual SourceRange getSourceRange() const { 1523 return SourceRange(BuiltinLoc, RParenLoc); 1524 } 1525 static bool classof(const Stmt *T) { 1526 return T->getStmtClass() == ShuffleVectorExprClass; 1527 } 1528 static bool classof(const ShuffleVectorExpr *) { return true; } 1529 1530 ~ShuffleVectorExpr() { 1531 delete [] SubExprs; 1532 } 1533 1534 /// getNumSubExprs - Return the size of the SubExprs array. This includes the 1535 /// constant expression, the actual arguments passed in, and the function 1536 /// pointers. 1537 unsigned getNumSubExprs() const { return NumExprs; } 1538 1539 /// getExpr - Return the Expr at the specified index. 1540 Expr *getExpr(unsigned Index) { 1541 assert((Index < NumExprs) && "Arg access out of range!"); 1542 return cast<Expr>(SubExprs[Index]); 1543 } 1544 const Expr *getExpr(unsigned Index) const { 1545 assert((Index < NumExprs) && "Arg access out of range!"); 1546 return cast<Expr>(SubExprs[Index]); 1547 } 1548 1549 unsigned getShuffleMaskIdx(ASTContext &Ctx, unsigned N) { 1550 assert((N < NumExprs - 2) && "Shuffle idx out of range!"); 1551 return getExpr(N+2)->getIntegerConstantExprValue(Ctx).getZExtValue(); 1552 } 1553 1554 // Iterators 1555 virtual child_iterator child_begin(); 1556 virtual child_iterator child_end(); 1557 1558 virtual void EmitImpl(llvm::Serializer& S) const; 1559 static ShuffleVectorExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C); 1560}; 1561 1562/// ChooseExpr - GNU builtin-in function __builtin_choose_expr. 1563/// This AST node is similar to the conditional operator (?:) in C, with 1564/// the following exceptions: 1565/// - the test expression must be a integer constant expression. 1566/// - the expression returned acts like the chosen subexpression in every 1567/// visible way: the type is the same as that of the chosen subexpression, 1568/// and all predicates (whether it's an l-value, whether it's an integer 1569/// constant expression, etc.) return the same result as for the chosen 1570/// sub-expression. 1571class ChooseExpr : public Expr { 1572 enum { COND, LHS, RHS, END_EXPR }; 1573 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides. 1574 SourceLocation BuiltinLoc, RParenLoc; 1575public: 1576 ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs, QualType t, 1577 SourceLocation RP) 1578 : Expr(ChooseExprClass, t), 1579 BuiltinLoc(BLoc), RParenLoc(RP) { 1580 SubExprs[COND] = cond; 1581 SubExprs[LHS] = lhs; 1582 SubExprs[RHS] = rhs; 1583 } 1584 1585 /// isConditionTrue - Return whether the condition is true (i.e. not 1586 /// equal to zero). 1587 bool isConditionTrue(ASTContext &C) const; 1588 1589 /// getChosenSubExpr - Return the subexpression chosen according to the 1590 /// condition. 1591 Expr *getChosenSubExpr(ASTContext &C) const { 1592 return isConditionTrue(C) ? getLHS() : getRHS(); 1593 } 1594 1595 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); } 1596 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } 1597 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } 1598 1599 virtual SourceRange getSourceRange() const { 1600 return SourceRange(BuiltinLoc, RParenLoc); 1601 } 1602 static bool classof(const Stmt *T) { 1603 return T->getStmtClass() == ChooseExprClass; 1604 } 1605 static bool classof(const ChooseExpr *) { return true; } 1606 1607 // Iterators 1608 virtual child_iterator child_begin(); 1609 virtual child_iterator child_end(); 1610 1611 virtual void EmitImpl(llvm::Serializer& S) const; 1612 static ChooseExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C); 1613}; 1614 1615/// GNUNullExpr - Implements the GNU __null extension, which is a name 1616/// for a null pointer constant that has integral type (e.g., int or 1617/// long) and is the same size and alignment as a pointer. The __null 1618/// extension is typically only used by system headers, which define 1619/// NULL as __null in C++ rather than using 0 (which is an integer 1620/// that may not match the size of a pointer). 1621class GNUNullExpr : public Expr { 1622 /// TokenLoc - The location of the __null keyword. 1623 SourceLocation TokenLoc; 1624 1625public: 1626 GNUNullExpr(QualType Ty, SourceLocation Loc) 1627 : Expr(GNUNullExprClass, Ty), TokenLoc(Loc) { } 1628 1629 /// getTokenLocation - The location of the __null token. 1630 SourceLocation getTokenLocation() const { return TokenLoc; } 1631 1632 virtual SourceRange getSourceRange() const { 1633 return SourceRange(TokenLoc); 1634 } 1635 static bool classof(const Stmt *T) { 1636 return T->getStmtClass() == GNUNullExprClass; 1637 } 1638 static bool classof(const GNUNullExpr *) { return true; } 1639 1640 // Iterators 1641 virtual child_iterator child_begin(); 1642 virtual child_iterator child_end(); 1643 1644 virtual void EmitImpl(llvm::Serializer& S) const; 1645 static GNUNullExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C); 1646}; 1647 1648/// VAArgExpr, used for the builtin function __builtin_va_start. 1649class VAArgExpr : public Expr { 1650 Stmt *Val; 1651 SourceLocation BuiltinLoc, RParenLoc; 1652public: 1653 VAArgExpr(SourceLocation BLoc, Expr* e, QualType t, SourceLocation RPLoc) 1654 : Expr(VAArgExprClass, t), 1655 Val(e), 1656 BuiltinLoc(BLoc), 1657 RParenLoc(RPLoc) { } 1658 1659 const Expr *getSubExpr() const { return cast<Expr>(Val); } 1660 Expr *getSubExpr() { return cast<Expr>(Val); } 1661 virtual SourceRange getSourceRange() const { 1662 return SourceRange(BuiltinLoc, RParenLoc); 1663 } 1664 static bool classof(const Stmt *T) { 1665 return T->getStmtClass() == VAArgExprClass; 1666 } 1667 static bool classof(const VAArgExpr *) { return true; } 1668 1669 // Iterators 1670 virtual child_iterator child_begin(); 1671 virtual child_iterator child_end(); 1672 1673 virtual void EmitImpl(llvm::Serializer& S) const; 1674 static VAArgExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C); 1675}; 1676 1677/// @brief Describes an C or C++ initializer list. 1678/// 1679/// InitListExpr describes an initializer list, which can be used to 1680/// initialize objects of different types, including 1681/// struct/class/union types, arrays, and vectors. For example: 1682/// 1683/// @code 1684/// struct foo x = { 1, { 2, 3 } }; 1685/// @endcode 1686/// 1687/// Prior to semantic analysis, an initializer list will represent the 1688/// initializer list as written by the user, but will have the 1689/// placeholder type "void". This initializer list is called the 1690/// syntactic form of the initializer, and may contain C99 designated 1691/// initializers (represented as DesignatedInitExprs), initializations 1692/// of subobject members without explicit braces, and so on. Clients 1693/// interested in the original syntax of the initializer list should 1694/// use the syntactic form of the initializer list. 1695/// 1696/// After semantic analysis, the initializer list will represent the 1697/// semantic form of the initializer, where the initializations of all 1698/// subobjects are made explicit with nested InitListExpr nodes and 1699/// C99 designators have been eliminated by placing the designated 1700/// initializations into the subobject they initialize. Additionally, 1701/// any "holes" in the initialization, where no initializer has been 1702/// specified for a particular subobject, will be replaced with 1703/// implicitly-generated ImplicitValueInitExpr expressions that 1704/// value-initialize the subobjects. Note, however, that the 1705/// initializer lists may still have fewer initializers than there are 1706/// elements to initialize within the object. 1707/// 1708/// Given the semantic form of the initializer list, one can retrieve 1709/// the original syntactic form of that initializer list (if it 1710/// exists) using getSyntacticForm(). Since many initializer lists 1711/// have the same syntactic and semantic forms, getSyntacticForm() may 1712/// return NULL, indicating that the current initializer list also 1713/// serves as its syntactic form. 1714class InitListExpr : public Expr { 1715 std::vector<Stmt *> InitExprs; 1716 SourceLocation LBraceLoc, RBraceLoc; 1717 1718 /// Contains the initializer list that describes the syntactic form 1719 /// written in the source code. 1720 InitListExpr *SyntacticForm; 1721 1722 /// If this initializer list initializes a union, specifies which 1723 /// field within the union will be initialized. 1724 FieldDecl *UnionFieldInit; 1725 1726 /// Whether this initializer list originally had a GNU array-range 1727 /// designator in it. This is a temporary marker used by CodeGen. 1728 bool HadArrayRangeDesignator; 1729 1730public: 1731 InitListExpr(SourceLocation lbraceloc, Expr **initexprs, unsigned numinits, 1732 SourceLocation rbraceloc); 1733 1734 unsigned getNumInits() const { return InitExprs.size(); } 1735 1736 const Expr* getInit(unsigned Init) const { 1737 assert(Init < getNumInits() && "Initializer access out of range!"); 1738 return cast_or_null<Expr>(InitExprs[Init]); 1739 } 1740 1741 Expr* getInit(unsigned Init) { 1742 assert(Init < getNumInits() && "Initializer access out of range!"); 1743 return cast_or_null<Expr>(InitExprs[Init]); 1744 } 1745 1746 void setInit(unsigned Init, Expr *expr) { 1747 assert(Init < getNumInits() && "Initializer access out of range!"); 1748 InitExprs[Init] = expr; 1749 } 1750 1751 /// @brief Specify the number of initializers 1752 /// 1753 /// If there are more than @p NumInits initializers, the remaining 1754 /// initializers will be destroyed. If there are fewer than @p 1755 /// NumInits initializers, NULL expressions will be added for the 1756 /// unknown initializers. 1757 void resizeInits(ASTContext &Context, unsigned NumInits); 1758 1759 /// @brief Updates the initializer at index @p Init with the new 1760 /// expression @p expr, and returns the old expression at that 1761 /// location. 1762 /// 1763 /// When @p Init is out of range for this initializer list, the 1764 /// initializer list will be extended with NULL expressions to 1765 /// accomodate the new entry. 1766 Expr *updateInit(unsigned Init, Expr *expr); 1767 1768 /// \brief If this initializes a union, specifies which field in the 1769 /// union to initialize. 1770 /// 1771 /// Typically, this field is the first named field within the 1772 /// union. However, a designated initializer can specify the 1773 /// initialization of a different field within the union. 1774 FieldDecl *getInitializedFieldInUnion() { return UnionFieldInit; } 1775 void setInitializedFieldInUnion(FieldDecl *FD) { UnionFieldInit = FD; } 1776 1777 // Explicit InitListExpr's originate from source code (and have valid source 1778 // locations). Implicit InitListExpr's are created by the semantic analyzer. 1779 bool isExplicit() { 1780 return LBraceLoc.isValid() && RBraceLoc.isValid(); 1781 } 1782 1783 void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; } 1784 1785 /// @brief Retrieve the initializer list that describes the 1786 /// syntactic form of the initializer. 1787 /// 1788 /// 1789 InitListExpr *getSyntacticForm() const { return SyntacticForm; } 1790 void setSyntacticForm(InitListExpr *Init) { SyntacticForm = Init; } 1791 1792 bool hadArrayRangeDesignator() const { return HadArrayRangeDesignator; } 1793 void sawArrayRangeDesignator() { 1794 HadArrayRangeDesignator = true; 1795 } 1796 1797 virtual SourceRange getSourceRange() const { 1798 return SourceRange(LBraceLoc, RBraceLoc); 1799 } 1800 static bool classof(const Stmt *T) { 1801 return T->getStmtClass() == InitListExprClass; 1802 } 1803 static bool classof(const InitListExpr *) { return true; } 1804 1805 // Iterators 1806 virtual child_iterator child_begin(); 1807 virtual child_iterator child_end(); 1808 1809 typedef std::vector<Stmt *>::iterator iterator; 1810 typedef std::vector<Stmt *>::reverse_iterator reverse_iterator; 1811 1812 iterator begin() { return InitExprs.begin(); } 1813 iterator end() { return InitExprs.end(); } 1814 reverse_iterator rbegin() { return InitExprs.rbegin(); } 1815 reverse_iterator rend() { return InitExprs.rend(); } 1816 1817 // Serailization. 1818 virtual void EmitImpl(llvm::Serializer& S) const; 1819 static InitListExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C); 1820 1821private: 1822 // Used by serializer. 1823 InitListExpr() : Expr(InitListExprClass, QualType()) {} 1824}; 1825 1826/// @brief Represents a C99 designated initializer expression. 1827/// 1828/// A designated initializer expression (C99 6.7.8) contains one or 1829/// more designators (which can be field designators, array 1830/// designators, or GNU array-range designators) followed by an 1831/// expression that initializes the field or element(s) that the 1832/// designators refer to. For example, given: 1833/// 1834/// @code 1835/// struct point { 1836/// double x; 1837/// double y; 1838/// }; 1839/// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 }; 1840/// @endcode 1841/// 1842/// The InitListExpr contains three DesignatedInitExprs, the first of 1843/// which covers @c [2].y=1.0. This DesignatedInitExpr will have two 1844/// designators, one array designator for @c [2] followed by one field 1845/// designator for @c .y. The initalization expression will be 1.0. 1846class DesignatedInitExpr : public Expr { 1847 /// The location of the '=' or ':' prior to the actual initializer 1848 /// expression. 1849 SourceLocation EqualOrColonLoc; 1850 1851 /// Whether this designated initializer used the GNU deprecated ':' 1852 /// syntax rather than the C99 '=' syntax. 1853 bool UsesColonSyntax : 1; 1854 1855 /// The number of designators in this initializer expression. 1856 unsigned NumDesignators : 15; 1857 1858 /// The number of subexpressions of this initializer expression, 1859 /// which contains both the initializer and any additional 1860 /// expressions used by array and array-range designators. 1861 unsigned NumSubExprs : 16; 1862 1863 DesignatedInitExpr(QualType Ty, unsigned NumDesignators, 1864 SourceLocation EqualOrColonLoc, bool UsesColonSyntax, 1865 unsigned NumSubExprs) 1866 : Expr(DesignatedInitExprClass, Ty), 1867 EqualOrColonLoc(EqualOrColonLoc), UsesColonSyntax(UsesColonSyntax), 1868 NumDesignators(NumDesignators), NumSubExprs(NumSubExprs) { } 1869 1870public: 1871 /// A field designator, e.g., ".x". 1872 struct FieldDesignator { 1873 /// Refers to the field that is being initialized. The low bit 1874 /// of this field determines whether this is actually a pointer 1875 /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When 1876 /// initially constructed, a field designator will store an 1877 /// IdentifierInfo*. After semantic analysis has resolved that 1878 /// name, the field designator will instead store a FieldDecl*. 1879 uintptr_t NameOrField; 1880 1881 /// The location of the '.' in the designated initializer. 1882 unsigned DotLoc; 1883 1884 /// The location of the field name in the designated initializer. 1885 unsigned FieldLoc; 1886 }; 1887 1888 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]". 1889 struct ArrayOrRangeDesignator { 1890 /// Location of the first index expression within the designated 1891 /// initializer expression's list of subexpressions. 1892 unsigned Index; 1893 /// The location of the '[' starting the array range designator. 1894 unsigned LBracketLoc; 1895 /// The location of the ellipsis separating the start and end 1896 /// indices. Only valid for GNU array-range designators. 1897 unsigned EllipsisLoc; 1898 /// The location of the ']' terminating the array range designator. 1899 unsigned RBracketLoc; 1900 }; 1901 1902 /// @brief Represents a single C99 designator. 1903 /// 1904 /// @todo This class is infuriatingly similar to clang::Designator, 1905 /// but minor differences (storing indices vs. storing pointers) 1906 /// keep us from reusing it. Try harder, later, to rectify these 1907 /// differences. 1908 class Designator { 1909 /// @brief The kind of designator this describes. 1910 enum { 1911 FieldDesignator, 1912 ArrayDesignator, 1913 ArrayRangeDesignator 1914 } Kind; 1915 1916 union { 1917 /// A field designator, e.g., ".x". 1918 struct FieldDesignator Field; 1919 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]". 1920 struct ArrayOrRangeDesignator ArrayOrRange; 1921 }; 1922 friend class DesignatedInitExpr; 1923 1924 public: 1925 /// @brief Initializes a field designator. 1926 Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc, 1927 SourceLocation FieldLoc) 1928 : Kind(FieldDesignator) { 1929 Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01; 1930 Field.DotLoc = DotLoc.getRawEncoding(); 1931 Field.FieldLoc = FieldLoc.getRawEncoding(); 1932 } 1933 1934 /// @brief Initializes an array designator. 1935 Designator(unsigned Index, SourceLocation LBracketLoc, 1936 SourceLocation RBracketLoc) 1937 : Kind(ArrayDesignator) { 1938 ArrayOrRange.Index = Index; 1939 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding(); 1940 ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding(); 1941 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding(); 1942 } 1943 1944 /// @brief Initializes a GNU array-range designator. 1945 Designator(unsigned Index, SourceLocation LBracketLoc, 1946 SourceLocation EllipsisLoc, SourceLocation RBracketLoc) 1947 : Kind(ArrayRangeDesignator) { 1948 ArrayOrRange.Index = Index; 1949 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding(); 1950 ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding(); 1951 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding(); 1952 } 1953 1954 bool isFieldDesignator() const { return Kind == FieldDesignator; } 1955 bool isArrayDesignator() const { return Kind == ArrayDesignator; } 1956 bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; } 1957 1958 IdentifierInfo * getFieldName(); 1959 1960 FieldDecl *getField() { 1961 assert(Kind == FieldDesignator && "Only valid on a field designator"); 1962 if (Field.NameOrField & 0x01) 1963 return 0; 1964 else 1965 return reinterpret_cast<FieldDecl *>(Field.NameOrField); 1966 } 1967 1968 void setField(FieldDecl *FD) { 1969 assert(Kind == FieldDesignator && "Only valid on a field designator"); 1970 Field.NameOrField = reinterpret_cast<uintptr_t>(FD); 1971 } 1972 1973 SourceLocation getDotLoc() const { 1974 assert(Kind == FieldDesignator && "Only valid on a field designator"); 1975 return SourceLocation::getFromRawEncoding(Field.DotLoc); 1976 } 1977 1978 SourceLocation getFieldLoc() const { 1979 assert(Kind == FieldDesignator && "Only valid on a field designator"); 1980 return SourceLocation::getFromRawEncoding(Field.FieldLoc); 1981 } 1982 1983 SourceLocation getLBracketLoc() const { 1984 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && 1985 "Only valid on an array or array-range designator"); 1986 return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc); 1987 } 1988 1989 SourceLocation getRBracketLoc() const { 1990 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && 1991 "Only valid on an array or array-range designator"); 1992 return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc); 1993 } 1994 1995 SourceLocation getEllipsisLoc() const { 1996 assert(Kind == ArrayRangeDesignator && 1997 "Only valid on an array-range designator"); 1998 return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc); 1999 } 2000 2001 SourceLocation getStartLocation() const { 2002 if (Kind == FieldDesignator) 2003 return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc(); 2004 else 2005 return getLBracketLoc(); 2006 } 2007 }; 2008 2009 static DesignatedInitExpr *Create(ASTContext &C, Designator *Designators, 2010 unsigned NumDesignators, 2011 Expr **IndexExprs, unsigned NumIndexExprs, 2012 SourceLocation EqualOrColonLoc, 2013 bool UsesColonSyntax, Expr *Init); 2014 2015 /// @brief Returns the number of designators in this initializer. 2016 unsigned size() const { return NumDesignators; } 2017 2018 // Iterator access to the designators. 2019 typedef Designator* designators_iterator; 2020 designators_iterator designators_begin(); 2021 designators_iterator designators_end(); 2022 2023 Expr *getArrayIndex(const Designator& D); 2024 Expr *getArrayRangeStart(const Designator& D); 2025 Expr *getArrayRangeEnd(const Designator& D); 2026 2027 /// @brief Retrieve the location of the '=' that precedes the 2028 /// initializer value itself, if present. 2029 SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; } 2030 2031 /// @brief Determines whether this designated initializer used the 2032 /// GNU 'fieldname:' syntax or the C99 '=' syntax. 2033 bool usesColonSyntax() const { return UsesColonSyntax; } 2034 2035 /// @brief Retrieve the initializer value. 2036 Expr *getInit() const { 2037 return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin()); 2038 } 2039 2040 void setInit(Expr *init) { 2041 *child_begin() = init; 2042 } 2043 2044 virtual SourceRange getSourceRange() const; 2045 2046 static bool classof(const Stmt *T) { 2047 return T->getStmtClass() == DesignatedInitExprClass; 2048 } 2049 static bool classof(const DesignatedInitExpr *) { return true; } 2050 2051 // Iterators 2052 virtual child_iterator child_begin(); 2053 virtual child_iterator child_end(); 2054}; 2055 2056/// \brief Represents an implicitly-generated value initialization of 2057/// an object of a given type. 2058/// 2059/// Implicit value initializations occur within semantic initializer 2060/// list expressions (InitListExpr) as placeholders for subobject 2061/// initializations not explicitly specified by the user. 2062/// 2063/// \see InitListExpr 2064class ImplicitValueInitExpr : public Expr { 2065public: 2066 explicit ImplicitValueInitExpr(QualType ty) 2067 : Expr(ImplicitValueInitExprClass, ty) { } 2068 2069 static bool classof(const Stmt *T) { 2070 return T->getStmtClass() == ImplicitValueInitExprClass; 2071 } 2072 static bool classof(const ImplicitValueInitExpr *) { return true; } 2073 2074 virtual SourceRange getSourceRange() const { 2075 return SourceRange(); 2076 } 2077 2078 // Iterators 2079 virtual child_iterator child_begin(); 2080 virtual child_iterator child_end(); 2081}; 2082 2083//===----------------------------------------------------------------------===// 2084// Clang Extensions 2085//===----------------------------------------------------------------------===// 2086 2087 2088/// ExtVectorElementExpr - This represents access to specific elements of a 2089/// vector, and may occur on the left hand side or right hand side. For example 2090/// the following is legal: "V.xy = V.zw" if V is a 4 element extended vector. 2091/// 2092/// Note that the base may have either vector or pointer to vector type, just 2093/// like a struct field reference. 2094/// 2095class ExtVectorElementExpr : public Expr { 2096 Stmt *Base; 2097 IdentifierInfo &Accessor; 2098 SourceLocation AccessorLoc; 2099public: 2100 ExtVectorElementExpr(QualType ty, Expr *base, IdentifierInfo &accessor, 2101 SourceLocation loc) 2102 : Expr(ExtVectorElementExprClass, ty), 2103 Base(base), Accessor(accessor), AccessorLoc(loc) {} 2104 2105 const Expr *getBase() const { return cast<Expr>(Base); } 2106 Expr *getBase() { return cast<Expr>(Base); } 2107 2108 IdentifierInfo &getAccessor() const { return Accessor; } 2109 2110 /// getNumElements - Get the number of components being selected. 2111 unsigned getNumElements() const; 2112 2113 /// containsDuplicateElements - Return true if any element access is 2114 /// repeated. 2115 bool containsDuplicateElements() const; 2116 2117 /// getEncodedElementAccess - Encode the elements accessed into an llvm 2118 /// aggregate Constant of ConstantInt(s). 2119 void getEncodedElementAccess(llvm::SmallVectorImpl<unsigned> &Elts) const; 2120 2121 virtual SourceRange getSourceRange() const { 2122 return SourceRange(getBase()->getLocStart(), AccessorLoc); 2123 } 2124 2125 /// isArrow - Return true if the base expression is a pointer to vector, 2126 /// return false if the base expression is a vector. 2127 bool isArrow() const; 2128 2129 static bool classof(const Stmt *T) { 2130 return T->getStmtClass() == ExtVectorElementExprClass; 2131 } 2132 static bool classof(const ExtVectorElementExpr *) { return true; } 2133 2134 // Iterators 2135 virtual child_iterator child_begin(); 2136 virtual child_iterator child_end(); 2137 2138 virtual void EmitImpl(llvm::Serializer& S) const; 2139 static ExtVectorElementExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C); 2140}; 2141 2142 2143/// BlockExpr - Adaptor class for mixing a BlockDecl with expressions. 2144/// ^{ statement-body } or ^(int arg1, float arg2){ statement-body } 2145class BlockExpr : public Expr { 2146protected: 2147 BlockDecl *TheBlock; 2148 bool HasBlockDeclRefExprs; 2149public: 2150 BlockExpr(BlockDecl *BD, QualType ty, bool hasBlockDeclRefExprs) 2151 : Expr(BlockExprClass, ty), 2152 TheBlock(BD), HasBlockDeclRefExprs(hasBlockDeclRefExprs) {} 2153 2154 const BlockDecl *getBlockDecl() const { return TheBlock; } 2155 BlockDecl *getBlockDecl() { return TheBlock; } 2156 2157 // Convenience functions for probing the underlying BlockDecl. 2158 SourceLocation getCaretLocation() const; 2159 const Stmt *getBody() const; 2160 Stmt *getBody(); 2161 2162 virtual SourceRange getSourceRange() const { 2163 return SourceRange(getCaretLocation(), getBody()->getLocEnd()); 2164 } 2165 2166 /// getFunctionType - Return the underlying function type for this block. 2167 const FunctionType *getFunctionType() const; 2168 2169 /// hasBlockDeclRefExprs - Return true iff the block has BlockDeclRefExpr 2170 /// contained inside. 2171 bool hasBlockDeclRefExprs() const { return HasBlockDeclRefExprs; } 2172 2173 static bool classof(const Stmt *T) { 2174 return T->getStmtClass() == BlockExprClass; 2175 } 2176 static bool classof(const BlockExpr *) { return true; } 2177 2178 // Iterators 2179 virtual child_iterator child_begin(); 2180 virtual child_iterator child_end(); 2181 2182 virtual void EmitImpl(llvm::Serializer& S) const; 2183 static BlockExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C); 2184}; 2185 2186/// BlockDeclRefExpr - A reference to a declared variable, function, 2187/// enum, etc. 2188class BlockDeclRefExpr : public Expr { 2189 ValueDecl *D; 2190 SourceLocation Loc; 2191 bool IsByRef; 2192public: 2193 BlockDeclRefExpr(ValueDecl *d, QualType t, SourceLocation l, bool ByRef) : 2194 Expr(BlockDeclRefExprClass, t), D(d), Loc(l), IsByRef(ByRef) {} 2195 2196 ValueDecl *getDecl() { return D; } 2197 const ValueDecl *getDecl() const { return D; } 2198 virtual SourceRange getSourceRange() const { return SourceRange(Loc); } 2199 2200 bool isByRef() const { return IsByRef; } 2201 2202 static bool classof(const Stmt *T) { 2203 return T->getStmtClass() == BlockDeclRefExprClass; 2204 } 2205 static bool classof(const BlockDeclRefExpr *) { return true; } 2206 2207 // Iterators 2208 virtual child_iterator child_begin(); 2209 virtual child_iterator child_end(); 2210 2211 virtual void EmitImpl(llvm::Serializer& S) const; 2212 static BlockDeclRefExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C); 2213}; 2214 2215} // end namespace clang 2216 2217#endif 2218