Expr.cpp revision 6f4a69a3107e7ff1569c747f7c6bdf7cff8cbf55
1//===--- Expr.cpp - Expression AST Node Implementation --------------------===// 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 implements the Expr class and subclasses. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/AST/Expr.h" 15#include "clang/AST/APValue.h" 16#include "clang/AST/ASTContext.h" 17#include "clang/AST/DeclObjC.h" 18#include "clang/AST/DeclCXX.h" 19#include "clang/AST/DeclTemplate.h" 20#include "clang/AST/RecordLayout.h" 21#include "clang/AST/StmtVisitor.h" 22#include "clang/Basic/Builtins.h" 23#include "clang/Basic/TargetInfo.h" 24#include <algorithm> 25using namespace clang; 26 27//===----------------------------------------------------------------------===// 28// Primary Expressions. 29//===----------------------------------------------------------------------===// 30 31PredefinedExpr* PredefinedExpr::Clone(ASTContext &C) const { 32 return new (C) PredefinedExpr(Loc, getType(), Type); 33} 34 35IntegerLiteral* IntegerLiteral::Clone(ASTContext &C) const { 36 return new (C) IntegerLiteral(Value, getType(), Loc); 37} 38 39CharacterLiteral* CharacterLiteral::Clone(ASTContext &C) const { 40 return new (C) CharacterLiteral(Value, IsWide, getType(), Loc); 41} 42 43FloatingLiteral* FloatingLiteral::Clone(ASTContext &C) const { 44 return new (C) FloatingLiteral(Value, IsExact, getType(), Loc); 45} 46 47ImaginaryLiteral* ImaginaryLiteral::Clone(ASTContext &C) const { 48 // FIXME: Use virtual Clone(), once it is available 49 Expr *ClonedVal = 0; 50 if (const IntegerLiteral *IntLit = dyn_cast<IntegerLiteral>(Val)) 51 ClonedVal = IntLit->Clone(C); 52 else 53 ClonedVal = cast<FloatingLiteral>(Val)->Clone(C); 54 return new (C) ImaginaryLiteral(ClonedVal, getType()); 55} 56 57GNUNullExpr* GNUNullExpr::Clone(ASTContext &C) const { 58 return new (C) GNUNullExpr(getType(), TokenLoc); 59} 60 61/// getValueAsApproximateDouble - This returns the value as an inaccurate 62/// double. Note that this may cause loss of precision, but is useful for 63/// debugging dumps, etc. 64double FloatingLiteral::getValueAsApproximateDouble() const { 65 llvm::APFloat V = getValue(); 66 bool ignored; 67 V.convert(llvm::APFloat::IEEEdouble, llvm::APFloat::rmNearestTiesToEven, 68 &ignored); 69 return V.convertToDouble(); 70} 71 72StringLiteral *StringLiteral::Create(ASTContext &C, const char *StrData, 73 unsigned ByteLength, bool Wide, 74 QualType Ty, 75 const SourceLocation *Loc, 76 unsigned NumStrs) { 77 // Allocate enough space for the StringLiteral plus an array of locations for 78 // any concatenated string tokens. 79 void *Mem = C.Allocate(sizeof(StringLiteral)+ 80 sizeof(SourceLocation)*(NumStrs-1), 81 llvm::alignof<StringLiteral>()); 82 StringLiteral *SL = new (Mem) StringLiteral(Ty); 83 84 // OPTIMIZE: could allocate this appended to the StringLiteral. 85 char *AStrData = new (C, 1) char[ByteLength]; 86 memcpy(AStrData, StrData, ByteLength); 87 SL->StrData = AStrData; 88 SL->ByteLength = ByteLength; 89 SL->IsWide = Wide; 90 SL->TokLocs[0] = Loc[0]; 91 SL->NumConcatenated = NumStrs; 92 93 if (NumStrs != 1) 94 memcpy(&SL->TokLocs[1], Loc+1, sizeof(SourceLocation)*(NumStrs-1)); 95 return SL; 96} 97 98StringLiteral *StringLiteral::CreateEmpty(ASTContext &C, unsigned NumStrs) { 99 void *Mem = C.Allocate(sizeof(StringLiteral)+ 100 sizeof(SourceLocation)*(NumStrs-1), 101 llvm::alignof<StringLiteral>()); 102 StringLiteral *SL = new (Mem) StringLiteral(QualType()); 103 SL->StrData = 0; 104 SL->ByteLength = 0; 105 SL->NumConcatenated = NumStrs; 106 return SL; 107} 108 109StringLiteral* StringLiteral::Clone(ASTContext &C) const { 110 return Create(C, StrData, ByteLength, IsWide, getType(), 111 TokLocs, NumConcatenated); 112} 113 114void StringLiteral::Destroy(ASTContext &C) { 115 C.Deallocate(const_cast<char*>(StrData)); 116 this->~StringLiteral(); 117 C.Deallocate(this); 118} 119 120void StringLiteral::setStrData(ASTContext &C, const char *Str, unsigned Len) { 121 if (StrData) 122 C.Deallocate(const_cast<char*>(StrData)); 123 124 char *AStrData = new (C, 1) char[Len]; 125 memcpy(AStrData, Str, Len); 126 StrData = AStrData; 127 ByteLength = Len; 128} 129 130/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it 131/// corresponds to, e.g. "sizeof" or "[pre]++". 132const char *UnaryOperator::getOpcodeStr(Opcode Op) { 133 switch (Op) { 134 default: assert(0 && "Unknown unary operator"); 135 case PostInc: return "++"; 136 case PostDec: return "--"; 137 case PreInc: return "++"; 138 case PreDec: return "--"; 139 case AddrOf: return "&"; 140 case Deref: return "*"; 141 case Plus: return "+"; 142 case Minus: return "-"; 143 case Not: return "~"; 144 case LNot: return "!"; 145 case Real: return "__real"; 146 case Imag: return "__imag"; 147 case Extension: return "__extension__"; 148 case OffsetOf: return "__builtin_offsetof"; 149 } 150} 151 152UnaryOperator::Opcode 153UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) { 154 switch (OO) { 155 default: assert(false && "No unary operator for overloaded function"); 156 case OO_PlusPlus: return Postfix ? PostInc : PreInc; 157 case OO_MinusMinus: return Postfix ? PostDec : PreDec; 158 case OO_Amp: return AddrOf; 159 case OO_Star: return Deref; 160 case OO_Plus: return Plus; 161 case OO_Minus: return Minus; 162 case OO_Tilde: return Not; 163 case OO_Exclaim: return LNot; 164 } 165} 166 167OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) { 168 switch (Opc) { 169 case PostInc: case PreInc: return OO_PlusPlus; 170 case PostDec: case PreDec: return OO_MinusMinus; 171 case AddrOf: return OO_Amp; 172 case Deref: return OO_Star; 173 case Plus: return OO_Plus; 174 case Minus: return OO_Minus; 175 case Not: return OO_Tilde; 176 case LNot: return OO_Exclaim; 177 default: return OO_None; 178 } 179} 180 181 182//===----------------------------------------------------------------------===// 183// Postfix Operators. 184//===----------------------------------------------------------------------===// 185 186CallExpr::CallExpr(ASTContext& C, StmtClass SC, Expr *fn, Expr **args, 187 unsigned numargs, QualType t, SourceLocation rparenloc) 188 : Expr(SC, t, 189 fn->isTypeDependent() || hasAnyTypeDependentArguments(args, numargs), 190 fn->isValueDependent() || hasAnyValueDependentArguments(args,numargs)), 191 NumArgs(numargs) { 192 193 SubExprs = new (C) Stmt*[numargs+1]; 194 SubExprs[FN] = fn; 195 for (unsigned i = 0; i != numargs; ++i) 196 SubExprs[i+ARGS_START] = args[i]; 197 198 RParenLoc = rparenloc; 199} 200 201CallExpr::CallExpr(ASTContext& C, Expr *fn, Expr **args, unsigned numargs, 202 QualType t, SourceLocation rparenloc) 203 : Expr(CallExprClass, t, 204 fn->isTypeDependent() || hasAnyTypeDependentArguments(args, numargs), 205 fn->isValueDependent() || hasAnyValueDependentArguments(args,numargs)), 206 NumArgs(numargs) { 207 208 SubExprs = new (C) Stmt*[numargs+1]; 209 SubExprs[FN] = fn; 210 for (unsigned i = 0; i != numargs; ++i) 211 SubExprs[i+ARGS_START] = args[i]; 212 213 RParenLoc = rparenloc; 214} 215 216CallExpr::CallExpr(ASTContext &C, EmptyShell Empty) 217 : Expr(CallExprClass, Empty), SubExprs(0), NumArgs(0) { 218 SubExprs = new (C) Stmt*[1]; 219} 220 221void CallExpr::Destroy(ASTContext& C) { 222 DestroyChildren(C); 223 if (SubExprs) C.Deallocate(SubExprs); 224 this->~CallExpr(); 225 C.Deallocate(this); 226} 227 228/// setNumArgs - This changes the number of arguments present in this call. 229/// Any orphaned expressions are deleted by this, and any new operands are set 230/// to null. 231void CallExpr::setNumArgs(ASTContext& C, unsigned NumArgs) { 232 // No change, just return. 233 if (NumArgs == getNumArgs()) return; 234 235 // If shrinking # arguments, just delete the extras and forgot them. 236 if (NumArgs < getNumArgs()) { 237 for (unsigned i = NumArgs, e = getNumArgs(); i != e; ++i) 238 getArg(i)->Destroy(C); 239 this->NumArgs = NumArgs; 240 return; 241 } 242 243 // Otherwise, we are growing the # arguments. New an bigger argument array. 244 Stmt **NewSubExprs = new Stmt*[NumArgs+1]; 245 // Copy over args. 246 for (unsigned i = 0; i != getNumArgs()+ARGS_START; ++i) 247 NewSubExprs[i] = SubExprs[i]; 248 // Null out new args. 249 for (unsigned i = getNumArgs()+ARGS_START; i != NumArgs+ARGS_START; ++i) 250 NewSubExprs[i] = 0; 251 252 if (SubExprs) C.Deallocate(SubExprs); 253 SubExprs = NewSubExprs; 254 this->NumArgs = NumArgs; 255} 256 257/// isBuiltinCall - If this is a call to a builtin, return the builtin ID. If 258/// not, return 0. 259unsigned CallExpr::isBuiltinCall(ASTContext &Context) const { 260 // All simple function calls (e.g. func()) are implicitly cast to pointer to 261 // function. As a result, we try and obtain the DeclRefExpr from the 262 // ImplicitCastExpr. 263 const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee()); 264 if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()). 265 return 0; 266 267 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()); 268 if (!DRE) 269 return 0; 270 271 const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl()); 272 if (!FDecl) 273 return 0; 274 275 if (!FDecl->getIdentifier()) 276 return 0; 277 278 return FDecl->getBuiltinID(Context); 279} 280 281QualType CallExpr::getCallReturnType() const { 282 QualType CalleeType = getCallee()->getType(); 283 if (const PointerType *FnTypePtr = CalleeType->getAsPointerType()) 284 CalleeType = FnTypePtr->getPointeeType(); 285 else if (const BlockPointerType *BPT = CalleeType->getAsBlockPointerType()) 286 CalleeType = BPT->getPointeeType(); 287 288 const FunctionType *FnType = CalleeType->getAsFunctionType(); 289 return FnType->getResultType(); 290} 291 292/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it 293/// corresponds to, e.g. "<<=". 294const char *BinaryOperator::getOpcodeStr(Opcode Op) { 295 switch (Op) { 296 case PtrMemD: return ".*"; 297 case PtrMemI: return "->*"; 298 case Mul: return "*"; 299 case Div: return "/"; 300 case Rem: return "%"; 301 case Add: return "+"; 302 case Sub: return "-"; 303 case Shl: return "<<"; 304 case Shr: return ">>"; 305 case LT: return "<"; 306 case GT: return ">"; 307 case LE: return "<="; 308 case GE: return ">="; 309 case EQ: return "=="; 310 case NE: return "!="; 311 case And: return "&"; 312 case Xor: return "^"; 313 case Or: return "|"; 314 case LAnd: return "&&"; 315 case LOr: return "||"; 316 case Assign: return "="; 317 case MulAssign: return "*="; 318 case DivAssign: return "/="; 319 case RemAssign: return "%="; 320 case AddAssign: return "+="; 321 case SubAssign: return "-="; 322 case ShlAssign: return "<<="; 323 case ShrAssign: return ">>="; 324 case AndAssign: return "&="; 325 case XorAssign: return "^="; 326 case OrAssign: return "|="; 327 case Comma: return ","; 328 } 329 330 return ""; 331} 332 333BinaryOperator::Opcode 334BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) { 335 switch (OO) { 336 default: assert(false && "Not an overloadable binary operator"); 337 case OO_Plus: return Add; 338 case OO_Minus: return Sub; 339 case OO_Star: return Mul; 340 case OO_Slash: return Div; 341 case OO_Percent: return Rem; 342 case OO_Caret: return Xor; 343 case OO_Amp: return And; 344 case OO_Pipe: return Or; 345 case OO_Equal: return Assign; 346 case OO_Less: return LT; 347 case OO_Greater: return GT; 348 case OO_PlusEqual: return AddAssign; 349 case OO_MinusEqual: return SubAssign; 350 case OO_StarEqual: return MulAssign; 351 case OO_SlashEqual: return DivAssign; 352 case OO_PercentEqual: return RemAssign; 353 case OO_CaretEqual: return XorAssign; 354 case OO_AmpEqual: return AndAssign; 355 case OO_PipeEqual: return OrAssign; 356 case OO_LessLess: return Shl; 357 case OO_GreaterGreater: return Shr; 358 case OO_LessLessEqual: return ShlAssign; 359 case OO_GreaterGreaterEqual: return ShrAssign; 360 case OO_EqualEqual: return EQ; 361 case OO_ExclaimEqual: return NE; 362 case OO_LessEqual: return LE; 363 case OO_GreaterEqual: return GE; 364 case OO_AmpAmp: return LAnd; 365 case OO_PipePipe: return LOr; 366 case OO_Comma: return Comma; 367 case OO_ArrowStar: return PtrMemI; 368 } 369} 370 371OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) { 372 static const OverloadedOperatorKind OverOps[] = { 373 /* .* Cannot be overloaded */OO_None, OO_ArrowStar, 374 OO_Star, OO_Slash, OO_Percent, 375 OO_Plus, OO_Minus, 376 OO_LessLess, OO_GreaterGreater, 377 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual, 378 OO_EqualEqual, OO_ExclaimEqual, 379 OO_Amp, 380 OO_Caret, 381 OO_Pipe, 382 OO_AmpAmp, 383 OO_PipePipe, 384 OO_Equal, OO_StarEqual, 385 OO_SlashEqual, OO_PercentEqual, 386 OO_PlusEqual, OO_MinusEqual, 387 OO_LessLessEqual, OO_GreaterGreaterEqual, 388 OO_AmpEqual, OO_CaretEqual, 389 OO_PipeEqual, 390 OO_Comma 391 }; 392 return OverOps[Opc]; 393} 394 395InitListExpr::InitListExpr(SourceLocation lbraceloc, 396 Expr **initExprs, unsigned numInits, 397 SourceLocation rbraceloc) 398 : Expr(InitListExprClass, QualType(), 399 hasAnyTypeDependentArguments(initExprs, numInits), 400 hasAnyValueDependentArguments(initExprs, numInits)), 401 LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), SyntacticForm(0), 402 UnionFieldInit(0), HadArrayRangeDesignator(false) { 403 404 InitExprs.insert(InitExprs.end(), initExprs, initExprs+numInits); 405} 406 407void InitListExpr::reserveInits(unsigned NumInits) { 408 if (NumInits > InitExprs.size()) 409 InitExprs.reserve(NumInits); 410} 411 412void InitListExpr::resizeInits(ASTContext &Context, unsigned NumInits) { 413 for (unsigned Idx = NumInits, LastIdx = InitExprs.size(); 414 Idx < LastIdx; ++Idx) 415 InitExprs[Idx]->Destroy(Context); 416 InitExprs.resize(NumInits, 0); 417} 418 419Expr *InitListExpr::updateInit(unsigned Init, Expr *expr) { 420 if (Init >= InitExprs.size()) { 421 InitExprs.insert(InitExprs.end(), Init - InitExprs.size() + 1, 0); 422 InitExprs.back() = expr; 423 return 0; 424 } 425 426 Expr *Result = cast_or_null<Expr>(InitExprs[Init]); 427 InitExprs[Init] = expr; 428 return Result; 429} 430 431/// getFunctionType - Return the underlying function type for this block. 432/// 433const FunctionType *BlockExpr::getFunctionType() const { 434 return getType()->getAsBlockPointerType()-> 435 getPointeeType()->getAsFunctionType(); 436} 437 438SourceLocation BlockExpr::getCaretLocation() const { 439 return TheBlock->getCaretLocation(); 440} 441const Stmt *BlockExpr::getBody() const { 442 return TheBlock->getBody(); 443} 444Stmt *BlockExpr::getBody() { 445 return TheBlock->getBody(); 446} 447 448 449//===----------------------------------------------------------------------===// 450// Generic Expression Routines 451//===----------------------------------------------------------------------===// 452 453/// isUnusedResultAWarning - Return true if this immediate expression should 454/// be warned about if the result is unused. If so, fill in Loc and Ranges 455/// with location to warn on and the source range[s] to report with the 456/// warning. 457bool Expr::isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1, 458 SourceRange &R2) const { 459 // Don't warn if the expr is type dependent. The type could end up 460 // instantiating to void. 461 if (isTypeDependent()) 462 return false; 463 464 switch (getStmtClass()) { 465 default: 466 Loc = getExprLoc(); 467 R1 = getSourceRange(); 468 return true; 469 case ParenExprClass: 470 return cast<ParenExpr>(this)->getSubExpr()-> 471 isUnusedResultAWarning(Loc, R1, R2); 472 case UnaryOperatorClass: { 473 const UnaryOperator *UO = cast<UnaryOperator>(this); 474 475 switch (UO->getOpcode()) { 476 default: break; 477 case UnaryOperator::PostInc: 478 case UnaryOperator::PostDec: 479 case UnaryOperator::PreInc: 480 case UnaryOperator::PreDec: // ++/-- 481 return false; // Not a warning. 482 case UnaryOperator::Deref: 483 // Dereferencing a volatile pointer is a side-effect. 484 if (getType().isVolatileQualified()) 485 return false; 486 break; 487 case UnaryOperator::Real: 488 case UnaryOperator::Imag: 489 // accessing a piece of a volatile complex is a side-effect. 490 if (UO->getSubExpr()->getType().isVolatileQualified()) 491 return false; 492 break; 493 case UnaryOperator::Extension: 494 return UO->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2); 495 } 496 Loc = UO->getOperatorLoc(); 497 R1 = UO->getSubExpr()->getSourceRange(); 498 return true; 499 } 500 case BinaryOperatorClass: { 501 const BinaryOperator *BO = cast<BinaryOperator>(this); 502 // Consider comma to have side effects if the LHS or RHS does. 503 if (BO->getOpcode() == BinaryOperator::Comma) 504 return BO->getRHS()->isUnusedResultAWarning(Loc, R1, R2) || 505 BO->getLHS()->isUnusedResultAWarning(Loc, R1, R2); 506 507 if (BO->isAssignmentOp()) 508 return false; 509 Loc = BO->getOperatorLoc(); 510 R1 = BO->getLHS()->getSourceRange(); 511 R2 = BO->getRHS()->getSourceRange(); 512 return true; 513 } 514 case CompoundAssignOperatorClass: 515 return false; 516 517 case ConditionalOperatorClass: { 518 // The condition must be evaluated, but if either the LHS or RHS is a 519 // warning, warn about them. 520 const ConditionalOperator *Exp = cast<ConditionalOperator>(this); 521 if (Exp->getLHS() && 522 Exp->getLHS()->isUnusedResultAWarning(Loc, R1, R2)) 523 return true; 524 return Exp->getRHS()->isUnusedResultAWarning(Loc, R1, R2); 525 } 526 527 case MemberExprClass: 528 // If the base pointer or element is to a volatile pointer/field, accessing 529 // it is a side effect. 530 if (getType().isVolatileQualified()) 531 return false; 532 Loc = cast<MemberExpr>(this)->getMemberLoc(); 533 R1 = SourceRange(Loc, Loc); 534 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange(); 535 return true; 536 537 case ArraySubscriptExprClass: 538 // If the base pointer or element is to a volatile pointer/field, accessing 539 // it is a side effect. 540 if (getType().isVolatileQualified()) 541 return false; 542 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc(); 543 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange(); 544 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange(); 545 return true; 546 547 case CallExprClass: 548 case CXXOperatorCallExprClass: 549 case CXXMemberCallExprClass: { 550 // If this is a direct call, get the callee. 551 const CallExpr *CE = cast<CallExpr>(this); 552 const Expr *CalleeExpr = CE->getCallee()->IgnoreParenCasts(); 553 if (const DeclRefExpr *CalleeDRE = dyn_cast<DeclRefExpr>(CalleeExpr)) { 554 // If the callee has attribute pure, const, or warn_unused_result, warn 555 // about it. void foo() { strlen("bar"); } should warn. 556 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CalleeDRE->getDecl())) 557 if (FD->getAttr<WarnUnusedResultAttr>() || 558 FD->getAttr<PureAttr>() || FD->getAttr<ConstAttr>()) { 559 Loc = CE->getCallee()->getLocStart(); 560 R1 = CE->getCallee()->getSourceRange(); 561 562 if (unsigned NumArgs = CE->getNumArgs()) 563 R2 = SourceRange(CE->getArg(0)->getLocStart(), 564 CE->getArg(NumArgs-1)->getLocEnd()); 565 return true; 566 } 567 } 568 return false; 569 } 570 case ObjCMessageExprClass: 571 return false; 572 case StmtExprClass: { 573 // Statement exprs don't logically have side effects themselves, but are 574 // sometimes used in macros in ways that give them a type that is unused. 575 // For example ({ blah; foo(); }) will end up with a type if foo has a type. 576 // however, if the result of the stmt expr is dead, we don't want to emit a 577 // warning. 578 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt(); 579 if (!CS->body_empty()) 580 if (const Expr *E = dyn_cast<Expr>(CS->body_back())) 581 return E->isUnusedResultAWarning(Loc, R1, R2); 582 583 Loc = cast<StmtExpr>(this)->getLParenLoc(); 584 R1 = getSourceRange(); 585 return true; 586 } 587 case CStyleCastExprClass: 588 // If this is a cast to void, check the operand. Otherwise, the result of 589 // the cast is unused. 590 if (getType()->isVoidType()) 591 return cast<CastExpr>(this)->getSubExpr() 592 ->isUnusedResultAWarning(Loc, R1, R2); 593 Loc = cast<CStyleCastExpr>(this)->getLParenLoc(); 594 R1 = cast<CStyleCastExpr>(this)->getSubExpr()->getSourceRange(); 595 return true; 596 case CXXFunctionalCastExprClass: 597 // If this is a cast to void, check the operand. Otherwise, the result of 598 // the cast is unused. 599 if (getType()->isVoidType()) 600 return cast<CastExpr>(this)->getSubExpr() 601 ->isUnusedResultAWarning(Loc, R1, R2); 602 Loc = cast<CXXFunctionalCastExpr>(this)->getTypeBeginLoc(); 603 R1 = cast<CXXFunctionalCastExpr>(this)->getSubExpr()->getSourceRange(); 604 return true; 605 606 case ImplicitCastExprClass: 607 // Check the operand, since implicit casts are inserted by Sema 608 return cast<ImplicitCastExpr>(this) 609 ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2); 610 611 case CXXDefaultArgExprClass: 612 return cast<CXXDefaultArgExpr>(this) 613 ->getExpr()->isUnusedResultAWarning(Loc, R1, R2); 614 615 case CXXNewExprClass: 616 // FIXME: In theory, there might be new expressions that don't have side 617 // effects (e.g. a placement new with an uninitialized POD). 618 case CXXDeleteExprClass: 619 return false; 620 case CXXExprWithTemporariesClass: 621 return cast<CXXExprWithTemporaries>(this) 622 ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2); 623 } 624} 625 626/// DeclCanBeLvalue - Determine whether the given declaration can be 627/// an lvalue. This is a helper routine for isLvalue. 628static bool DeclCanBeLvalue(const NamedDecl *Decl, ASTContext &Ctx) { 629 // C++ [temp.param]p6: 630 // A non-type non-reference template-parameter is not an lvalue. 631 if (const NonTypeTemplateParmDecl *NTTParm 632 = dyn_cast<NonTypeTemplateParmDecl>(Decl)) 633 return NTTParm->getType()->isReferenceType(); 634 635 return isa<VarDecl>(Decl) || isa<FieldDecl>(Decl) || 636 // C++ 3.10p2: An lvalue refers to an object or function. 637 (Ctx.getLangOptions().CPlusPlus && 638 (isa<FunctionDecl>(Decl) || isa<OverloadedFunctionDecl>(Decl))); 639} 640 641/// isLvalue - C99 6.3.2.1: an lvalue is an expression with an object type or an 642/// incomplete type other than void. Nonarray expressions that can be lvalues: 643/// - name, where name must be a variable 644/// - e[i] 645/// - (e), where e must be an lvalue 646/// - e.name, where e must be an lvalue 647/// - e->name 648/// - *e, the type of e cannot be a function type 649/// - string-constant 650/// - (__real__ e) and (__imag__ e) where e is an lvalue [GNU extension] 651/// - reference type [C++ [expr]] 652/// 653Expr::isLvalueResult Expr::isLvalue(ASTContext &Ctx) const { 654 assert(!TR->isReferenceType() && "Expressions can't have reference type."); 655 656 isLvalueResult Res = isLvalueInternal(Ctx); 657 if (Res != LV_Valid || Ctx.getLangOptions().CPlusPlus) 658 return Res; 659 660 // first, check the type (C99 6.3.2.1). Expressions with function 661 // type in C are not lvalues, but they can be lvalues in C++. 662 if (TR->isFunctionType()) 663 return LV_NotObjectType; 664 665 // Allow qualified void which is an incomplete type other than void (yuck). 666 if (TR->isVoidType() && !Ctx.getCanonicalType(TR).getCVRQualifiers()) 667 return LV_IncompleteVoidType; 668 669 return LV_Valid; 670} 671 672// Check whether the expression can be sanely treated like an l-value 673Expr::isLvalueResult Expr::isLvalueInternal(ASTContext &Ctx) const { 674 switch (getStmtClass()) { 675 case StringLiteralClass: // C99 6.5.1p4 676 case ObjCEncodeExprClass: // @encode behaves like its string in every way. 677 return LV_Valid; 678 case ArraySubscriptExprClass: // C99 6.5.3p4 (e1[e2] == (*((e1)+(e2)))) 679 // For vectors, make sure base is an lvalue (i.e. not a function call). 680 if (cast<ArraySubscriptExpr>(this)->getBase()->getType()->isVectorType()) 681 return cast<ArraySubscriptExpr>(this)->getBase()->isLvalue(Ctx); 682 return LV_Valid; 683 case DeclRefExprClass: 684 case QualifiedDeclRefExprClass: { // C99 6.5.1p2 685 const NamedDecl *RefdDecl = cast<DeclRefExpr>(this)->getDecl(); 686 if (DeclCanBeLvalue(RefdDecl, Ctx)) 687 return LV_Valid; 688 break; 689 } 690 case BlockDeclRefExprClass: { 691 const BlockDeclRefExpr *BDR = cast<BlockDeclRefExpr>(this); 692 if (isa<VarDecl>(BDR->getDecl())) 693 return LV_Valid; 694 break; 695 } 696 case MemberExprClass: { 697 const MemberExpr *m = cast<MemberExpr>(this); 698 if (Ctx.getLangOptions().CPlusPlus) { // C++ [expr.ref]p4: 699 NamedDecl *Member = m->getMemberDecl(); 700 // C++ [expr.ref]p4: 701 // If E2 is declared to have type "reference to T", then E1.E2 702 // is an lvalue. 703 if (ValueDecl *Value = dyn_cast<ValueDecl>(Member)) 704 if (Value->getType()->isReferenceType()) 705 return LV_Valid; 706 707 // -- If E2 is a static data member [...] then E1.E2 is an lvalue. 708 if (isa<VarDecl>(Member) && Member->getDeclContext()->isRecord()) 709 return LV_Valid; 710 711 // -- If E2 is a non-static data member [...]. If E1 is an 712 // lvalue, then E1.E2 is an lvalue. 713 if (isa<FieldDecl>(Member)) 714 return m->isArrow() ? LV_Valid : m->getBase()->isLvalue(Ctx); 715 716 // -- If it refers to a static member function [...], then 717 // E1.E2 is an lvalue. 718 // -- Otherwise, if E1.E2 refers to a non-static member 719 // function [...], then E1.E2 is not an lvalue. 720 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) 721 return Method->isStatic()? LV_Valid : LV_MemberFunction; 722 723 // -- If E2 is a member enumerator [...], the expression E1.E2 724 // is not an lvalue. 725 if (isa<EnumConstantDecl>(Member)) 726 return LV_InvalidExpression; 727 728 // Not an lvalue. 729 return LV_InvalidExpression; 730 } 731 732 // C99 6.5.2.3p4 733 return m->isArrow() ? LV_Valid : m->getBase()->isLvalue(Ctx); 734 } 735 case UnaryOperatorClass: 736 if (cast<UnaryOperator>(this)->getOpcode() == UnaryOperator::Deref) 737 return LV_Valid; // C99 6.5.3p4 738 739 if (cast<UnaryOperator>(this)->getOpcode() == UnaryOperator::Real || 740 cast<UnaryOperator>(this)->getOpcode() == UnaryOperator::Imag || 741 cast<UnaryOperator>(this)->getOpcode() == UnaryOperator::Extension) 742 return cast<UnaryOperator>(this)->getSubExpr()->isLvalue(Ctx); // GNU. 743 744 if (Ctx.getLangOptions().CPlusPlus && // C++ [expr.pre.incr]p1 745 (cast<UnaryOperator>(this)->getOpcode() == UnaryOperator::PreInc || 746 cast<UnaryOperator>(this)->getOpcode() == UnaryOperator::PreDec)) 747 return LV_Valid; 748 break; 749 case ImplicitCastExprClass: 750 return cast<ImplicitCastExpr>(this)->isLvalueCast()? LV_Valid 751 : LV_InvalidExpression; 752 case ParenExprClass: // C99 6.5.1p5 753 return cast<ParenExpr>(this)->getSubExpr()->isLvalue(Ctx); 754 case BinaryOperatorClass: 755 case CompoundAssignOperatorClass: { 756 const BinaryOperator *BinOp = cast<BinaryOperator>(this); 757 758 if (Ctx.getLangOptions().CPlusPlus && // C++ [expr.comma]p1 759 BinOp->getOpcode() == BinaryOperator::Comma) 760 return BinOp->getRHS()->isLvalue(Ctx); 761 762 // C++ [expr.mptr.oper]p6 763 if ((BinOp->getOpcode() == BinaryOperator::PtrMemD || 764 BinOp->getOpcode() == BinaryOperator::PtrMemI) && 765 !BinOp->getType()->isFunctionType()) 766 return BinOp->getLHS()->isLvalue(Ctx); 767 768 if (!BinOp->isAssignmentOp()) 769 return LV_InvalidExpression; 770 771 if (Ctx.getLangOptions().CPlusPlus) 772 // C++ [expr.ass]p1: 773 // The result of an assignment operation [...] is an lvalue. 774 return LV_Valid; 775 776 777 // C99 6.5.16: 778 // An assignment expression [...] is not an lvalue. 779 return LV_InvalidExpression; 780 } 781 case CallExprClass: 782 case CXXOperatorCallExprClass: 783 case CXXMemberCallExprClass: { 784 // C++0x [expr.call]p10 785 // A function call is an lvalue if and only if the result type 786 // is an lvalue reference. 787 QualType ReturnType = cast<CallExpr>(this)->getCallReturnType(); 788 if (ReturnType->isLValueReferenceType()) 789 return LV_Valid; 790 791 break; 792 } 793 case CompoundLiteralExprClass: // C99 6.5.2.5p5 794 return LV_Valid; 795 case ChooseExprClass: 796 // __builtin_choose_expr is an lvalue if the selected operand is. 797 return cast<ChooseExpr>(this)->getChosenSubExpr(Ctx)->isLvalue(Ctx); 798 case ExtVectorElementExprClass: 799 if (cast<ExtVectorElementExpr>(this)->containsDuplicateElements()) 800 return LV_DuplicateVectorComponents; 801 return LV_Valid; 802 case ObjCIvarRefExprClass: // ObjC instance variables are lvalues. 803 return LV_Valid; 804 case ObjCPropertyRefExprClass: // FIXME: check if read-only property. 805 return LV_Valid; 806 case ObjCKVCRefExprClass: // FIXME: check if read-only property. 807 return LV_Valid; 808 case PredefinedExprClass: 809 return LV_Valid; 810 case CXXDefaultArgExprClass: 811 return cast<CXXDefaultArgExpr>(this)->getExpr()->isLvalue(Ctx); 812 case CXXConditionDeclExprClass: 813 return LV_Valid; 814 case CStyleCastExprClass: 815 case CXXFunctionalCastExprClass: 816 case CXXStaticCastExprClass: 817 case CXXDynamicCastExprClass: 818 case CXXReinterpretCastExprClass: 819 case CXXConstCastExprClass: 820 // The result of an explicit cast is an lvalue if the type we are 821 // casting to is an lvalue reference type. See C++ [expr.cast]p1, 822 // C++ [expr.static.cast]p2, C++ [expr.dynamic.cast]p2, 823 // C++ [expr.reinterpret.cast]p1, C++ [expr.const.cast]p1. 824 if (cast<ExplicitCastExpr>(this)->getTypeAsWritten()-> 825 isLValueReferenceType()) 826 return LV_Valid; 827 break; 828 case CXXTypeidExprClass: 829 // C++ 5.2.8p1: The result of a typeid expression is an lvalue of ... 830 return LV_Valid; 831 case ConditionalOperatorClass: { 832 // Complicated handling is only for C++. 833 if (!Ctx.getLangOptions().CPlusPlus) 834 return LV_InvalidExpression; 835 836 // Sema should have taken care to ensure that a CXXTemporaryObjectExpr is 837 // everywhere there's an object converted to an rvalue. Also, any other 838 // casts should be wrapped by ImplicitCastExprs. There's just the special 839 // case involving throws to work out. 840 const ConditionalOperator *Cond = cast<ConditionalOperator>(this); 841 Expr *True = Cond->getTrueExpr(); 842 Expr *False = Cond->getFalseExpr(); 843 // C++0x 5.16p2 844 // If either the second or the third operand has type (cv) void, [...] 845 // the result [...] is an rvalue. 846 if (True->getType()->isVoidType() || False->getType()->isVoidType()) 847 return LV_InvalidExpression; 848 849 // Both sides must be lvalues for the result to be an lvalue. 850 if (True->isLvalue(Ctx) != LV_Valid || False->isLvalue(Ctx) != LV_Valid) 851 return LV_InvalidExpression; 852 853 // That's it. 854 return LV_Valid; 855 } 856 857 default: 858 break; 859 } 860 return LV_InvalidExpression; 861} 862 863/// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type, 864/// does not have an incomplete type, does not have a const-qualified type, and 865/// if it is a structure or union, does not have any member (including, 866/// recursively, any member or element of all contained aggregates or unions) 867/// with a const-qualified type. 868Expr::isModifiableLvalueResult 869Expr::isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc) const { 870 isLvalueResult lvalResult = isLvalue(Ctx); 871 872 switch (lvalResult) { 873 case LV_Valid: 874 // C++ 3.10p11: Functions cannot be modified, but pointers to 875 // functions can be modifiable. 876 if (Ctx.getLangOptions().CPlusPlus && TR->isFunctionType()) 877 return MLV_NotObjectType; 878 break; 879 880 case LV_NotObjectType: return MLV_NotObjectType; 881 case LV_IncompleteVoidType: return MLV_IncompleteVoidType; 882 case LV_DuplicateVectorComponents: return MLV_DuplicateVectorComponents; 883 case LV_InvalidExpression: 884 // If the top level is a C-style cast, and the subexpression is a valid 885 // lvalue, then this is probably a use of the old-school "cast as lvalue" 886 // GCC extension. We don't support it, but we want to produce good 887 // diagnostics when it happens so that the user knows why. 888 if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(IgnoreParens())) { 889 if (CE->getSubExpr()->isLvalue(Ctx) == LV_Valid) { 890 if (Loc) 891 *Loc = CE->getLParenLoc(); 892 return MLV_LValueCast; 893 } 894 } 895 return MLV_InvalidExpression; 896 case LV_MemberFunction: return MLV_MemberFunction; 897 } 898 899 // The following is illegal: 900 // void takeclosure(void (^C)(void)); 901 // void func() { int x = 1; takeclosure(^{ x = 7; }); } 902 // 903 if (isa<BlockDeclRefExpr>(this)) { 904 const BlockDeclRefExpr *BDR = cast<BlockDeclRefExpr>(this); 905 if (!BDR->isByRef() && isa<VarDecl>(BDR->getDecl())) 906 return MLV_NotBlockQualified; 907 } 908 909 QualType CT = Ctx.getCanonicalType(getType()); 910 911 if (CT.isConstQualified()) 912 return MLV_ConstQualified; 913 if (CT->isArrayType()) 914 return MLV_ArrayType; 915 if (CT->isIncompleteType()) 916 return MLV_IncompleteType; 917 918 if (const RecordType *r = CT->getAsRecordType()) { 919 if (r->hasConstFields()) 920 return MLV_ConstQualified; 921 } 922 923 // Assigning to an 'implicit' property? 924 else if (isa<ObjCKVCRefExpr>(this)) { 925 const ObjCKVCRefExpr* KVCExpr = cast<ObjCKVCRefExpr>(this); 926 if (KVCExpr->getSetterMethod() == 0) 927 return MLV_NoSetterProperty; 928 } 929 return MLV_Valid; 930} 931 932/// hasGlobalStorage - Return true if this expression has static storage 933/// duration. This means that the address of this expression is a link-time 934/// constant. 935bool Expr::hasGlobalStorage() const { 936 switch (getStmtClass()) { 937 default: 938 return false; 939 case BlockExprClass: 940 return true; 941 case ParenExprClass: 942 return cast<ParenExpr>(this)->getSubExpr()->hasGlobalStorage(); 943 case ImplicitCastExprClass: 944 return cast<ImplicitCastExpr>(this)->getSubExpr()->hasGlobalStorage(); 945 case CompoundLiteralExprClass: 946 return cast<CompoundLiteralExpr>(this)->isFileScope(); 947 case DeclRefExprClass: 948 case QualifiedDeclRefExprClass: { 949 const Decl *D = cast<DeclRefExpr>(this)->getDecl(); 950 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 951 return VD->hasGlobalStorage(); 952 if (isa<FunctionDecl>(D)) 953 return true; 954 return false; 955 } 956 case MemberExprClass: { 957 const MemberExpr *M = cast<MemberExpr>(this); 958 return !M->isArrow() && M->getBase()->hasGlobalStorage(); 959 } 960 case ArraySubscriptExprClass: 961 return cast<ArraySubscriptExpr>(this)->getBase()->hasGlobalStorage(); 962 case PredefinedExprClass: 963 return true; 964 case CXXDefaultArgExprClass: 965 return cast<CXXDefaultArgExpr>(this)->getExpr()->hasGlobalStorage(); 966 } 967} 968 969/// isOBJCGCCandidate - Check if an expression is objc gc'able. 970/// 971bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const { 972 switch (getStmtClass()) { 973 default: 974 return false; 975 case ObjCIvarRefExprClass: 976 return true; 977 case Expr::UnaryOperatorClass: 978 return cast<UnaryOperator>(this)->getSubExpr()->isOBJCGCCandidate(Ctx); 979 case ParenExprClass: 980 return cast<ParenExpr>(this)->getSubExpr()->isOBJCGCCandidate(Ctx); 981 case ImplicitCastExprClass: 982 return cast<ImplicitCastExpr>(this)->getSubExpr()->isOBJCGCCandidate(Ctx); 983 case CStyleCastExprClass: 984 return cast<CStyleCastExpr>(this)->getSubExpr()->isOBJCGCCandidate(Ctx); 985 case DeclRefExprClass: 986 case QualifiedDeclRefExprClass: { 987 const Decl *D = cast<DeclRefExpr>(this)->getDecl(); 988 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 989 if (VD->hasGlobalStorage()) 990 return true; 991 QualType T = VD->getType(); 992 // dereferencing to an object pointer is always a gc'able candidate 993 if (T->isPointerType() && 994 Ctx.isObjCObjectPointerType(T->getAsPointerType()->getPointeeType())) 995 return true; 996 997 } 998 return false; 999 } 1000 case MemberExprClass: { 1001 const MemberExpr *M = cast<MemberExpr>(this); 1002 return M->getBase()->isOBJCGCCandidate(Ctx); 1003 } 1004 case ArraySubscriptExprClass: 1005 return cast<ArraySubscriptExpr>(this)->getBase()->isOBJCGCCandidate(Ctx); 1006 } 1007} 1008Expr* Expr::IgnoreParens() { 1009 Expr* E = this; 1010 while (ParenExpr* P = dyn_cast<ParenExpr>(E)) 1011 E = P->getSubExpr(); 1012 1013 return E; 1014} 1015 1016/// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr 1017/// or CastExprs or ImplicitCastExprs, returning their operand. 1018Expr *Expr::IgnoreParenCasts() { 1019 Expr *E = this; 1020 while (true) { 1021 if (ParenExpr *P = dyn_cast<ParenExpr>(E)) 1022 E = P->getSubExpr(); 1023 else if (CastExpr *P = dyn_cast<CastExpr>(E)) 1024 E = P->getSubExpr(); 1025 else 1026 return E; 1027 } 1028} 1029 1030/// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the 1031/// value (including ptr->int casts of the same size). Strip off any 1032/// ParenExpr or CastExprs, returning their operand. 1033Expr *Expr::IgnoreParenNoopCasts(ASTContext &Ctx) { 1034 Expr *E = this; 1035 while (true) { 1036 if (ParenExpr *P = dyn_cast<ParenExpr>(E)) { 1037 E = P->getSubExpr(); 1038 continue; 1039 } 1040 1041 if (CastExpr *P = dyn_cast<CastExpr>(E)) { 1042 // We ignore integer <-> casts that are of the same width, ptr<->ptr and 1043 // ptr<->int casts of the same width. We also ignore all identify casts. 1044 Expr *SE = P->getSubExpr(); 1045 1046 if (Ctx.hasSameUnqualifiedType(E->getType(), SE->getType())) { 1047 E = SE; 1048 continue; 1049 } 1050 1051 if ((E->getType()->isPointerType() || E->getType()->isIntegralType()) && 1052 (SE->getType()->isPointerType() || SE->getType()->isIntegralType()) && 1053 Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SE->getType())) { 1054 E = SE; 1055 continue; 1056 } 1057 } 1058 1059 return E; 1060 } 1061} 1062 1063 1064/// hasAnyTypeDependentArguments - Determines if any of the expressions 1065/// in Exprs is type-dependent. 1066bool Expr::hasAnyTypeDependentArguments(Expr** Exprs, unsigned NumExprs) { 1067 for (unsigned I = 0; I < NumExprs; ++I) 1068 if (Exprs[I]->isTypeDependent()) 1069 return true; 1070 1071 return false; 1072} 1073 1074/// hasAnyValueDependentArguments - Determines if any of the expressions 1075/// in Exprs is value-dependent. 1076bool Expr::hasAnyValueDependentArguments(Expr** Exprs, unsigned NumExprs) { 1077 for (unsigned I = 0; I < NumExprs; ++I) 1078 if (Exprs[I]->isValueDependent()) 1079 return true; 1080 1081 return false; 1082} 1083 1084bool Expr::isConstantInitializer(ASTContext &Ctx) const { 1085 // This function is attempting whether an expression is an initializer 1086 // which can be evaluated at compile-time. isEvaluatable handles most 1087 // of the cases, but it can't deal with some initializer-specific 1088 // expressions, and it can't deal with aggregates; we deal with those here, 1089 // and fall back to isEvaluatable for the other cases. 1090 1091 // FIXME: This function assumes the variable being assigned to 1092 // isn't a reference type! 1093 1094 switch (getStmtClass()) { 1095 default: break; 1096 case StringLiteralClass: 1097 case ObjCEncodeExprClass: 1098 return true; 1099 case CompoundLiteralExprClass: { 1100 // This handles gcc's extension that allows global initializers like 1101 // "struct x {int x;} x = (struct x) {};". 1102 // FIXME: This accepts other cases it shouldn't! 1103 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer(); 1104 return Exp->isConstantInitializer(Ctx); 1105 } 1106 case InitListExprClass: { 1107 // FIXME: This doesn't deal with fields with reference types correctly. 1108 // FIXME: This incorrectly allows pointers cast to integers to be assigned 1109 // to bitfields. 1110 const InitListExpr *Exp = cast<InitListExpr>(this); 1111 unsigned numInits = Exp->getNumInits(); 1112 for (unsigned i = 0; i < numInits; i++) { 1113 if (!Exp->getInit(i)->isConstantInitializer(Ctx)) 1114 return false; 1115 } 1116 return true; 1117 } 1118 case ImplicitValueInitExprClass: 1119 return true; 1120 case ParenExprClass: { 1121 return cast<ParenExpr>(this)->getSubExpr()->isConstantInitializer(Ctx); 1122 } 1123 case UnaryOperatorClass: { 1124 const UnaryOperator* Exp = cast<UnaryOperator>(this); 1125 if (Exp->getOpcode() == UnaryOperator::Extension) 1126 return Exp->getSubExpr()->isConstantInitializer(Ctx); 1127 break; 1128 } 1129 case ImplicitCastExprClass: 1130 case CStyleCastExprClass: 1131 // Handle casts with a destination that's a struct or union; this 1132 // deals with both the gcc no-op struct cast extension and the 1133 // cast-to-union extension. 1134 if (getType()->isRecordType()) 1135 return cast<CastExpr>(this)->getSubExpr()->isConstantInitializer(Ctx); 1136 break; 1137 } 1138 1139 return isEvaluatable(Ctx); 1140} 1141 1142/// isIntegerConstantExpr - this recursive routine will test if an expression is 1143/// an integer constant expression. 1144 1145/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 1146/// comma, etc 1147/// 1148/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof 1149/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer 1150/// cast+dereference. 1151 1152// CheckICE - This function does the fundamental ICE checking: the returned 1153// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation. 1154// Note that to reduce code duplication, this helper does no evaluation 1155// itself; the caller checks whether the expression is evaluatable, and 1156// in the rare cases where CheckICE actually cares about the evaluated 1157// value, it calls into Evalute. 1158// 1159// Meanings of Val: 1160// 0: This expression is an ICE if it can be evaluated by Evaluate. 1161// 1: This expression is not an ICE, but if it isn't evaluated, it's 1162// a legal subexpression for an ICE. This return value is used to handle 1163// the comma operator in C99 mode. 1164// 2: This expression is not an ICE, and is not a legal subexpression for one. 1165 1166struct ICEDiag { 1167 unsigned Val; 1168 SourceLocation Loc; 1169 1170 public: 1171 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {} 1172 ICEDiag() : Val(0) {} 1173}; 1174 1175ICEDiag NoDiag() { return ICEDiag(); } 1176 1177static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) { 1178 Expr::EvalResult EVResult; 1179 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects || 1180 !EVResult.Val.isInt()) { 1181 return ICEDiag(2, E->getLocStart()); 1182 } 1183 return NoDiag(); 1184} 1185 1186static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) { 1187 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 1188 if (!E->getType()->isIntegralType()) { 1189 return ICEDiag(2, E->getLocStart()); 1190 } 1191 1192 switch (E->getStmtClass()) { 1193 default: 1194 return ICEDiag(2, E->getLocStart()); 1195 case Expr::ParenExprClass: 1196 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 1197 case Expr::IntegerLiteralClass: 1198 case Expr::CharacterLiteralClass: 1199 case Expr::CXXBoolLiteralExprClass: 1200 case Expr::CXXZeroInitValueExprClass: 1201 case Expr::TypesCompatibleExprClass: 1202 case Expr::UnaryTypeTraitExprClass: 1203 return NoDiag(); 1204 case Expr::CallExprClass: 1205 case Expr::CXXOperatorCallExprClass: { 1206 const CallExpr *CE = cast<CallExpr>(E); 1207 if (CE->isBuiltinCall(Ctx)) 1208 return CheckEvalInICE(E, Ctx); 1209 return ICEDiag(2, E->getLocStart()); 1210 } 1211 case Expr::DeclRefExprClass: 1212 case Expr::QualifiedDeclRefExprClass: 1213 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl())) 1214 return NoDiag(); 1215 if (Ctx.getLangOptions().CPlusPlus && 1216 E->getType().getCVRQualifiers() == QualType::Const) { 1217 // C++ 7.1.5.1p2 1218 // A variable of non-volatile const-qualified integral or enumeration 1219 // type initialized by an ICE can be used in ICEs. 1220 if (const VarDecl *Dcl = 1221 dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 1222 if (Dcl->isInitKnownICE()) { 1223 // We have already checked whether this subexpression is an 1224 // integral constant expression. 1225 if (Dcl->isInitICE()) 1226 return NoDiag(); 1227 else 1228 return ICEDiag(2, E->getLocStart()); 1229 } 1230 1231 if (const Expr *Init = Dcl->getInit()) { 1232 ICEDiag Result = CheckICE(Init, Ctx); 1233 // Cache the result of the ICE test. 1234 Dcl->setInitKnownICE(Ctx, Result.Val == 0); 1235 return Result; 1236 } 1237 } 1238 } 1239 return ICEDiag(2, E->getLocStart()); 1240 case Expr::UnaryOperatorClass: { 1241 const UnaryOperator *Exp = cast<UnaryOperator>(E); 1242 switch (Exp->getOpcode()) { 1243 default: 1244 return ICEDiag(2, E->getLocStart()); 1245 case UnaryOperator::Extension: 1246 case UnaryOperator::LNot: 1247 case UnaryOperator::Plus: 1248 case UnaryOperator::Minus: 1249 case UnaryOperator::Not: 1250 case UnaryOperator::Real: 1251 case UnaryOperator::Imag: 1252 return CheckICE(Exp->getSubExpr(), Ctx); 1253 case UnaryOperator::OffsetOf: 1254 // Note that per C99, offsetof must be an ICE. And AFAIK, using 1255 // Evaluate matches the proposed gcc behavior for cases like 1256 // "offsetof(struct s{int x[4];}, x[!.0])". This doesn't affect 1257 // compliance: we should warn earlier for offsetof expressions with 1258 // array subscripts that aren't ICEs, and if the array subscripts 1259 // are ICEs, the value of the offsetof must be an integer constant. 1260 return CheckEvalInICE(E, Ctx); 1261 } 1262 } 1263 case Expr::SizeOfAlignOfExprClass: { 1264 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(E); 1265 if (Exp->isSizeOf() && Exp->getTypeOfArgument()->isVariableArrayType()) 1266 return ICEDiag(2, E->getLocStart()); 1267 return NoDiag(); 1268 } 1269 case Expr::BinaryOperatorClass: { 1270 const BinaryOperator *Exp = cast<BinaryOperator>(E); 1271 switch (Exp->getOpcode()) { 1272 default: 1273 return ICEDiag(2, E->getLocStart()); 1274 case BinaryOperator::Mul: 1275 case BinaryOperator::Div: 1276 case BinaryOperator::Rem: 1277 case BinaryOperator::Add: 1278 case BinaryOperator::Sub: 1279 case BinaryOperator::Shl: 1280 case BinaryOperator::Shr: 1281 case BinaryOperator::LT: 1282 case BinaryOperator::GT: 1283 case BinaryOperator::LE: 1284 case BinaryOperator::GE: 1285 case BinaryOperator::EQ: 1286 case BinaryOperator::NE: 1287 case BinaryOperator::And: 1288 case BinaryOperator::Xor: 1289 case BinaryOperator::Or: 1290 case BinaryOperator::Comma: { 1291 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 1292 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 1293 if (Exp->getOpcode() == BinaryOperator::Div || 1294 Exp->getOpcode() == BinaryOperator::Rem) { 1295 // Evaluate gives an error for undefined Div/Rem, so make sure 1296 // we don't evaluate one. 1297 if (LHSResult.Val != 2 && RHSResult.Val != 2) { 1298 llvm::APSInt REval = Exp->getRHS()->EvaluateAsInt(Ctx); 1299 if (REval == 0) 1300 return ICEDiag(1, E->getLocStart()); 1301 if (REval.isSigned() && REval.isAllOnesValue()) { 1302 llvm::APSInt LEval = Exp->getLHS()->EvaluateAsInt(Ctx); 1303 if (LEval.isMinSignedValue()) 1304 return ICEDiag(1, E->getLocStart()); 1305 } 1306 } 1307 } 1308 if (Exp->getOpcode() == BinaryOperator::Comma) { 1309 if (Ctx.getLangOptions().C99) { 1310 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 1311 // if it isn't evaluated. 1312 if (LHSResult.Val == 0 && RHSResult.Val == 0) 1313 return ICEDiag(1, E->getLocStart()); 1314 } else { 1315 // In both C89 and C++, commas in ICEs are illegal. 1316 return ICEDiag(2, E->getLocStart()); 1317 } 1318 } 1319 if (LHSResult.Val >= RHSResult.Val) 1320 return LHSResult; 1321 return RHSResult; 1322 } 1323 case BinaryOperator::LAnd: 1324 case BinaryOperator::LOr: { 1325 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 1326 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 1327 if (LHSResult.Val == 0 && RHSResult.Val == 1) { 1328 // Rare case where the RHS has a comma "side-effect"; we need 1329 // to actually check the condition to see whether the side 1330 // with the comma is evaluated. 1331 if ((Exp->getOpcode() == BinaryOperator::LAnd) != 1332 (Exp->getLHS()->EvaluateAsInt(Ctx) == 0)) 1333 return RHSResult; 1334 return NoDiag(); 1335 } 1336 1337 if (LHSResult.Val >= RHSResult.Val) 1338 return LHSResult; 1339 return RHSResult; 1340 } 1341 } 1342 } 1343 case Expr::ImplicitCastExprClass: 1344 case Expr::CStyleCastExprClass: 1345 case Expr::CXXFunctionalCastExprClass: { 1346 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 1347 if (SubExpr->getType()->isIntegralType()) 1348 return CheckICE(SubExpr, Ctx); 1349 if (isa<FloatingLiteral>(SubExpr->IgnoreParens())) 1350 return NoDiag(); 1351 return ICEDiag(2, E->getLocStart()); 1352 } 1353 case Expr::ConditionalOperatorClass: { 1354 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 1355 // If the condition (ignoring parens) is a __builtin_constant_p call, 1356 // then only the true side is actually considered in an integer constant 1357 // expression, and it is fully evaluated. This is an important GNU 1358 // extension. See GCC PR38377 for discussion. 1359 if (const CallExpr *CallCE = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 1360 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) { 1361 Expr::EvalResult EVResult; 1362 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects || 1363 !EVResult.Val.isInt()) { 1364 return ICEDiag(2, E->getLocStart()); 1365 } 1366 return NoDiag(); 1367 } 1368 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 1369 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 1370 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 1371 if (CondResult.Val == 2) 1372 return CondResult; 1373 if (TrueResult.Val == 2) 1374 return TrueResult; 1375 if (FalseResult.Val == 2) 1376 return FalseResult; 1377 if (CondResult.Val == 1) 1378 return CondResult; 1379 if (TrueResult.Val == 0 && FalseResult.Val == 0) 1380 return NoDiag(); 1381 // Rare case where the diagnostics depend on which side is evaluated 1382 // Note that if we get here, CondResult is 0, and at least one of 1383 // TrueResult and FalseResult is non-zero. 1384 if (Exp->getCond()->EvaluateAsInt(Ctx) == 0) { 1385 return FalseResult; 1386 } 1387 return TrueResult; 1388 } 1389 case Expr::CXXDefaultArgExprClass: 1390 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 1391 case Expr::ChooseExprClass: { 1392 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx); 1393 } 1394 } 1395} 1396 1397bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx, 1398 SourceLocation *Loc, bool isEvaluated) const { 1399 ICEDiag d = CheckICE(this, Ctx); 1400 if (d.Val != 0) { 1401 if (Loc) *Loc = d.Loc; 1402 return false; 1403 } 1404 EvalResult EvalResult; 1405 if (!Evaluate(EvalResult, Ctx)) 1406 assert(0 && "ICE cannot be evaluated!"); 1407 assert(!EvalResult.HasSideEffects && "ICE with side effects!"); 1408 assert(EvalResult.Val.isInt() && "ICE that isn't integer!"); 1409 Result = EvalResult.Val.getInt(); 1410 return true; 1411} 1412 1413/// isNullPointerConstant - C99 6.3.2.3p3 - Return true if this is either an 1414/// integer constant expression with the value zero, or if this is one that is 1415/// cast to void*. 1416bool Expr::isNullPointerConstant(ASTContext &Ctx) const 1417{ 1418 // Strip off a cast to void*, if it exists. Except in C++. 1419 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) { 1420 if (!Ctx.getLangOptions().CPlusPlus) { 1421 // Check that it is a cast to void*. 1422 if (const PointerType *PT = CE->getType()->getAsPointerType()) { 1423 QualType Pointee = PT->getPointeeType(); 1424 if (Pointee.getCVRQualifiers() == 0 && 1425 Pointee->isVoidType() && // to void* 1426 CE->getSubExpr()->getType()->isIntegerType()) // from int. 1427 return CE->getSubExpr()->isNullPointerConstant(Ctx); 1428 } 1429 } 1430 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) { 1431 // Ignore the ImplicitCastExpr type entirely. 1432 return ICE->getSubExpr()->isNullPointerConstant(Ctx); 1433 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) { 1434 // Accept ((void*)0) as a null pointer constant, as many other 1435 // implementations do. 1436 return PE->getSubExpr()->isNullPointerConstant(Ctx); 1437 } else if (const CXXDefaultArgExpr *DefaultArg 1438 = dyn_cast<CXXDefaultArgExpr>(this)) { 1439 // See through default argument expressions 1440 return DefaultArg->getExpr()->isNullPointerConstant(Ctx); 1441 } else if (isa<GNUNullExpr>(this)) { 1442 // The GNU __null extension is always a null pointer constant. 1443 return true; 1444 } 1445 1446 // C++0x nullptr_t is always a null pointer constant. 1447 if (getType()->isNullPtrType()) 1448 return true; 1449 1450 // This expression must be an integer type. 1451 if (!getType()->isIntegerType()) 1452 return false; 1453 1454 // If we have an integer constant expression, we need to *evaluate* it and 1455 // test for the value 0. 1456 llvm::APSInt Result; 1457 return isIntegerConstantExpr(Result, Ctx) && Result == 0; 1458} 1459 1460FieldDecl *Expr::getBitField() { 1461 Expr *E = this->IgnoreParens(); 1462 1463 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E)) 1464 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl())) 1465 if (Field->isBitField()) 1466 return Field; 1467 1468 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) 1469 if (BinOp->isAssignmentOp() && BinOp->getLHS()) 1470 return BinOp->getLHS()->getBitField(); 1471 1472 return 0; 1473} 1474 1475/// isArrow - Return true if the base expression is a pointer to vector, 1476/// return false if the base expression is a vector. 1477bool ExtVectorElementExpr::isArrow() const { 1478 return getBase()->getType()->isPointerType(); 1479} 1480 1481unsigned ExtVectorElementExpr::getNumElements() const { 1482 if (const VectorType *VT = getType()->getAsVectorType()) 1483 return VT->getNumElements(); 1484 return 1; 1485} 1486 1487/// containsDuplicateElements - Return true if any element access is repeated. 1488bool ExtVectorElementExpr::containsDuplicateElements() const { 1489 const char *compStr = Accessor->getName(); 1490 unsigned length = Accessor->getLength(); 1491 1492 // Halving swizzles do not contain duplicate elements. 1493 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") || 1494 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) 1495 return false; 1496 1497 // Advance past s-char prefix on hex swizzles. 1498 if (*compStr == 's' || *compStr == 'S') { 1499 compStr++; 1500 length--; 1501 } 1502 1503 for (unsigned i = 0; i != length-1; i++) { 1504 const char *s = compStr+i; 1505 for (const char c = *s++; *s; s++) 1506 if (c == *s) 1507 return true; 1508 } 1509 return false; 1510} 1511 1512/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray. 1513void ExtVectorElementExpr::getEncodedElementAccess( 1514 llvm::SmallVectorImpl<unsigned> &Elts) const { 1515 const char *compStr = Accessor->getName(); 1516 if (*compStr == 's' || *compStr == 'S') 1517 compStr++; 1518 1519 bool isHi = !strcmp(compStr, "hi"); 1520 bool isLo = !strcmp(compStr, "lo"); 1521 bool isEven = !strcmp(compStr, "even"); 1522 bool isOdd = !strcmp(compStr, "odd"); 1523 1524 for (unsigned i = 0, e = getNumElements(); i != e; ++i) { 1525 uint64_t Index; 1526 1527 if (isHi) 1528 Index = e + i; 1529 else if (isLo) 1530 Index = i; 1531 else if (isEven) 1532 Index = 2 * i; 1533 else if (isOdd) 1534 Index = 2 * i + 1; 1535 else 1536 Index = ExtVectorType::getAccessorIdx(compStr[i]); 1537 1538 Elts.push_back(Index); 1539 } 1540} 1541 1542// constructor for instance messages. 1543ObjCMessageExpr::ObjCMessageExpr(Expr *receiver, Selector selInfo, 1544 QualType retType, ObjCMethodDecl *mproto, 1545 SourceLocation LBrac, SourceLocation RBrac, 1546 Expr **ArgExprs, unsigned nargs) 1547 : Expr(ObjCMessageExprClass, retType), SelName(selInfo), 1548 MethodProto(mproto) { 1549 NumArgs = nargs; 1550 SubExprs = new Stmt*[NumArgs+1]; 1551 SubExprs[RECEIVER] = receiver; 1552 if (NumArgs) { 1553 for (unsigned i = 0; i != NumArgs; ++i) 1554 SubExprs[i+ARGS_START] = static_cast<Expr *>(ArgExprs[i]); 1555 } 1556 LBracloc = LBrac; 1557 RBracloc = RBrac; 1558} 1559 1560ObjCStringLiteral* ObjCStringLiteral::Clone(ASTContext &C) const { 1561 // Clone the string literal. 1562 StringLiteral *NewString = 1563 String ? cast<StringLiteral>(String)->Clone(C) : 0; 1564 1565 return new (C) ObjCStringLiteral(NewString, getType(), AtLoc); 1566} 1567 1568ObjCSelectorExpr *ObjCSelectorExpr::Clone(ASTContext &C) const { 1569 return new (C) ObjCSelectorExpr(getType(), SelName, AtLoc, RParenLoc); 1570} 1571 1572ObjCProtocolExpr *ObjCProtocolExpr::Clone(ASTContext &C) const { 1573 return new (C) ObjCProtocolExpr(getType(), TheProtocol, AtLoc, RParenLoc); 1574} 1575 1576// constructor for class messages. 1577// FIXME: clsName should be typed to ObjCInterfaceType 1578ObjCMessageExpr::ObjCMessageExpr(IdentifierInfo *clsName, Selector selInfo, 1579 QualType retType, ObjCMethodDecl *mproto, 1580 SourceLocation LBrac, SourceLocation RBrac, 1581 Expr **ArgExprs, unsigned nargs) 1582 : Expr(ObjCMessageExprClass, retType), SelName(selInfo), 1583 MethodProto(mproto) { 1584 NumArgs = nargs; 1585 SubExprs = new Stmt*[NumArgs+1]; 1586 SubExprs[RECEIVER] = (Expr*) ((uintptr_t) clsName | IsClsMethDeclUnknown); 1587 if (NumArgs) { 1588 for (unsigned i = 0; i != NumArgs; ++i) 1589 SubExprs[i+ARGS_START] = static_cast<Expr *>(ArgExprs[i]); 1590 } 1591 LBracloc = LBrac; 1592 RBracloc = RBrac; 1593} 1594 1595// constructor for class messages. 1596ObjCMessageExpr::ObjCMessageExpr(ObjCInterfaceDecl *cls, Selector selInfo, 1597 QualType retType, ObjCMethodDecl *mproto, 1598 SourceLocation LBrac, SourceLocation RBrac, 1599 Expr **ArgExprs, unsigned nargs) 1600: Expr(ObjCMessageExprClass, retType), SelName(selInfo), 1601MethodProto(mproto) { 1602 NumArgs = nargs; 1603 SubExprs = new Stmt*[NumArgs+1]; 1604 SubExprs[RECEIVER] = (Expr*) ((uintptr_t) cls | IsClsMethDeclKnown); 1605 if (NumArgs) { 1606 for (unsigned i = 0; i != NumArgs; ++i) 1607 SubExprs[i+ARGS_START] = static_cast<Expr *>(ArgExprs[i]); 1608 } 1609 LBracloc = LBrac; 1610 RBracloc = RBrac; 1611} 1612 1613ObjCMessageExpr::ClassInfo ObjCMessageExpr::getClassInfo() const { 1614 uintptr_t x = (uintptr_t) SubExprs[RECEIVER]; 1615 switch (x & Flags) { 1616 default: 1617 assert(false && "Invalid ObjCMessageExpr."); 1618 case IsInstMeth: 1619 return ClassInfo(0, 0); 1620 case IsClsMethDeclUnknown: 1621 return ClassInfo(0, (IdentifierInfo*) (x & ~Flags)); 1622 case IsClsMethDeclKnown: { 1623 ObjCInterfaceDecl* D = (ObjCInterfaceDecl*) (x & ~Flags); 1624 return ClassInfo(D, D->getIdentifier()); 1625 } 1626 } 1627} 1628 1629void ObjCMessageExpr::setClassInfo(const ObjCMessageExpr::ClassInfo &CI) { 1630 if (CI.first == 0 && CI.second == 0) 1631 SubExprs[RECEIVER] = (Expr*)((uintptr_t)0 | IsInstMeth); 1632 else if (CI.first == 0) 1633 SubExprs[RECEIVER] = (Expr*)((uintptr_t)CI.second | IsClsMethDeclUnknown); 1634 else 1635 SubExprs[RECEIVER] = (Expr*)((uintptr_t)CI.first | IsClsMethDeclKnown); 1636} 1637 1638 1639bool ChooseExpr::isConditionTrue(ASTContext &C) const { 1640 return getCond()->EvaluateAsInt(C) != 0; 1641} 1642 1643void ShuffleVectorExpr::setExprs(Expr ** Exprs, unsigned NumExprs) { 1644 if (NumExprs) 1645 delete [] SubExprs; 1646 1647 SubExprs = new Stmt* [NumExprs]; 1648 this->NumExprs = NumExprs; 1649 memcpy(SubExprs, Exprs, sizeof(Expr *) * NumExprs); 1650} 1651 1652void SizeOfAlignOfExpr::Destroy(ASTContext& C) { 1653 // Override default behavior of traversing children. If this has a type 1654 // operand and the type is a variable-length array, the child iteration 1655 // will iterate over the size expression. However, this expression belongs 1656 // to the type, not to this, so we don't want to delete it. 1657 // We still want to delete this expression. 1658 if (isArgumentType()) { 1659 this->~SizeOfAlignOfExpr(); 1660 C.Deallocate(this); 1661 } 1662 else 1663 Expr::Destroy(C); 1664} 1665 1666//===----------------------------------------------------------------------===// 1667// DesignatedInitExpr 1668//===----------------------------------------------------------------------===// 1669 1670IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() { 1671 assert(Kind == FieldDesignator && "Only valid on a field designator"); 1672 if (Field.NameOrField & 0x01) 1673 return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01); 1674 else 1675 return getField()->getIdentifier(); 1676} 1677 1678DesignatedInitExpr::DesignatedInitExpr(QualType Ty, unsigned NumDesignators, 1679 const Designator *Designators, 1680 SourceLocation EqualOrColonLoc, 1681 bool GNUSyntax, 1682 Expr **IndexExprs, 1683 unsigned NumIndexExprs, 1684 Expr *Init) 1685 : Expr(DesignatedInitExprClass, Ty, 1686 Init->isTypeDependent(), Init->isValueDependent()), 1687 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax), 1688 NumDesignators(NumDesignators), NumSubExprs(NumIndexExprs + 1) { 1689 this->Designators = new Designator[NumDesignators]; 1690 1691 // Record the initializer itself. 1692 child_iterator Child = child_begin(); 1693 *Child++ = Init; 1694 1695 // Copy the designators and their subexpressions, computing 1696 // value-dependence along the way. 1697 unsigned IndexIdx = 0; 1698 for (unsigned I = 0; I != NumDesignators; ++I) { 1699 this->Designators[I] = Designators[I]; 1700 1701 if (this->Designators[I].isArrayDesignator()) { 1702 // Compute type- and value-dependence. 1703 Expr *Index = IndexExprs[IndexIdx]; 1704 ValueDependent = ValueDependent || 1705 Index->isTypeDependent() || Index->isValueDependent(); 1706 1707 // Copy the index expressions into permanent storage. 1708 *Child++ = IndexExprs[IndexIdx++]; 1709 } else if (this->Designators[I].isArrayRangeDesignator()) { 1710 // Compute type- and value-dependence. 1711 Expr *Start = IndexExprs[IndexIdx]; 1712 Expr *End = IndexExprs[IndexIdx + 1]; 1713 ValueDependent = ValueDependent || 1714 Start->isTypeDependent() || Start->isValueDependent() || 1715 End->isTypeDependent() || End->isValueDependent(); 1716 1717 // Copy the start/end expressions into permanent storage. 1718 *Child++ = IndexExprs[IndexIdx++]; 1719 *Child++ = IndexExprs[IndexIdx++]; 1720 } 1721 } 1722 1723 assert(IndexIdx == NumIndexExprs && "Wrong number of index expressions"); 1724} 1725 1726DesignatedInitExpr * 1727DesignatedInitExpr::Create(ASTContext &C, Designator *Designators, 1728 unsigned NumDesignators, 1729 Expr **IndexExprs, unsigned NumIndexExprs, 1730 SourceLocation ColonOrEqualLoc, 1731 bool UsesColonSyntax, Expr *Init) { 1732 void *Mem = C.Allocate(sizeof(DesignatedInitExpr) + 1733 sizeof(Stmt *) * (NumIndexExprs + 1), 8); 1734 return new (Mem) DesignatedInitExpr(C.VoidTy, NumDesignators, Designators, 1735 ColonOrEqualLoc, UsesColonSyntax, 1736 IndexExprs, NumIndexExprs, Init); 1737} 1738 1739DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(ASTContext &C, 1740 unsigned NumIndexExprs) { 1741 void *Mem = C.Allocate(sizeof(DesignatedInitExpr) + 1742 sizeof(Stmt *) * (NumIndexExprs + 1), 8); 1743 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1); 1744} 1745 1746void DesignatedInitExpr::setDesignators(const Designator *Desigs, 1747 unsigned NumDesigs) { 1748 if (Designators) 1749 delete [] Designators; 1750 1751 Designators = new Designator[NumDesigs]; 1752 NumDesignators = NumDesigs; 1753 for (unsigned I = 0; I != NumDesigs; ++I) 1754 Designators[I] = Desigs[I]; 1755} 1756 1757SourceRange DesignatedInitExpr::getSourceRange() const { 1758 SourceLocation StartLoc; 1759 Designator &First = 1760 *const_cast<DesignatedInitExpr*>(this)->designators_begin(); 1761 if (First.isFieldDesignator()) { 1762 if (GNUSyntax) 1763 StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc); 1764 else 1765 StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc); 1766 } else 1767 StartLoc = 1768 SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc); 1769 return SourceRange(StartLoc, getInit()->getSourceRange().getEnd()); 1770} 1771 1772Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) { 1773 assert(D.Kind == Designator::ArrayDesignator && "Requires array designator"); 1774 char* Ptr = static_cast<char*>(static_cast<void *>(this)); 1775 Ptr += sizeof(DesignatedInitExpr); 1776 Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr)); 1777 return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1)); 1778} 1779 1780Expr *DesignatedInitExpr::getArrayRangeStart(const Designator& D) { 1781 assert(D.Kind == Designator::ArrayRangeDesignator && 1782 "Requires array range designator"); 1783 char* Ptr = static_cast<char*>(static_cast<void *>(this)); 1784 Ptr += sizeof(DesignatedInitExpr); 1785 Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr)); 1786 return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1)); 1787} 1788 1789Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator& D) { 1790 assert(D.Kind == Designator::ArrayRangeDesignator && 1791 "Requires array range designator"); 1792 char* Ptr = static_cast<char*>(static_cast<void *>(this)); 1793 Ptr += sizeof(DesignatedInitExpr); 1794 Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr)); 1795 return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 2)); 1796} 1797 1798/// \brief Replaces the designator at index @p Idx with the series 1799/// of designators in [First, Last). 1800void DesignatedInitExpr::ExpandDesignator(unsigned Idx, 1801 const Designator *First, 1802 const Designator *Last) { 1803 unsigned NumNewDesignators = Last - First; 1804 if (NumNewDesignators == 0) { 1805 std::copy_backward(Designators + Idx + 1, 1806 Designators + NumDesignators, 1807 Designators + Idx); 1808 --NumNewDesignators; 1809 return; 1810 } else if (NumNewDesignators == 1) { 1811 Designators[Idx] = *First; 1812 return; 1813 } 1814 1815 Designator *NewDesignators 1816 = new Designator[NumDesignators - 1 + NumNewDesignators]; 1817 std::copy(Designators, Designators + Idx, NewDesignators); 1818 std::copy(First, Last, NewDesignators + Idx); 1819 std::copy(Designators + Idx + 1, Designators + NumDesignators, 1820 NewDesignators + Idx + NumNewDesignators); 1821 delete [] Designators; 1822 Designators = NewDesignators; 1823 NumDesignators = NumDesignators - 1 + NumNewDesignators; 1824} 1825 1826void DesignatedInitExpr::Destroy(ASTContext &C) { 1827 delete [] Designators; 1828 Expr::Destroy(C); 1829} 1830 1831ImplicitValueInitExpr *ImplicitValueInitExpr::Clone(ASTContext &C) const { 1832 return new (C) ImplicitValueInitExpr(getType()); 1833} 1834 1835//===----------------------------------------------------------------------===// 1836// ExprIterator. 1837//===----------------------------------------------------------------------===// 1838 1839Expr* ExprIterator::operator[](size_t idx) { return cast<Expr>(I[idx]); } 1840Expr* ExprIterator::operator*() const { return cast<Expr>(*I); } 1841Expr* ExprIterator::operator->() const { return cast<Expr>(*I); } 1842const Expr* ConstExprIterator::operator[](size_t idx) const { 1843 return cast<Expr>(I[idx]); 1844} 1845const Expr* ConstExprIterator::operator*() const { return cast<Expr>(*I); } 1846const Expr* ConstExprIterator::operator->() const { return cast<Expr>(*I); } 1847 1848//===----------------------------------------------------------------------===// 1849// Child Iterators for iterating over subexpressions/substatements 1850//===----------------------------------------------------------------------===// 1851 1852// DeclRefExpr 1853Stmt::child_iterator DeclRefExpr::child_begin() { return child_iterator(); } 1854Stmt::child_iterator DeclRefExpr::child_end() { return child_iterator(); } 1855 1856// ObjCIvarRefExpr 1857Stmt::child_iterator ObjCIvarRefExpr::child_begin() { return &Base; } 1858Stmt::child_iterator ObjCIvarRefExpr::child_end() { return &Base+1; } 1859 1860// ObjCPropertyRefExpr 1861Stmt::child_iterator ObjCPropertyRefExpr::child_begin() { return &Base; } 1862Stmt::child_iterator ObjCPropertyRefExpr::child_end() { return &Base+1; } 1863 1864// ObjCKVCRefExpr 1865Stmt::child_iterator ObjCKVCRefExpr::child_begin() { return &Base; } 1866Stmt::child_iterator ObjCKVCRefExpr::child_end() { return &Base+1; } 1867 1868// ObjCSuperExpr 1869Stmt::child_iterator ObjCSuperExpr::child_begin() { return child_iterator(); } 1870Stmt::child_iterator ObjCSuperExpr::child_end() { return child_iterator(); } 1871 1872// PredefinedExpr 1873Stmt::child_iterator PredefinedExpr::child_begin() { return child_iterator(); } 1874Stmt::child_iterator PredefinedExpr::child_end() { return child_iterator(); } 1875 1876// IntegerLiteral 1877Stmt::child_iterator IntegerLiteral::child_begin() { return child_iterator(); } 1878Stmt::child_iterator IntegerLiteral::child_end() { return child_iterator(); } 1879 1880// CharacterLiteral 1881Stmt::child_iterator CharacterLiteral::child_begin() { return child_iterator();} 1882Stmt::child_iterator CharacterLiteral::child_end() { return child_iterator(); } 1883 1884// FloatingLiteral 1885Stmt::child_iterator FloatingLiteral::child_begin() { return child_iterator(); } 1886Stmt::child_iterator FloatingLiteral::child_end() { return child_iterator(); } 1887 1888// ImaginaryLiteral 1889Stmt::child_iterator ImaginaryLiteral::child_begin() { return &Val; } 1890Stmt::child_iterator ImaginaryLiteral::child_end() { return &Val+1; } 1891 1892// StringLiteral 1893Stmt::child_iterator StringLiteral::child_begin() { return child_iterator(); } 1894Stmt::child_iterator StringLiteral::child_end() { return child_iterator(); } 1895 1896// ParenExpr 1897Stmt::child_iterator ParenExpr::child_begin() { return &Val; } 1898Stmt::child_iterator ParenExpr::child_end() { return &Val+1; } 1899 1900// UnaryOperator 1901Stmt::child_iterator UnaryOperator::child_begin() { return &Val; } 1902Stmt::child_iterator UnaryOperator::child_end() { return &Val+1; } 1903 1904// SizeOfAlignOfExpr 1905Stmt::child_iterator SizeOfAlignOfExpr::child_begin() { 1906 // If this is of a type and the type is a VLA type (and not a typedef), the 1907 // size expression of the VLA needs to be treated as an executable expression. 1908 // Why isn't this weirdness documented better in StmtIterator? 1909 if (isArgumentType()) { 1910 if (VariableArrayType* T = dyn_cast<VariableArrayType>( 1911 getArgumentType().getTypePtr())) 1912 return child_iterator(T); 1913 return child_iterator(); 1914 } 1915 return child_iterator(&Argument.Ex); 1916} 1917Stmt::child_iterator SizeOfAlignOfExpr::child_end() { 1918 if (isArgumentType()) 1919 return child_iterator(); 1920 return child_iterator(&Argument.Ex + 1); 1921} 1922 1923// ArraySubscriptExpr 1924Stmt::child_iterator ArraySubscriptExpr::child_begin() { 1925 return &SubExprs[0]; 1926} 1927Stmt::child_iterator ArraySubscriptExpr::child_end() { 1928 return &SubExprs[0]+END_EXPR; 1929} 1930 1931// CallExpr 1932Stmt::child_iterator CallExpr::child_begin() { 1933 return &SubExprs[0]; 1934} 1935Stmt::child_iterator CallExpr::child_end() { 1936 return &SubExprs[0]+NumArgs+ARGS_START; 1937} 1938 1939// MemberExpr 1940Stmt::child_iterator MemberExpr::child_begin() { return &Base; } 1941Stmt::child_iterator MemberExpr::child_end() { return &Base+1; } 1942 1943// ExtVectorElementExpr 1944Stmt::child_iterator ExtVectorElementExpr::child_begin() { return &Base; } 1945Stmt::child_iterator ExtVectorElementExpr::child_end() { return &Base+1; } 1946 1947// CompoundLiteralExpr 1948Stmt::child_iterator CompoundLiteralExpr::child_begin() { return &Init; } 1949Stmt::child_iterator CompoundLiteralExpr::child_end() { return &Init+1; } 1950 1951// CastExpr 1952Stmt::child_iterator CastExpr::child_begin() { return &Op; } 1953Stmt::child_iterator CastExpr::child_end() { return &Op+1; } 1954 1955// BinaryOperator 1956Stmt::child_iterator BinaryOperator::child_begin() { 1957 return &SubExprs[0]; 1958} 1959Stmt::child_iterator BinaryOperator::child_end() { 1960 return &SubExprs[0]+END_EXPR; 1961} 1962 1963// ConditionalOperator 1964Stmt::child_iterator ConditionalOperator::child_begin() { 1965 return &SubExprs[0]; 1966} 1967Stmt::child_iterator ConditionalOperator::child_end() { 1968 return &SubExprs[0]+END_EXPR; 1969} 1970 1971// AddrLabelExpr 1972Stmt::child_iterator AddrLabelExpr::child_begin() { return child_iterator(); } 1973Stmt::child_iterator AddrLabelExpr::child_end() { return child_iterator(); } 1974 1975// StmtExpr 1976Stmt::child_iterator StmtExpr::child_begin() { return &SubStmt; } 1977Stmt::child_iterator StmtExpr::child_end() { return &SubStmt+1; } 1978 1979// TypesCompatibleExpr 1980Stmt::child_iterator TypesCompatibleExpr::child_begin() { 1981 return child_iterator(); 1982} 1983 1984Stmt::child_iterator TypesCompatibleExpr::child_end() { 1985 return child_iterator(); 1986} 1987 1988// ChooseExpr 1989Stmt::child_iterator ChooseExpr::child_begin() { return &SubExprs[0]; } 1990Stmt::child_iterator ChooseExpr::child_end() { return &SubExprs[0]+END_EXPR; } 1991 1992// GNUNullExpr 1993Stmt::child_iterator GNUNullExpr::child_begin() { return child_iterator(); } 1994Stmt::child_iterator GNUNullExpr::child_end() { return child_iterator(); } 1995 1996// ShuffleVectorExpr 1997Stmt::child_iterator ShuffleVectorExpr::child_begin() { 1998 return &SubExprs[0]; 1999} 2000Stmt::child_iterator ShuffleVectorExpr::child_end() { 2001 return &SubExprs[0]+NumExprs; 2002} 2003 2004// VAArgExpr 2005Stmt::child_iterator VAArgExpr::child_begin() { return &Val; } 2006Stmt::child_iterator VAArgExpr::child_end() { return &Val+1; } 2007 2008// InitListExpr 2009Stmt::child_iterator InitListExpr::child_begin() { 2010 return InitExprs.size() ? &InitExprs[0] : 0; 2011} 2012Stmt::child_iterator InitListExpr::child_end() { 2013 return InitExprs.size() ? &InitExprs[0] + InitExprs.size() : 0; 2014} 2015 2016// DesignatedInitExpr 2017Stmt::child_iterator DesignatedInitExpr::child_begin() { 2018 char* Ptr = static_cast<char*>(static_cast<void *>(this)); 2019 Ptr += sizeof(DesignatedInitExpr); 2020 return reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr)); 2021} 2022Stmt::child_iterator DesignatedInitExpr::child_end() { 2023 return child_iterator(&*child_begin() + NumSubExprs); 2024} 2025 2026// ImplicitValueInitExpr 2027Stmt::child_iterator ImplicitValueInitExpr::child_begin() { 2028 return child_iterator(); 2029} 2030 2031Stmt::child_iterator ImplicitValueInitExpr::child_end() { 2032 return child_iterator(); 2033} 2034 2035// ObjCStringLiteral 2036Stmt::child_iterator ObjCStringLiteral::child_begin() { 2037 return &String; 2038} 2039Stmt::child_iterator ObjCStringLiteral::child_end() { 2040 return &String+1; 2041} 2042 2043// ObjCEncodeExpr 2044Stmt::child_iterator ObjCEncodeExpr::child_begin() { return child_iterator(); } 2045Stmt::child_iterator ObjCEncodeExpr::child_end() { return child_iterator(); } 2046 2047// ObjCSelectorExpr 2048Stmt::child_iterator ObjCSelectorExpr::child_begin() { 2049 return child_iterator(); 2050} 2051Stmt::child_iterator ObjCSelectorExpr::child_end() { 2052 return child_iterator(); 2053} 2054 2055// ObjCProtocolExpr 2056Stmt::child_iterator ObjCProtocolExpr::child_begin() { 2057 return child_iterator(); 2058} 2059Stmt::child_iterator ObjCProtocolExpr::child_end() { 2060 return child_iterator(); 2061} 2062 2063// ObjCMessageExpr 2064Stmt::child_iterator ObjCMessageExpr::child_begin() { 2065 return getReceiver() ? &SubExprs[0] : &SubExprs[0] + ARGS_START; 2066} 2067Stmt::child_iterator ObjCMessageExpr::child_end() { 2068 return &SubExprs[0]+ARGS_START+getNumArgs(); 2069} 2070 2071// Blocks 2072Stmt::child_iterator BlockExpr::child_begin() { return child_iterator(); } 2073Stmt::child_iterator BlockExpr::child_end() { return child_iterator(); } 2074 2075Stmt::child_iterator BlockDeclRefExpr::child_begin() { return child_iterator();} 2076Stmt::child_iterator BlockDeclRefExpr::child_end() { return child_iterator(); } 2077