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/APValue.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/Attr.h" 17 #include "clang/AST/DeclCXX.h" 18 #include "clang/AST/DeclObjC.h" 19 #include "clang/AST/DeclTemplate.h" 20 #include "clang/AST/EvaluatedExprVisitor.h" 21 #include "clang/AST/Expr.h" 22 #include "clang/AST/ExprCXX.h" 23 #include "clang/AST/RecordLayout.h" 24 #include "clang/AST/StmtVisitor.h" 25 #include "clang/Basic/Builtins.h" 26 #include "clang/Basic/CharInfo.h" 27 #include "clang/Basic/SourceManager.h" 28 #include "clang/Basic/TargetInfo.h" 29 #include "clang/Lex/Lexer.h" 30 #include "clang/Lex/LiteralSupport.h" 31 #include "clang/Sema/SemaDiagnostic.h" 32 #include "llvm/Support/ErrorHandling.h" 33 #include "llvm/Support/raw_ostream.h" 34 #include <algorithm> 35 #include <cstring> 36 using namespace clang; 37 38 const CXXRecordDecl *Expr::getBestDynamicClassType() const { 39 const Expr *E = ignoreParenBaseCasts(); 40 41 QualType DerivedType = E->getType(); 42 if (const PointerType *PTy = DerivedType->getAs<PointerType>()) 43 DerivedType = PTy->getPointeeType(); 44 45 if (DerivedType->isDependentType()) 46 return NULL; 47 48 const RecordType *Ty = DerivedType->castAs<RecordType>(); 49 Decl *D = Ty->getDecl(); 50 return cast<CXXRecordDecl>(D); 51 } 52 53 const Expr *Expr::skipRValueSubobjectAdjustments( 54 SmallVectorImpl<const Expr *> &CommaLHSs, 55 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const { 56 const Expr *E = this; 57 while (true) { 58 E = E->IgnoreParens(); 59 60 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 61 if ((CE->getCastKind() == CK_DerivedToBase || 62 CE->getCastKind() == CK_UncheckedDerivedToBase) && 63 E->getType()->isRecordType()) { 64 E = CE->getSubExpr(); 65 CXXRecordDecl *Derived 66 = cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl()); 67 Adjustments.push_back(SubobjectAdjustment(CE, Derived)); 68 continue; 69 } 70 71 if (CE->getCastKind() == CK_NoOp) { 72 E = CE->getSubExpr(); 73 continue; 74 } 75 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 76 if (!ME->isArrow()) { 77 assert(ME->getBase()->getType()->isRecordType()); 78 if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 79 if (!Field->isBitField() && !Field->getType()->isReferenceType()) { 80 E = ME->getBase(); 81 Adjustments.push_back(SubobjectAdjustment(Field)); 82 continue; 83 } 84 } 85 } 86 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 87 if (BO->isPtrMemOp()) { 88 assert(BO->getRHS()->isRValue()); 89 E = BO->getLHS(); 90 const MemberPointerType *MPT = 91 BO->getRHS()->getType()->getAs<MemberPointerType>(); 92 Adjustments.push_back(SubobjectAdjustment(MPT, BO->getRHS())); 93 continue; 94 } else if (BO->getOpcode() == BO_Comma) { 95 CommaLHSs.push_back(BO->getLHS()); 96 E = BO->getRHS(); 97 continue; 98 } 99 } 100 101 // Nothing changed. 102 break; 103 } 104 return E; 105 } 106 107 const Expr * 108 Expr::findMaterializedTemporary(const MaterializeTemporaryExpr *&MTE) const { 109 const Expr *E = this; 110 111 // This might be a default initializer for a reference member. Walk over the 112 // wrapper node for that. 113 if (const CXXDefaultInitExpr *DAE = dyn_cast<CXXDefaultInitExpr>(E)) 114 E = DAE->getExpr(); 115 116 // Look through single-element init lists that claim to be lvalues. They're 117 // just syntactic wrappers in this case. 118 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E)) { 119 if (ILE->getNumInits() == 1 && ILE->isGLValue()) { 120 E = ILE->getInit(0); 121 if (const CXXDefaultInitExpr *DAE = dyn_cast<CXXDefaultInitExpr>(E)) 122 E = DAE->getExpr(); 123 } 124 } 125 126 // Look through expressions for materialized temporaries (for now). 127 if (const MaterializeTemporaryExpr *M 128 = dyn_cast<MaterializeTemporaryExpr>(E)) { 129 MTE = M; 130 E = M->GetTemporaryExpr(); 131 } 132 133 if (const CXXDefaultArgExpr *DAE = dyn_cast<CXXDefaultArgExpr>(E)) 134 E = DAE->getExpr(); 135 return E; 136 } 137 138 /// isKnownToHaveBooleanValue - Return true if this is an integer expression 139 /// that is known to return 0 or 1. This happens for _Bool/bool expressions 140 /// but also int expressions which are produced by things like comparisons in 141 /// C. 142 bool Expr::isKnownToHaveBooleanValue() const { 143 const Expr *E = IgnoreParens(); 144 145 // If this value has _Bool type, it is obvious 0/1. 146 if (E->getType()->isBooleanType()) return true; 147 // If this is a non-scalar-integer type, we don't care enough to try. 148 if (!E->getType()->isIntegralOrEnumerationType()) return false; 149 150 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 151 switch (UO->getOpcode()) { 152 case UO_Plus: 153 return UO->getSubExpr()->isKnownToHaveBooleanValue(); 154 default: 155 return false; 156 } 157 } 158 159 // Only look through implicit casts. If the user writes 160 // '(int) (a && b)' treat it as an arbitrary int. 161 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) 162 return CE->getSubExpr()->isKnownToHaveBooleanValue(); 163 164 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 165 switch (BO->getOpcode()) { 166 default: return false; 167 case BO_LT: // Relational operators. 168 case BO_GT: 169 case BO_LE: 170 case BO_GE: 171 case BO_EQ: // Equality operators. 172 case BO_NE: 173 case BO_LAnd: // AND operator. 174 case BO_LOr: // Logical OR operator. 175 return true; 176 177 case BO_And: // Bitwise AND operator. 178 case BO_Xor: // Bitwise XOR operator. 179 case BO_Or: // Bitwise OR operator. 180 // Handle things like (x==2)|(y==12). 181 return BO->getLHS()->isKnownToHaveBooleanValue() && 182 BO->getRHS()->isKnownToHaveBooleanValue(); 183 184 case BO_Comma: 185 case BO_Assign: 186 return BO->getRHS()->isKnownToHaveBooleanValue(); 187 } 188 } 189 190 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) 191 return CO->getTrueExpr()->isKnownToHaveBooleanValue() && 192 CO->getFalseExpr()->isKnownToHaveBooleanValue(); 193 194 return false; 195 } 196 197 // Amusing macro metaprogramming hack: check whether a class provides 198 // a more specific implementation of getExprLoc(). 199 // 200 // See also Stmt.cpp:{getLocStart(),getLocEnd()}. 201 namespace { 202 /// This implementation is used when a class provides a custom 203 /// implementation of getExprLoc. 204 template <class E, class T> 205 SourceLocation getExprLocImpl(const Expr *expr, 206 SourceLocation (T::*v)() const) { 207 return static_cast<const E*>(expr)->getExprLoc(); 208 } 209 210 /// This implementation is used when a class doesn't provide 211 /// a custom implementation of getExprLoc. Overload resolution 212 /// should pick it over the implementation above because it's 213 /// more specialized according to function template partial ordering. 214 template <class E> 215 SourceLocation getExprLocImpl(const Expr *expr, 216 SourceLocation (Expr::*v)() const) { 217 return static_cast<const E*>(expr)->getLocStart(); 218 } 219 } 220 221 SourceLocation Expr::getExprLoc() const { 222 switch (getStmtClass()) { 223 case Stmt::NoStmtClass: llvm_unreachable("statement without class"); 224 #define ABSTRACT_STMT(type) 225 #define STMT(type, base) \ 226 case Stmt::type##Class: llvm_unreachable(#type " is not an Expr"); break; 227 #define EXPR(type, base) \ 228 case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc); 229 #include "clang/AST/StmtNodes.inc" 230 } 231 llvm_unreachable("unknown statement kind"); 232 } 233 234 //===----------------------------------------------------------------------===// 235 // Primary Expressions. 236 //===----------------------------------------------------------------------===// 237 238 /// \brief Compute the type-, value-, and instantiation-dependence of a 239 /// declaration reference 240 /// based on the declaration being referenced. 241 static void computeDeclRefDependence(ASTContext &Ctx, NamedDecl *D, QualType T, 242 bool &TypeDependent, 243 bool &ValueDependent, 244 bool &InstantiationDependent) { 245 TypeDependent = false; 246 ValueDependent = false; 247 InstantiationDependent = false; 248 249 // (TD) C++ [temp.dep.expr]p3: 250 // An id-expression is type-dependent if it contains: 251 // 252 // and 253 // 254 // (VD) C++ [temp.dep.constexpr]p2: 255 // An identifier is value-dependent if it is: 256 257 // (TD) - an identifier that was declared with dependent type 258 // (VD) - a name declared with a dependent type, 259 if (T->isDependentType()) { 260 TypeDependent = true; 261 ValueDependent = true; 262 InstantiationDependent = true; 263 return; 264 } else if (T->isInstantiationDependentType()) { 265 InstantiationDependent = true; 266 } 267 268 // (TD) - a conversion-function-id that specifies a dependent type 269 if (D->getDeclName().getNameKind() 270 == DeclarationName::CXXConversionFunctionName) { 271 QualType T = D->getDeclName().getCXXNameType(); 272 if (T->isDependentType()) { 273 TypeDependent = true; 274 ValueDependent = true; 275 InstantiationDependent = true; 276 return; 277 } 278 279 if (T->isInstantiationDependentType()) 280 InstantiationDependent = true; 281 } 282 283 // (VD) - the name of a non-type template parameter, 284 if (isa<NonTypeTemplateParmDecl>(D)) { 285 ValueDependent = true; 286 InstantiationDependent = true; 287 return; 288 } 289 290 // (VD) - a constant with integral or enumeration type and is 291 // initialized with an expression that is value-dependent. 292 // (VD) - a constant with literal type and is initialized with an 293 // expression that is value-dependent [C++11]. 294 // (VD) - FIXME: Missing from the standard: 295 // - an entity with reference type and is initialized with an 296 // expression that is value-dependent [C++11] 297 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 298 if ((Ctx.getLangOpts().CPlusPlus11 ? 299 Var->getType()->isLiteralType(Ctx) : 300 Var->getType()->isIntegralOrEnumerationType()) && 301 (Var->getType().isConstQualified() || 302 Var->getType()->isReferenceType())) { 303 if (const Expr *Init = Var->getAnyInitializer()) 304 if (Init->isValueDependent()) { 305 ValueDependent = true; 306 InstantiationDependent = true; 307 } 308 } 309 310 // (VD) - FIXME: Missing from the standard: 311 // - a member function or a static data member of the current 312 // instantiation 313 if (Var->isStaticDataMember() && 314 Var->getDeclContext()->isDependentContext()) { 315 ValueDependent = true; 316 InstantiationDependent = true; 317 } 318 319 return; 320 } 321 322 // (VD) - FIXME: Missing from the standard: 323 // - a member function or a static data member of the current 324 // instantiation 325 if (isa<CXXMethodDecl>(D) && D->getDeclContext()->isDependentContext()) { 326 ValueDependent = true; 327 InstantiationDependent = true; 328 } 329 } 330 331 void DeclRefExpr::computeDependence(ASTContext &Ctx) { 332 bool TypeDependent = false; 333 bool ValueDependent = false; 334 bool InstantiationDependent = false; 335 computeDeclRefDependence(Ctx, getDecl(), getType(), TypeDependent, 336 ValueDependent, InstantiationDependent); 337 338 // (TD) C++ [temp.dep.expr]p3: 339 // An id-expression is type-dependent if it contains: 340 // 341 // and 342 // 343 // (VD) C++ [temp.dep.constexpr]p2: 344 // An identifier is value-dependent if it is: 345 if (!TypeDependent && !ValueDependent && 346 hasExplicitTemplateArgs() && 347 TemplateSpecializationType::anyDependentTemplateArguments( 348 getTemplateArgs(), 349 getNumTemplateArgs(), 350 InstantiationDependent)) { 351 TypeDependent = true; 352 ValueDependent = true; 353 InstantiationDependent = true; 354 } 355 356 ExprBits.TypeDependent = TypeDependent; 357 ExprBits.ValueDependent = ValueDependent; 358 ExprBits.InstantiationDependent = InstantiationDependent; 359 360 // Is the declaration a parameter pack? 361 if (getDecl()->isParameterPack()) 362 ExprBits.ContainsUnexpandedParameterPack = true; 363 } 364 365 DeclRefExpr::DeclRefExpr(ASTContext &Ctx, 366 NestedNameSpecifierLoc QualifierLoc, 367 SourceLocation TemplateKWLoc, 368 ValueDecl *D, bool RefersToEnclosingLocal, 369 const DeclarationNameInfo &NameInfo, 370 NamedDecl *FoundD, 371 const TemplateArgumentListInfo *TemplateArgs, 372 QualType T, ExprValueKind VK) 373 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false), 374 D(D), Loc(NameInfo.getLoc()), DNLoc(NameInfo.getInfo()) { 375 DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0; 376 if (QualifierLoc) 377 getInternalQualifierLoc() = QualifierLoc; 378 DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0; 379 if (FoundD) 380 getInternalFoundDecl() = FoundD; 381 DeclRefExprBits.HasTemplateKWAndArgsInfo 382 = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0; 383 DeclRefExprBits.RefersToEnclosingLocal = RefersToEnclosingLocal; 384 if (TemplateArgs) { 385 bool Dependent = false; 386 bool InstantiationDependent = false; 387 bool ContainsUnexpandedParameterPack = false; 388 getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc, *TemplateArgs, 389 Dependent, 390 InstantiationDependent, 391 ContainsUnexpandedParameterPack); 392 if (InstantiationDependent) 393 setInstantiationDependent(true); 394 } else if (TemplateKWLoc.isValid()) { 395 getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc); 396 } 397 DeclRefExprBits.HadMultipleCandidates = 0; 398 399 computeDependence(Ctx); 400 } 401 402 DeclRefExpr *DeclRefExpr::Create(ASTContext &Context, 403 NestedNameSpecifierLoc QualifierLoc, 404 SourceLocation TemplateKWLoc, 405 ValueDecl *D, 406 bool RefersToEnclosingLocal, 407 SourceLocation NameLoc, 408 QualType T, 409 ExprValueKind VK, 410 NamedDecl *FoundD, 411 const TemplateArgumentListInfo *TemplateArgs) { 412 return Create(Context, QualifierLoc, TemplateKWLoc, D, 413 RefersToEnclosingLocal, 414 DeclarationNameInfo(D->getDeclName(), NameLoc), 415 T, VK, FoundD, TemplateArgs); 416 } 417 418 DeclRefExpr *DeclRefExpr::Create(ASTContext &Context, 419 NestedNameSpecifierLoc QualifierLoc, 420 SourceLocation TemplateKWLoc, 421 ValueDecl *D, 422 bool RefersToEnclosingLocal, 423 const DeclarationNameInfo &NameInfo, 424 QualType T, 425 ExprValueKind VK, 426 NamedDecl *FoundD, 427 const TemplateArgumentListInfo *TemplateArgs) { 428 // Filter out cases where the found Decl is the same as the value refenenced. 429 if (D == FoundD) 430 FoundD = 0; 431 432 std::size_t Size = sizeof(DeclRefExpr); 433 if (QualifierLoc) 434 Size += sizeof(NestedNameSpecifierLoc); 435 if (FoundD) 436 Size += sizeof(NamedDecl *); 437 if (TemplateArgs) 438 Size += ASTTemplateKWAndArgsInfo::sizeFor(TemplateArgs->size()); 439 else if (TemplateKWLoc.isValid()) 440 Size += ASTTemplateKWAndArgsInfo::sizeFor(0); 441 442 void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>()); 443 return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D, 444 RefersToEnclosingLocal, 445 NameInfo, FoundD, TemplateArgs, T, VK); 446 } 447 448 DeclRefExpr *DeclRefExpr::CreateEmpty(ASTContext &Context, 449 bool HasQualifier, 450 bool HasFoundDecl, 451 bool HasTemplateKWAndArgsInfo, 452 unsigned NumTemplateArgs) { 453 std::size_t Size = sizeof(DeclRefExpr); 454 if (HasQualifier) 455 Size += sizeof(NestedNameSpecifierLoc); 456 if (HasFoundDecl) 457 Size += sizeof(NamedDecl *); 458 if (HasTemplateKWAndArgsInfo) 459 Size += ASTTemplateKWAndArgsInfo::sizeFor(NumTemplateArgs); 460 461 void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>()); 462 return new (Mem) DeclRefExpr(EmptyShell()); 463 } 464 465 SourceLocation DeclRefExpr::getLocStart() const { 466 if (hasQualifier()) 467 return getQualifierLoc().getBeginLoc(); 468 return getNameInfo().getLocStart(); 469 } 470 SourceLocation DeclRefExpr::getLocEnd() const { 471 if (hasExplicitTemplateArgs()) 472 return getRAngleLoc(); 473 return getNameInfo().getLocEnd(); 474 } 475 476 // FIXME: Maybe this should use DeclPrinter with a special "print predefined 477 // expr" policy instead. 478 std::string PredefinedExpr::ComputeName(IdentType IT, const Decl *CurrentDecl) { 479 ASTContext &Context = CurrentDecl->getASTContext(); 480 481 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) { 482 if (IT != PrettyFunction && IT != PrettyFunctionNoVirtual) 483 return FD->getNameAsString(); 484 485 SmallString<256> Name; 486 llvm::raw_svector_ostream Out(Name); 487 488 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 489 if (MD->isVirtual() && IT != PrettyFunctionNoVirtual) 490 Out << "virtual "; 491 if (MD->isStatic()) 492 Out << "static "; 493 } 494 495 PrintingPolicy Policy(Context.getLangOpts()); 496 std::string Proto; 497 llvm::raw_string_ostream POut(Proto); 498 FD->printQualifiedName(POut, Policy); 499 500 const FunctionDecl *Decl = FD; 501 if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern()) 502 Decl = Pattern; 503 const FunctionType *AFT = Decl->getType()->getAs<FunctionType>(); 504 const FunctionProtoType *FT = 0; 505 if (FD->hasWrittenPrototype()) 506 FT = dyn_cast<FunctionProtoType>(AFT); 507 508 POut << "("; 509 if (FT) { 510 for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) { 511 if (i) POut << ", "; 512 POut << Decl->getParamDecl(i)->getType().stream(Policy); 513 } 514 515 if (FT->isVariadic()) { 516 if (FD->getNumParams()) POut << ", "; 517 POut << "..."; 518 } 519 } 520 POut << ")"; 521 522 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 523 const FunctionType *FT = MD->getType()->castAs<FunctionType>(); 524 if (FT->isConst()) 525 POut << " const"; 526 if (FT->isVolatile()) 527 POut << " volatile"; 528 RefQualifierKind Ref = MD->getRefQualifier(); 529 if (Ref == RQ_LValue) 530 POut << " &"; 531 else if (Ref == RQ_RValue) 532 POut << " &&"; 533 } 534 535 typedef SmallVector<const ClassTemplateSpecializationDecl *, 8> SpecsTy; 536 SpecsTy Specs; 537 const DeclContext *Ctx = FD->getDeclContext(); 538 while (Ctx && isa<NamedDecl>(Ctx)) { 539 const ClassTemplateSpecializationDecl *Spec 540 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx); 541 if (Spec && !Spec->isExplicitSpecialization()) 542 Specs.push_back(Spec); 543 Ctx = Ctx->getParent(); 544 } 545 546 std::string TemplateParams; 547 llvm::raw_string_ostream TOut(TemplateParams); 548 for (SpecsTy::reverse_iterator I = Specs.rbegin(), E = Specs.rend(); 549 I != E; ++I) { 550 const TemplateParameterList *Params 551 = (*I)->getSpecializedTemplate()->getTemplateParameters(); 552 const TemplateArgumentList &Args = (*I)->getTemplateArgs(); 553 assert(Params->size() == Args.size()); 554 for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) { 555 StringRef Param = Params->getParam(i)->getName(); 556 if (Param.empty()) continue; 557 TOut << Param << " = "; 558 Args.get(i).print(Policy, TOut); 559 TOut << ", "; 560 } 561 } 562 563 FunctionTemplateSpecializationInfo *FSI 564 = FD->getTemplateSpecializationInfo(); 565 if (FSI && !FSI->isExplicitSpecialization()) { 566 const TemplateParameterList* Params 567 = FSI->getTemplate()->getTemplateParameters(); 568 const TemplateArgumentList* Args = FSI->TemplateArguments; 569 assert(Params->size() == Args->size()); 570 for (unsigned i = 0, e = Params->size(); i != e; ++i) { 571 StringRef Param = Params->getParam(i)->getName(); 572 if (Param.empty()) continue; 573 TOut << Param << " = "; 574 Args->get(i).print(Policy, TOut); 575 TOut << ", "; 576 } 577 } 578 579 TOut.flush(); 580 if (!TemplateParams.empty()) { 581 // remove the trailing comma and space 582 TemplateParams.resize(TemplateParams.size() - 2); 583 POut << " [" << TemplateParams << "]"; 584 } 585 586 POut.flush(); 587 588 if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD)) 589 AFT->getResultType().getAsStringInternal(Proto, Policy); 590 591 Out << Proto; 592 593 Out.flush(); 594 return Name.str().str(); 595 } 596 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) { 597 SmallString<256> Name; 598 llvm::raw_svector_ostream Out(Name); 599 Out << (MD->isInstanceMethod() ? '-' : '+'); 600 Out << '['; 601 602 // For incorrect code, there might not be an ObjCInterfaceDecl. Do 603 // a null check to avoid a crash. 604 if (const ObjCInterfaceDecl *ID = MD->getClassInterface()) 605 Out << *ID; 606 607 if (const ObjCCategoryImplDecl *CID = 608 dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext())) 609 Out << '(' << *CID << ')'; 610 611 Out << ' '; 612 Out << MD->getSelector().getAsString(); 613 Out << ']'; 614 615 Out.flush(); 616 return Name.str().str(); 617 } 618 if (isa<TranslationUnitDecl>(CurrentDecl) && IT == PrettyFunction) { 619 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string. 620 return "top level"; 621 } 622 return ""; 623 } 624 625 void APNumericStorage::setIntValue(ASTContext &C, const llvm::APInt &Val) { 626 if (hasAllocation()) 627 C.Deallocate(pVal); 628 629 BitWidth = Val.getBitWidth(); 630 unsigned NumWords = Val.getNumWords(); 631 const uint64_t* Words = Val.getRawData(); 632 if (NumWords > 1) { 633 pVal = new (C) uint64_t[NumWords]; 634 std::copy(Words, Words + NumWords, pVal); 635 } else if (NumWords == 1) 636 VAL = Words[0]; 637 else 638 VAL = 0; 639 } 640 641 IntegerLiteral::IntegerLiteral(ASTContext &C, const llvm::APInt &V, 642 QualType type, SourceLocation l) 643 : Expr(IntegerLiteralClass, type, VK_RValue, OK_Ordinary, false, false, 644 false, false), 645 Loc(l) { 646 assert(type->isIntegerType() && "Illegal type in IntegerLiteral"); 647 assert(V.getBitWidth() == C.getIntWidth(type) && 648 "Integer type is not the correct size for constant."); 649 setValue(C, V); 650 } 651 652 IntegerLiteral * 653 IntegerLiteral::Create(ASTContext &C, const llvm::APInt &V, 654 QualType type, SourceLocation l) { 655 return new (C) IntegerLiteral(C, V, type, l); 656 } 657 658 IntegerLiteral * 659 IntegerLiteral::Create(ASTContext &C, EmptyShell Empty) { 660 return new (C) IntegerLiteral(Empty); 661 } 662 663 FloatingLiteral::FloatingLiteral(ASTContext &C, const llvm::APFloat &V, 664 bool isexact, QualType Type, SourceLocation L) 665 : Expr(FloatingLiteralClass, Type, VK_RValue, OK_Ordinary, false, false, 666 false, false), Loc(L) { 667 setSemantics(V.getSemantics()); 668 FloatingLiteralBits.IsExact = isexact; 669 setValue(C, V); 670 } 671 672 FloatingLiteral::FloatingLiteral(ASTContext &C, EmptyShell Empty) 673 : Expr(FloatingLiteralClass, Empty) { 674 setRawSemantics(IEEEhalf); 675 FloatingLiteralBits.IsExact = false; 676 } 677 678 FloatingLiteral * 679 FloatingLiteral::Create(ASTContext &C, const llvm::APFloat &V, 680 bool isexact, QualType Type, SourceLocation L) { 681 return new (C) FloatingLiteral(C, V, isexact, Type, L); 682 } 683 684 FloatingLiteral * 685 FloatingLiteral::Create(ASTContext &C, EmptyShell Empty) { 686 return new (C) FloatingLiteral(C, Empty); 687 } 688 689 const llvm::fltSemantics &FloatingLiteral::getSemantics() const { 690 switch(FloatingLiteralBits.Semantics) { 691 case IEEEhalf: 692 return llvm::APFloat::IEEEhalf; 693 case IEEEsingle: 694 return llvm::APFloat::IEEEsingle; 695 case IEEEdouble: 696 return llvm::APFloat::IEEEdouble; 697 case x87DoubleExtended: 698 return llvm::APFloat::x87DoubleExtended; 699 case IEEEquad: 700 return llvm::APFloat::IEEEquad; 701 case PPCDoubleDouble: 702 return llvm::APFloat::PPCDoubleDouble; 703 } 704 llvm_unreachable("Unrecognised floating semantics"); 705 } 706 707 void FloatingLiteral::setSemantics(const llvm::fltSemantics &Sem) { 708 if (&Sem == &llvm::APFloat::IEEEhalf) 709 FloatingLiteralBits.Semantics = IEEEhalf; 710 else if (&Sem == &llvm::APFloat::IEEEsingle) 711 FloatingLiteralBits.Semantics = IEEEsingle; 712 else if (&Sem == &llvm::APFloat::IEEEdouble) 713 FloatingLiteralBits.Semantics = IEEEdouble; 714 else if (&Sem == &llvm::APFloat::x87DoubleExtended) 715 FloatingLiteralBits.Semantics = x87DoubleExtended; 716 else if (&Sem == &llvm::APFloat::IEEEquad) 717 FloatingLiteralBits.Semantics = IEEEquad; 718 else if (&Sem == &llvm::APFloat::PPCDoubleDouble) 719 FloatingLiteralBits.Semantics = PPCDoubleDouble; 720 else 721 llvm_unreachable("Unknown floating semantics"); 722 } 723 724 /// getValueAsApproximateDouble - This returns the value as an inaccurate 725 /// double. Note that this may cause loss of precision, but is useful for 726 /// debugging dumps, etc. 727 double FloatingLiteral::getValueAsApproximateDouble() const { 728 llvm::APFloat V = getValue(); 729 bool ignored; 730 V.convert(llvm::APFloat::IEEEdouble, llvm::APFloat::rmNearestTiesToEven, 731 &ignored); 732 return V.convertToDouble(); 733 } 734 735 int StringLiteral::mapCharByteWidth(TargetInfo const &target,StringKind k) { 736 int CharByteWidth = 0; 737 switch(k) { 738 case Ascii: 739 case UTF8: 740 CharByteWidth = target.getCharWidth(); 741 break; 742 case Wide: 743 CharByteWidth = target.getWCharWidth(); 744 break; 745 case UTF16: 746 CharByteWidth = target.getChar16Width(); 747 break; 748 case UTF32: 749 CharByteWidth = target.getChar32Width(); 750 break; 751 } 752 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple"); 753 CharByteWidth /= 8; 754 assert((CharByteWidth==1 || CharByteWidth==2 || CharByteWidth==4) 755 && "character byte widths supported are 1, 2, and 4 only"); 756 return CharByteWidth; 757 } 758 759 StringLiteral *StringLiteral::Create(ASTContext &C, StringRef Str, 760 StringKind Kind, bool Pascal, QualType Ty, 761 const SourceLocation *Loc, 762 unsigned NumStrs) { 763 // Allocate enough space for the StringLiteral plus an array of locations for 764 // any concatenated string tokens. 765 void *Mem = C.Allocate(sizeof(StringLiteral)+ 766 sizeof(SourceLocation)*(NumStrs-1), 767 llvm::alignOf<StringLiteral>()); 768 StringLiteral *SL = new (Mem) StringLiteral(Ty); 769 770 // OPTIMIZE: could allocate this appended to the StringLiteral. 771 SL->setString(C,Str,Kind,Pascal); 772 773 SL->TokLocs[0] = Loc[0]; 774 SL->NumConcatenated = NumStrs; 775 776 if (NumStrs != 1) 777 memcpy(&SL->TokLocs[1], Loc+1, sizeof(SourceLocation)*(NumStrs-1)); 778 return SL; 779 } 780 781 StringLiteral *StringLiteral::CreateEmpty(ASTContext &C, unsigned NumStrs) { 782 void *Mem = C.Allocate(sizeof(StringLiteral)+ 783 sizeof(SourceLocation)*(NumStrs-1), 784 llvm::alignOf<StringLiteral>()); 785 StringLiteral *SL = new (Mem) StringLiteral(QualType()); 786 SL->CharByteWidth = 0; 787 SL->Length = 0; 788 SL->NumConcatenated = NumStrs; 789 return SL; 790 } 791 792 void StringLiteral::outputString(raw_ostream &OS) const { 793 switch (getKind()) { 794 case Ascii: break; // no prefix. 795 case Wide: OS << 'L'; break; 796 case UTF8: OS << "u8"; break; 797 case UTF16: OS << 'u'; break; 798 case UTF32: OS << 'U'; break; 799 } 800 OS << '"'; 801 static const char Hex[] = "0123456789ABCDEF"; 802 803 unsigned LastSlashX = getLength(); 804 for (unsigned I = 0, N = getLength(); I != N; ++I) { 805 switch (uint32_t Char = getCodeUnit(I)) { 806 default: 807 // FIXME: Convert UTF-8 back to codepoints before rendering. 808 809 // Convert UTF-16 surrogate pairs back to codepoints before rendering. 810 // Leave invalid surrogates alone; we'll use \x for those. 811 if (getKind() == UTF16 && I != N - 1 && Char >= 0xd800 && 812 Char <= 0xdbff) { 813 uint32_t Trail = getCodeUnit(I + 1); 814 if (Trail >= 0xdc00 && Trail <= 0xdfff) { 815 Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00); 816 ++I; 817 } 818 } 819 820 if (Char > 0xff) { 821 // If this is a wide string, output characters over 0xff using \x 822 // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a 823 // codepoint: use \x escapes for invalid codepoints. 824 if (getKind() == Wide || 825 (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) { 826 // FIXME: Is this the best way to print wchar_t? 827 OS << "\\x"; 828 int Shift = 28; 829 while ((Char >> Shift) == 0) 830 Shift -= 4; 831 for (/**/; Shift >= 0; Shift -= 4) 832 OS << Hex[(Char >> Shift) & 15]; 833 LastSlashX = I; 834 break; 835 } 836 837 if (Char > 0xffff) 838 OS << "\\U00" 839 << Hex[(Char >> 20) & 15] 840 << Hex[(Char >> 16) & 15]; 841 else 842 OS << "\\u"; 843 OS << Hex[(Char >> 12) & 15] 844 << Hex[(Char >> 8) & 15] 845 << Hex[(Char >> 4) & 15] 846 << Hex[(Char >> 0) & 15]; 847 break; 848 } 849 850 // If we used \x... for the previous character, and this character is a 851 // hexadecimal digit, prevent it being slurped as part of the \x. 852 if (LastSlashX + 1 == I) { 853 switch (Char) { 854 case '0': case '1': case '2': case '3': case '4': 855 case '5': case '6': case '7': case '8': case '9': 856 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': 857 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': 858 OS << "\"\""; 859 } 860 } 861 862 assert(Char <= 0xff && 863 "Characters above 0xff should already have been handled."); 864 865 if (isPrintable(Char)) 866 OS << (char)Char; 867 else // Output anything hard as an octal escape. 868 OS << '\\' 869 << (char)('0' + ((Char >> 6) & 7)) 870 << (char)('0' + ((Char >> 3) & 7)) 871 << (char)('0' + ((Char >> 0) & 7)); 872 break; 873 // Handle some common non-printable cases to make dumps prettier. 874 case '\\': OS << "\\\\"; break; 875 case '"': OS << "\\\""; break; 876 case '\n': OS << "\\n"; break; 877 case '\t': OS << "\\t"; break; 878 case '\a': OS << "\\a"; break; 879 case '\b': OS << "\\b"; break; 880 } 881 } 882 OS << '"'; 883 } 884 885 void StringLiteral::setString(ASTContext &C, StringRef Str, 886 StringKind Kind, bool IsPascal) { 887 //FIXME: we assume that the string data comes from a target that uses the same 888 // code unit size and endianess for the type of string. 889 this->Kind = Kind; 890 this->IsPascal = IsPascal; 891 892 CharByteWidth = mapCharByteWidth(C.getTargetInfo(),Kind); 893 assert((Str.size()%CharByteWidth == 0) 894 && "size of data must be multiple of CharByteWidth"); 895 Length = Str.size()/CharByteWidth; 896 897 switch(CharByteWidth) { 898 case 1: { 899 char *AStrData = new (C) char[Length]; 900 std::memcpy(AStrData,Str.data(),Length*sizeof(*AStrData)); 901 StrData.asChar = AStrData; 902 break; 903 } 904 case 2: { 905 uint16_t *AStrData = new (C) uint16_t[Length]; 906 std::memcpy(AStrData,Str.data(),Length*sizeof(*AStrData)); 907 StrData.asUInt16 = AStrData; 908 break; 909 } 910 case 4: { 911 uint32_t *AStrData = new (C) uint32_t[Length]; 912 std::memcpy(AStrData,Str.data(),Length*sizeof(*AStrData)); 913 StrData.asUInt32 = AStrData; 914 break; 915 } 916 default: 917 assert(false && "unsupported CharByteWidth"); 918 } 919 } 920 921 /// getLocationOfByte - Return a source location that points to the specified 922 /// byte of this string literal. 923 /// 924 /// Strings are amazingly complex. They can be formed from multiple tokens and 925 /// can have escape sequences in them in addition to the usual trigraph and 926 /// escaped newline business. This routine handles this complexity. 927 /// 928 SourceLocation StringLiteral:: 929 getLocationOfByte(unsigned ByteNo, const SourceManager &SM, 930 const LangOptions &Features, const TargetInfo &Target) const { 931 assert((Kind == StringLiteral::Ascii || Kind == StringLiteral::UTF8) && 932 "Only narrow string literals are currently supported"); 933 934 // Loop over all of the tokens in this string until we find the one that 935 // contains the byte we're looking for. 936 unsigned TokNo = 0; 937 while (1) { 938 assert(TokNo < getNumConcatenated() && "Invalid byte number!"); 939 SourceLocation StrTokLoc = getStrTokenLoc(TokNo); 940 941 // Get the spelling of the string so that we can get the data that makes up 942 // the string literal, not the identifier for the macro it is potentially 943 // expanded through. 944 SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc); 945 946 // Re-lex the token to get its length and original spelling. 947 std::pair<FileID, unsigned> LocInfo =SM.getDecomposedLoc(StrTokSpellingLoc); 948 bool Invalid = false; 949 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 950 if (Invalid) 951 return StrTokSpellingLoc; 952 953 const char *StrData = Buffer.data()+LocInfo.second; 954 955 // Create a lexer starting at the beginning of this token. 956 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features, 957 Buffer.begin(), StrData, Buffer.end()); 958 Token TheTok; 959 TheLexer.LexFromRawLexer(TheTok); 960 961 // Use the StringLiteralParser to compute the length of the string in bytes. 962 StringLiteralParser SLP(&TheTok, 1, SM, Features, Target); 963 unsigned TokNumBytes = SLP.GetStringLength(); 964 965 // If the byte is in this token, return the location of the byte. 966 if (ByteNo < TokNumBytes || 967 (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) { 968 unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo); 969 970 // Now that we know the offset of the token in the spelling, use the 971 // preprocessor to get the offset in the original source. 972 return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features); 973 } 974 975 // Move to the next string token. 976 ++TokNo; 977 ByteNo -= TokNumBytes; 978 } 979 } 980 981 982 983 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it 984 /// corresponds to, e.g. "sizeof" or "[pre]++". 985 StringRef UnaryOperator::getOpcodeStr(Opcode Op) { 986 switch (Op) { 987 case UO_PostInc: return "++"; 988 case UO_PostDec: return "--"; 989 case UO_PreInc: return "++"; 990 case UO_PreDec: return "--"; 991 case UO_AddrOf: return "&"; 992 case UO_Deref: return "*"; 993 case UO_Plus: return "+"; 994 case UO_Minus: return "-"; 995 case UO_Not: return "~"; 996 case UO_LNot: return "!"; 997 case UO_Real: return "__real"; 998 case UO_Imag: return "__imag"; 999 case UO_Extension: return "__extension__"; 1000 } 1001 llvm_unreachable("Unknown unary operator"); 1002 } 1003 1004 UnaryOperatorKind 1005 UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) { 1006 switch (OO) { 1007 default: llvm_unreachable("No unary operator for overloaded function"); 1008 case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc; 1009 case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec; 1010 case OO_Amp: return UO_AddrOf; 1011 case OO_Star: return UO_Deref; 1012 case OO_Plus: return UO_Plus; 1013 case OO_Minus: return UO_Minus; 1014 case OO_Tilde: return UO_Not; 1015 case OO_Exclaim: return UO_LNot; 1016 } 1017 } 1018 1019 OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) { 1020 switch (Opc) { 1021 case UO_PostInc: case UO_PreInc: return OO_PlusPlus; 1022 case UO_PostDec: case UO_PreDec: return OO_MinusMinus; 1023 case UO_AddrOf: return OO_Amp; 1024 case UO_Deref: return OO_Star; 1025 case UO_Plus: return OO_Plus; 1026 case UO_Minus: return OO_Minus; 1027 case UO_Not: return OO_Tilde; 1028 case UO_LNot: return OO_Exclaim; 1029 default: return OO_None; 1030 } 1031 } 1032 1033 1034 //===----------------------------------------------------------------------===// 1035 // Postfix Operators. 1036 //===----------------------------------------------------------------------===// 1037 1038 CallExpr::CallExpr(ASTContext& C, StmtClass SC, Expr *fn, unsigned NumPreArgs, 1039 ArrayRef<Expr*> args, QualType t, ExprValueKind VK, 1040 SourceLocation rparenloc) 1041 : Expr(SC, t, VK, OK_Ordinary, 1042 fn->isTypeDependent(), 1043 fn->isValueDependent(), 1044 fn->isInstantiationDependent(), 1045 fn->containsUnexpandedParameterPack()), 1046 NumArgs(args.size()) { 1047 1048 SubExprs = new (C) Stmt*[args.size()+PREARGS_START+NumPreArgs]; 1049 SubExprs[FN] = fn; 1050 for (unsigned i = 0; i != args.size(); ++i) { 1051 if (args[i]->isTypeDependent()) 1052 ExprBits.TypeDependent = true; 1053 if (args[i]->isValueDependent()) 1054 ExprBits.ValueDependent = true; 1055 if (args[i]->isInstantiationDependent()) 1056 ExprBits.InstantiationDependent = true; 1057 if (args[i]->containsUnexpandedParameterPack()) 1058 ExprBits.ContainsUnexpandedParameterPack = true; 1059 1060 SubExprs[i+PREARGS_START+NumPreArgs] = args[i]; 1061 } 1062 1063 CallExprBits.NumPreArgs = NumPreArgs; 1064 RParenLoc = rparenloc; 1065 } 1066 1067 CallExpr::CallExpr(ASTContext& C, Expr *fn, ArrayRef<Expr*> args, 1068 QualType t, ExprValueKind VK, SourceLocation rparenloc) 1069 : Expr(CallExprClass, t, VK, OK_Ordinary, 1070 fn->isTypeDependent(), 1071 fn->isValueDependent(), 1072 fn->isInstantiationDependent(), 1073 fn->containsUnexpandedParameterPack()), 1074 NumArgs(args.size()) { 1075 1076 SubExprs = new (C) Stmt*[args.size()+PREARGS_START]; 1077 SubExprs[FN] = fn; 1078 for (unsigned i = 0; i != args.size(); ++i) { 1079 if (args[i]->isTypeDependent()) 1080 ExprBits.TypeDependent = true; 1081 if (args[i]->isValueDependent()) 1082 ExprBits.ValueDependent = true; 1083 if (args[i]->isInstantiationDependent()) 1084 ExprBits.InstantiationDependent = true; 1085 if (args[i]->containsUnexpandedParameterPack()) 1086 ExprBits.ContainsUnexpandedParameterPack = true; 1087 1088 SubExprs[i+PREARGS_START] = args[i]; 1089 } 1090 1091 CallExprBits.NumPreArgs = 0; 1092 RParenLoc = rparenloc; 1093 } 1094 1095 CallExpr::CallExpr(ASTContext &C, StmtClass SC, EmptyShell Empty) 1096 : Expr(SC, Empty), SubExprs(0), NumArgs(0) { 1097 // FIXME: Why do we allocate this? 1098 SubExprs = new (C) Stmt*[PREARGS_START]; 1099 CallExprBits.NumPreArgs = 0; 1100 } 1101 1102 CallExpr::CallExpr(ASTContext &C, StmtClass SC, unsigned NumPreArgs, 1103 EmptyShell Empty) 1104 : Expr(SC, Empty), SubExprs(0), NumArgs(0) { 1105 // FIXME: Why do we allocate this? 1106 SubExprs = new (C) Stmt*[PREARGS_START+NumPreArgs]; 1107 CallExprBits.NumPreArgs = NumPreArgs; 1108 } 1109 1110 Decl *CallExpr::getCalleeDecl() { 1111 Expr *CEE = getCallee()->IgnoreParenImpCasts(); 1112 1113 while (SubstNonTypeTemplateParmExpr *NTTP 1114 = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE)) { 1115 CEE = NTTP->getReplacement()->IgnoreParenCasts(); 1116 } 1117 1118 // If we're calling a dereference, look at the pointer instead. 1119 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) { 1120 if (BO->isPtrMemOp()) 1121 CEE = BO->getRHS()->IgnoreParenCasts(); 1122 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) { 1123 if (UO->getOpcode() == UO_Deref) 1124 CEE = UO->getSubExpr()->IgnoreParenCasts(); 1125 } 1126 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE)) 1127 return DRE->getDecl(); 1128 if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE)) 1129 return ME->getMemberDecl(); 1130 1131 return 0; 1132 } 1133 1134 FunctionDecl *CallExpr::getDirectCallee() { 1135 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl()); 1136 } 1137 1138 /// setNumArgs - This changes the number of arguments present in this call. 1139 /// Any orphaned expressions are deleted by this, and any new operands are set 1140 /// to null. 1141 void CallExpr::setNumArgs(ASTContext& C, unsigned NumArgs) { 1142 // No change, just return. 1143 if (NumArgs == getNumArgs()) return; 1144 1145 // If shrinking # arguments, just delete the extras and forgot them. 1146 if (NumArgs < getNumArgs()) { 1147 this->NumArgs = NumArgs; 1148 return; 1149 } 1150 1151 // Otherwise, we are growing the # arguments. New an bigger argument array. 1152 unsigned NumPreArgs = getNumPreArgs(); 1153 Stmt **NewSubExprs = new (C) Stmt*[NumArgs+PREARGS_START+NumPreArgs]; 1154 // Copy over args. 1155 for (unsigned i = 0; i != getNumArgs()+PREARGS_START+NumPreArgs; ++i) 1156 NewSubExprs[i] = SubExprs[i]; 1157 // Null out new args. 1158 for (unsigned i = getNumArgs()+PREARGS_START+NumPreArgs; 1159 i != NumArgs+PREARGS_START+NumPreArgs; ++i) 1160 NewSubExprs[i] = 0; 1161 1162 if (SubExprs) C.Deallocate(SubExprs); 1163 SubExprs = NewSubExprs; 1164 this->NumArgs = NumArgs; 1165 } 1166 1167 /// isBuiltinCall - If this is a call to a builtin, return the builtin ID. If 1168 /// not, return 0. 1169 unsigned CallExpr::isBuiltinCall() const { 1170 // All simple function calls (e.g. func()) are implicitly cast to pointer to 1171 // function. As a result, we try and obtain the DeclRefExpr from the 1172 // ImplicitCastExpr. 1173 const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee()); 1174 if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()). 1175 return 0; 1176 1177 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()); 1178 if (!DRE) 1179 return 0; 1180 1181 const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl()); 1182 if (!FDecl) 1183 return 0; 1184 1185 if (!FDecl->getIdentifier()) 1186 return 0; 1187 1188 return FDecl->getBuiltinID(); 1189 } 1190 1191 bool CallExpr::isUnevaluatedBuiltinCall(ASTContext &Ctx) const { 1192 if (unsigned BI = isBuiltinCall()) 1193 return Ctx.BuiltinInfo.isUnevaluated(BI); 1194 return false; 1195 } 1196 1197 QualType CallExpr::getCallReturnType() const { 1198 QualType CalleeType = getCallee()->getType(); 1199 if (const PointerType *FnTypePtr = CalleeType->getAs<PointerType>()) 1200 CalleeType = FnTypePtr->getPointeeType(); 1201 else if (const BlockPointerType *BPT = CalleeType->getAs<BlockPointerType>()) 1202 CalleeType = BPT->getPointeeType(); 1203 else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) 1204 // This should never be overloaded and so should never return null. 1205 CalleeType = Expr::findBoundMemberType(getCallee()); 1206 1207 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 1208 return FnType->getResultType(); 1209 } 1210 1211 SourceLocation CallExpr::getLocStart() const { 1212 if (isa<CXXOperatorCallExpr>(this)) 1213 return cast<CXXOperatorCallExpr>(this)->getLocStart(); 1214 1215 SourceLocation begin = getCallee()->getLocStart(); 1216 if (begin.isInvalid() && getNumArgs() > 0) 1217 begin = getArg(0)->getLocStart(); 1218 return begin; 1219 } 1220 SourceLocation CallExpr::getLocEnd() const { 1221 if (isa<CXXOperatorCallExpr>(this)) 1222 return cast<CXXOperatorCallExpr>(this)->getLocEnd(); 1223 1224 SourceLocation end = getRParenLoc(); 1225 if (end.isInvalid() && getNumArgs() > 0) 1226 end = getArg(getNumArgs() - 1)->getLocEnd(); 1227 return end; 1228 } 1229 1230 OffsetOfExpr *OffsetOfExpr::Create(ASTContext &C, QualType type, 1231 SourceLocation OperatorLoc, 1232 TypeSourceInfo *tsi, 1233 ArrayRef<OffsetOfNode> comps, 1234 ArrayRef<Expr*> exprs, 1235 SourceLocation RParenLoc) { 1236 void *Mem = C.Allocate(sizeof(OffsetOfExpr) + 1237 sizeof(OffsetOfNode) * comps.size() + 1238 sizeof(Expr*) * exprs.size()); 1239 1240 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs, 1241 RParenLoc); 1242 } 1243 1244 OffsetOfExpr *OffsetOfExpr::CreateEmpty(ASTContext &C, 1245 unsigned numComps, unsigned numExprs) { 1246 void *Mem = C.Allocate(sizeof(OffsetOfExpr) + 1247 sizeof(OffsetOfNode) * numComps + 1248 sizeof(Expr*) * numExprs); 1249 return new (Mem) OffsetOfExpr(numComps, numExprs); 1250 } 1251 1252 OffsetOfExpr::OffsetOfExpr(ASTContext &C, QualType type, 1253 SourceLocation OperatorLoc, TypeSourceInfo *tsi, 1254 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs, 1255 SourceLocation RParenLoc) 1256 : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary, 1257 /*TypeDependent=*/false, 1258 /*ValueDependent=*/tsi->getType()->isDependentType(), 1259 tsi->getType()->isInstantiationDependentType(), 1260 tsi->getType()->containsUnexpandedParameterPack()), 1261 OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi), 1262 NumComps(comps.size()), NumExprs(exprs.size()) 1263 { 1264 for (unsigned i = 0; i != comps.size(); ++i) { 1265 setComponent(i, comps[i]); 1266 } 1267 1268 for (unsigned i = 0; i != exprs.size(); ++i) { 1269 if (exprs[i]->isTypeDependent() || exprs[i]->isValueDependent()) 1270 ExprBits.ValueDependent = true; 1271 if (exprs[i]->containsUnexpandedParameterPack()) 1272 ExprBits.ContainsUnexpandedParameterPack = true; 1273 1274 setIndexExpr(i, exprs[i]); 1275 } 1276 } 1277 1278 IdentifierInfo *OffsetOfExpr::OffsetOfNode::getFieldName() const { 1279 assert(getKind() == Field || getKind() == Identifier); 1280 if (getKind() == Field) 1281 return getField()->getIdentifier(); 1282 1283 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask); 1284 } 1285 1286 MemberExpr *MemberExpr::Create(ASTContext &C, Expr *base, bool isarrow, 1287 NestedNameSpecifierLoc QualifierLoc, 1288 SourceLocation TemplateKWLoc, 1289 ValueDecl *memberdecl, 1290 DeclAccessPair founddecl, 1291 DeclarationNameInfo nameinfo, 1292 const TemplateArgumentListInfo *targs, 1293 QualType ty, 1294 ExprValueKind vk, 1295 ExprObjectKind ok) { 1296 std::size_t Size = sizeof(MemberExpr); 1297 1298 bool hasQualOrFound = (QualifierLoc || 1299 founddecl.getDecl() != memberdecl || 1300 founddecl.getAccess() != memberdecl->getAccess()); 1301 if (hasQualOrFound) 1302 Size += sizeof(MemberNameQualifier); 1303 1304 if (targs) 1305 Size += ASTTemplateKWAndArgsInfo::sizeFor(targs->size()); 1306 else if (TemplateKWLoc.isValid()) 1307 Size += ASTTemplateKWAndArgsInfo::sizeFor(0); 1308 1309 void *Mem = C.Allocate(Size, llvm::alignOf<MemberExpr>()); 1310 MemberExpr *E = new (Mem) MemberExpr(base, isarrow, memberdecl, nameinfo, 1311 ty, vk, ok); 1312 1313 if (hasQualOrFound) { 1314 // FIXME: Wrong. We should be looking at the member declaration we found. 1315 if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent()) { 1316 E->setValueDependent(true); 1317 E->setTypeDependent(true); 1318 E->setInstantiationDependent(true); 1319 } 1320 else if (QualifierLoc && 1321 QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent()) 1322 E->setInstantiationDependent(true); 1323 1324 E->HasQualifierOrFoundDecl = true; 1325 1326 MemberNameQualifier *NQ = E->getMemberQualifier(); 1327 NQ->QualifierLoc = QualifierLoc; 1328 NQ->FoundDecl = founddecl; 1329 } 1330 1331 E->HasTemplateKWAndArgsInfo = (targs || TemplateKWLoc.isValid()); 1332 1333 if (targs) { 1334 bool Dependent = false; 1335 bool InstantiationDependent = false; 1336 bool ContainsUnexpandedParameterPack = false; 1337 E->getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc, *targs, 1338 Dependent, 1339 InstantiationDependent, 1340 ContainsUnexpandedParameterPack); 1341 if (InstantiationDependent) 1342 E->setInstantiationDependent(true); 1343 } else if (TemplateKWLoc.isValid()) { 1344 E->getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc); 1345 } 1346 1347 return E; 1348 } 1349 1350 SourceLocation MemberExpr::getLocStart() const { 1351 if (isImplicitAccess()) { 1352 if (hasQualifier()) 1353 return getQualifierLoc().getBeginLoc(); 1354 return MemberLoc; 1355 } 1356 1357 // FIXME: We don't want this to happen. Rather, we should be able to 1358 // detect all kinds of implicit accesses more cleanly. 1359 SourceLocation BaseStartLoc = getBase()->getLocStart(); 1360 if (BaseStartLoc.isValid()) 1361 return BaseStartLoc; 1362 return MemberLoc; 1363 } 1364 SourceLocation MemberExpr::getLocEnd() const { 1365 SourceLocation EndLoc = getMemberNameInfo().getEndLoc(); 1366 if (hasExplicitTemplateArgs()) 1367 EndLoc = getRAngleLoc(); 1368 else if (EndLoc.isInvalid()) 1369 EndLoc = getBase()->getLocEnd(); 1370 return EndLoc; 1371 } 1372 1373 void CastExpr::CheckCastConsistency() const { 1374 switch (getCastKind()) { 1375 case CK_DerivedToBase: 1376 case CK_UncheckedDerivedToBase: 1377 case CK_DerivedToBaseMemberPointer: 1378 case CK_BaseToDerived: 1379 case CK_BaseToDerivedMemberPointer: 1380 assert(!path_empty() && "Cast kind should have a base path!"); 1381 break; 1382 1383 case CK_CPointerToObjCPointerCast: 1384 assert(getType()->isObjCObjectPointerType()); 1385 assert(getSubExpr()->getType()->isPointerType()); 1386 goto CheckNoBasePath; 1387 1388 case CK_BlockPointerToObjCPointerCast: 1389 assert(getType()->isObjCObjectPointerType()); 1390 assert(getSubExpr()->getType()->isBlockPointerType()); 1391 goto CheckNoBasePath; 1392 1393 case CK_ReinterpretMemberPointer: 1394 assert(getType()->isMemberPointerType()); 1395 assert(getSubExpr()->getType()->isMemberPointerType()); 1396 goto CheckNoBasePath; 1397 1398 case CK_BitCast: 1399 // Arbitrary casts to C pointer types count as bitcasts. 1400 // Otherwise, we should only have block and ObjC pointer casts 1401 // here if they stay within the type kind. 1402 if (!getType()->isPointerType()) { 1403 assert(getType()->isObjCObjectPointerType() == 1404 getSubExpr()->getType()->isObjCObjectPointerType()); 1405 assert(getType()->isBlockPointerType() == 1406 getSubExpr()->getType()->isBlockPointerType()); 1407 } 1408 goto CheckNoBasePath; 1409 1410 case CK_AnyPointerToBlockPointerCast: 1411 assert(getType()->isBlockPointerType()); 1412 assert(getSubExpr()->getType()->isAnyPointerType() && 1413 !getSubExpr()->getType()->isBlockPointerType()); 1414 goto CheckNoBasePath; 1415 1416 case CK_CopyAndAutoreleaseBlockObject: 1417 assert(getType()->isBlockPointerType()); 1418 assert(getSubExpr()->getType()->isBlockPointerType()); 1419 goto CheckNoBasePath; 1420 1421 case CK_FunctionToPointerDecay: 1422 assert(getType()->isPointerType()); 1423 assert(getSubExpr()->getType()->isFunctionType()); 1424 goto CheckNoBasePath; 1425 1426 // These should not have an inheritance path. 1427 case CK_Dynamic: 1428 case CK_ToUnion: 1429 case CK_ArrayToPointerDecay: 1430 case CK_NullToMemberPointer: 1431 case CK_NullToPointer: 1432 case CK_ConstructorConversion: 1433 case CK_IntegralToPointer: 1434 case CK_PointerToIntegral: 1435 case CK_ToVoid: 1436 case CK_VectorSplat: 1437 case CK_IntegralCast: 1438 case CK_IntegralToFloating: 1439 case CK_FloatingToIntegral: 1440 case CK_FloatingCast: 1441 case CK_ObjCObjectLValueCast: 1442 case CK_FloatingRealToComplex: 1443 case CK_FloatingComplexToReal: 1444 case CK_FloatingComplexCast: 1445 case CK_FloatingComplexToIntegralComplex: 1446 case CK_IntegralRealToComplex: 1447 case CK_IntegralComplexToReal: 1448 case CK_IntegralComplexCast: 1449 case CK_IntegralComplexToFloatingComplex: 1450 case CK_ARCProduceObject: 1451 case CK_ARCConsumeObject: 1452 case CK_ARCReclaimReturnedObject: 1453 case CK_ARCExtendBlockObject: 1454 case CK_ZeroToOCLEvent: 1455 assert(!getType()->isBooleanType() && "unheralded conversion to bool"); 1456 goto CheckNoBasePath; 1457 1458 case CK_Dependent: 1459 case CK_LValueToRValue: 1460 case CK_NoOp: 1461 case CK_AtomicToNonAtomic: 1462 case CK_NonAtomicToAtomic: 1463 case CK_PointerToBoolean: 1464 case CK_IntegralToBoolean: 1465 case CK_FloatingToBoolean: 1466 case CK_MemberPointerToBoolean: 1467 case CK_FloatingComplexToBoolean: 1468 case CK_IntegralComplexToBoolean: 1469 case CK_LValueBitCast: // -> bool& 1470 case CK_UserDefinedConversion: // operator bool() 1471 case CK_BuiltinFnToFnPtr: 1472 CheckNoBasePath: 1473 assert(path_empty() && "Cast kind should not have a base path!"); 1474 break; 1475 } 1476 } 1477 1478 const char *CastExpr::getCastKindName() const { 1479 switch (getCastKind()) { 1480 case CK_Dependent: 1481 return "Dependent"; 1482 case CK_BitCast: 1483 return "BitCast"; 1484 case CK_LValueBitCast: 1485 return "LValueBitCast"; 1486 case CK_LValueToRValue: 1487 return "LValueToRValue"; 1488 case CK_NoOp: 1489 return "NoOp"; 1490 case CK_BaseToDerived: 1491 return "BaseToDerived"; 1492 case CK_DerivedToBase: 1493 return "DerivedToBase"; 1494 case CK_UncheckedDerivedToBase: 1495 return "UncheckedDerivedToBase"; 1496 case CK_Dynamic: 1497 return "Dynamic"; 1498 case CK_ToUnion: 1499 return "ToUnion"; 1500 case CK_ArrayToPointerDecay: 1501 return "ArrayToPointerDecay"; 1502 case CK_FunctionToPointerDecay: 1503 return "FunctionToPointerDecay"; 1504 case CK_NullToMemberPointer: 1505 return "NullToMemberPointer"; 1506 case CK_NullToPointer: 1507 return "NullToPointer"; 1508 case CK_BaseToDerivedMemberPointer: 1509 return "BaseToDerivedMemberPointer"; 1510 case CK_DerivedToBaseMemberPointer: 1511 return "DerivedToBaseMemberPointer"; 1512 case CK_ReinterpretMemberPointer: 1513 return "ReinterpretMemberPointer"; 1514 case CK_UserDefinedConversion: 1515 return "UserDefinedConversion"; 1516 case CK_ConstructorConversion: 1517 return "ConstructorConversion"; 1518 case CK_IntegralToPointer: 1519 return "IntegralToPointer"; 1520 case CK_PointerToIntegral: 1521 return "PointerToIntegral"; 1522 case CK_PointerToBoolean: 1523 return "PointerToBoolean"; 1524 case CK_ToVoid: 1525 return "ToVoid"; 1526 case CK_VectorSplat: 1527 return "VectorSplat"; 1528 case CK_IntegralCast: 1529 return "IntegralCast"; 1530 case CK_IntegralToBoolean: 1531 return "IntegralToBoolean"; 1532 case CK_IntegralToFloating: 1533 return "IntegralToFloating"; 1534 case CK_FloatingToIntegral: 1535 return "FloatingToIntegral"; 1536 case CK_FloatingCast: 1537 return "FloatingCast"; 1538 case CK_FloatingToBoolean: 1539 return "FloatingToBoolean"; 1540 case CK_MemberPointerToBoolean: 1541 return "MemberPointerToBoolean"; 1542 case CK_CPointerToObjCPointerCast: 1543 return "CPointerToObjCPointerCast"; 1544 case CK_BlockPointerToObjCPointerCast: 1545 return "BlockPointerToObjCPointerCast"; 1546 case CK_AnyPointerToBlockPointerCast: 1547 return "AnyPointerToBlockPointerCast"; 1548 case CK_ObjCObjectLValueCast: 1549 return "ObjCObjectLValueCast"; 1550 case CK_FloatingRealToComplex: 1551 return "FloatingRealToComplex"; 1552 case CK_FloatingComplexToReal: 1553 return "FloatingComplexToReal"; 1554 case CK_FloatingComplexToBoolean: 1555 return "FloatingComplexToBoolean"; 1556 case CK_FloatingComplexCast: 1557 return "FloatingComplexCast"; 1558 case CK_FloatingComplexToIntegralComplex: 1559 return "FloatingComplexToIntegralComplex"; 1560 case CK_IntegralRealToComplex: 1561 return "IntegralRealToComplex"; 1562 case CK_IntegralComplexToReal: 1563 return "IntegralComplexToReal"; 1564 case CK_IntegralComplexToBoolean: 1565 return "IntegralComplexToBoolean"; 1566 case CK_IntegralComplexCast: 1567 return "IntegralComplexCast"; 1568 case CK_IntegralComplexToFloatingComplex: 1569 return "IntegralComplexToFloatingComplex"; 1570 case CK_ARCConsumeObject: 1571 return "ARCConsumeObject"; 1572 case CK_ARCProduceObject: 1573 return "ARCProduceObject"; 1574 case CK_ARCReclaimReturnedObject: 1575 return "ARCReclaimReturnedObject"; 1576 case CK_ARCExtendBlockObject: 1577 return "ARCCExtendBlockObject"; 1578 case CK_AtomicToNonAtomic: 1579 return "AtomicToNonAtomic"; 1580 case CK_NonAtomicToAtomic: 1581 return "NonAtomicToAtomic"; 1582 case CK_CopyAndAutoreleaseBlockObject: 1583 return "CopyAndAutoreleaseBlockObject"; 1584 case CK_BuiltinFnToFnPtr: 1585 return "BuiltinFnToFnPtr"; 1586 case CK_ZeroToOCLEvent: 1587 return "ZeroToOCLEvent"; 1588 } 1589 1590 llvm_unreachable("Unhandled cast kind!"); 1591 } 1592 1593 Expr *CastExpr::getSubExprAsWritten() { 1594 Expr *SubExpr = 0; 1595 CastExpr *E = this; 1596 do { 1597 SubExpr = E->getSubExpr(); 1598 1599 // Skip through reference binding to temporary. 1600 if (MaterializeTemporaryExpr *Materialize 1601 = dyn_cast<MaterializeTemporaryExpr>(SubExpr)) 1602 SubExpr = Materialize->GetTemporaryExpr(); 1603 1604 // Skip any temporary bindings; they're implicit. 1605 if (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(SubExpr)) 1606 SubExpr = Binder->getSubExpr(); 1607 1608 // Conversions by constructor and conversion functions have a 1609 // subexpression describing the call; strip it off. 1610 if (E->getCastKind() == CK_ConstructorConversion) 1611 SubExpr = cast<CXXConstructExpr>(SubExpr)->getArg(0); 1612 else if (E->getCastKind() == CK_UserDefinedConversion) 1613 SubExpr = cast<CXXMemberCallExpr>(SubExpr)->getImplicitObjectArgument(); 1614 1615 // If the subexpression we're left with is an implicit cast, look 1616 // through that, too. 1617 } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr))); 1618 1619 return SubExpr; 1620 } 1621 1622 CXXBaseSpecifier **CastExpr::path_buffer() { 1623 switch (getStmtClass()) { 1624 #define ABSTRACT_STMT(x) 1625 #define CASTEXPR(Type, Base) \ 1626 case Stmt::Type##Class: \ 1627 return reinterpret_cast<CXXBaseSpecifier**>(static_cast<Type*>(this)+1); 1628 #define STMT(Type, Base) 1629 #include "clang/AST/StmtNodes.inc" 1630 default: 1631 llvm_unreachable("non-cast expressions not possible here"); 1632 } 1633 } 1634 1635 void CastExpr::setCastPath(const CXXCastPath &Path) { 1636 assert(Path.size() == path_size()); 1637 memcpy(path_buffer(), Path.data(), Path.size() * sizeof(CXXBaseSpecifier*)); 1638 } 1639 1640 ImplicitCastExpr *ImplicitCastExpr::Create(ASTContext &C, QualType T, 1641 CastKind Kind, Expr *Operand, 1642 const CXXCastPath *BasePath, 1643 ExprValueKind VK) { 1644 unsigned PathSize = (BasePath ? BasePath->size() : 0); 1645 void *Buffer = 1646 C.Allocate(sizeof(ImplicitCastExpr) + PathSize * sizeof(CXXBaseSpecifier*)); 1647 ImplicitCastExpr *E = 1648 new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK); 1649 if (PathSize) E->setCastPath(*BasePath); 1650 return E; 1651 } 1652 1653 ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(ASTContext &C, 1654 unsigned PathSize) { 1655 void *Buffer = 1656 C.Allocate(sizeof(ImplicitCastExpr) + PathSize * sizeof(CXXBaseSpecifier*)); 1657 return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize); 1658 } 1659 1660 1661 CStyleCastExpr *CStyleCastExpr::Create(ASTContext &C, QualType T, 1662 ExprValueKind VK, CastKind K, Expr *Op, 1663 const CXXCastPath *BasePath, 1664 TypeSourceInfo *WrittenTy, 1665 SourceLocation L, SourceLocation R) { 1666 unsigned PathSize = (BasePath ? BasePath->size() : 0); 1667 void *Buffer = 1668 C.Allocate(sizeof(CStyleCastExpr) + PathSize * sizeof(CXXBaseSpecifier*)); 1669 CStyleCastExpr *E = 1670 new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R); 1671 if (PathSize) E->setCastPath(*BasePath); 1672 return E; 1673 } 1674 1675 CStyleCastExpr *CStyleCastExpr::CreateEmpty(ASTContext &C, unsigned PathSize) { 1676 void *Buffer = 1677 C.Allocate(sizeof(CStyleCastExpr) + PathSize * sizeof(CXXBaseSpecifier*)); 1678 return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize); 1679 } 1680 1681 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it 1682 /// corresponds to, e.g. "<<=". 1683 StringRef BinaryOperator::getOpcodeStr(Opcode Op) { 1684 switch (Op) { 1685 case BO_PtrMemD: return ".*"; 1686 case BO_PtrMemI: return "->*"; 1687 case BO_Mul: return "*"; 1688 case BO_Div: return "/"; 1689 case BO_Rem: return "%"; 1690 case BO_Add: return "+"; 1691 case BO_Sub: return "-"; 1692 case BO_Shl: return "<<"; 1693 case BO_Shr: return ">>"; 1694 case BO_LT: return "<"; 1695 case BO_GT: return ">"; 1696 case BO_LE: return "<="; 1697 case BO_GE: return ">="; 1698 case BO_EQ: return "=="; 1699 case BO_NE: return "!="; 1700 case BO_And: return "&"; 1701 case BO_Xor: return "^"; 1702 case BO_Or: return "|"; 1703 case BO_LAnd: return "&&"; 1704 case BO_LOr: return "||"; 1705 case BO_Assign: return "="; 1706 case BO_MulAssign: return "*="; 1707 case BO_DivAssign: return "/="; 1708 case BO_RemAssign: return "%="; 1709 case BO_AddAssign: return "+="; 1710 case BO_SubAssign: return "-="; 1711 case BO_ShlAssign: return "<<="; 1712 case BO_ShrAssign: return ">>="; 1713 case BO_AndAssign: return "&="; 1714 case BO_XorAssign: return "^="; 1715 case BO_OrAssign: return "|="; 1716 case BO_Comma: return ","; 1717 } 1718 1719 llvm_unreachable("Invalid OpCode!"); 1720 } 1721 1722 BinaryOperatorKind 1723 BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) { 1724 switch (OO) { 1725 default: llvm_unreachable("Not an overloadable binary operator"); 1726 case OO_Plus: return BO_Add; 1727 case OO_Minus: return BO_Sub; 1728 case OO_Star: return BO_Mul; 1729 case OO_Slash: return BO_Div; 1730 case OO_Percent: return BO_Rem; 1731 case OO_Caret: return BO_Xor; 1732 case OO_Amp: return BO_And; 1733 case OO_Pipe: return BO_Or; 1734 case OO_Equal: return BO_Assign; 1735 case OO_Less: return BO_LT; 1736 case OO_Greater: return BO_GT; 1737 case OO_PlusEqual: return BO_AddAssign; 1738 case OO_MinusEqual: return BO_SubAssign; 1739 case OO_StarEqual: return BO_MulAssign; 1740 case OO_SlashEqual: return BO_DivAssign; 1741 case OO_PercentEqual: return BO_RemAssign; 1742 case OO_CaretEqual: return BO_XorAssign; 1743 case OO_AmpEqual: return BO_AndAssign; 1744 case OO_PipeEqual: return BO_OrAssign; 1745 case OO_LessLess: return BO_Shl; 1746 case OO_GreaterGreater: return BO_Shr; 1747 case OO_LessLessEqual: return BO_ShlAssign; 1748 case OO_GreaterGreaterEqual: return BO_ShrAssign; 1749 case OO_EqualEqual: return BO_EQ; 1750 case OO_ExclaimEqual: return BO_NE; 1751 case OO_LessEqual: return BO_LE; 1752 case OO_GreaterEqual: return BO_GE; 1753 case OO_AmpAmp: return BO_LAnd; 1754 case OO_PipePipe: return BO_LOr; 1755 case OO_Comma: return BO_Comma; 1756 case OO_ArrowStar: return BO_PtrMemI; 1757 } 1758 } 1759 1760 OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) { 1761 static const OverloadedOperatorKind OverOps[] = { 1762 /* .* Cannot be overloaded */OO_None, OO_ArrowStar, 1763 OO_Star, OO_Slash, OO_Percent, 1764 OO_Plus, OO_Minus, 1765 OO_LessLess, OO_GreaterGreater, 1766 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual, 1767 OO_EqualEqual, OO_ExclaimEqual, 1768 OO_Amp, 1769 OO_Caret, 1770 OO_Pipe, 1771 OO_AmpAmp, 1772 OO_PipePipe, 1773 OO_Equal, OO_StarEqual, 1774 OO_SlashEqual, OO_PercentEqual, 1775 OO_PlusEqual, OO_MinusEqual, 1776 OO_LessLessEqual, OO_GreaterGreaterEqual, 1777 OO_AmpEqual, OO_CaretEqual, 1778 OO_PipeEqual, 1779 OO_Comma 1780 }; 1781 return OverOps[Opc]; 1782 } 1783 1784 InitListExpr::InitListExpr(ASTContext &C, SourceLocation lbraceloc, 1785 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc) 1786 : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false, 1787 false, false), 1788 InitExprs(C, initExprs.size()), 1789 LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), AltForm(0, true) 1790 { 1791 sawArrayRangeDesignator(false); 1792 for (unsigned I = 0; I != initExprs.size(); ++I) { 1793 if (initExprs[I]->isTypeDependent()) 1794 ExprBits.TypeDependent = true; 1795 if (initExprs[I]->isValueDependent()) 1796 ExprBits.ValueDependent = true; 1797 if (initExprs[I]->isInstantiationDependent()) 1798 ExprBits.InstantiationDependent = true; 1799 if (initExprs[I]->containsUnexpandedParameterPack()) 1800 ExprBits.ContainsUnexpandedParameterPack = true; 1801 } 1802 1803 InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end()); 1804 } 1805 1806 void InitListExpr::reserveInits(ASTContext &C, unsigned NumInits) { 1807 if (NumInits > InitExprs.size()) 1808 InitExprs.reserve(C, NumInits); 1809 } 1810 1811 void InitListExpr::resizeInits(ASTContext &C, unsigned NumInits) { 1812 InitExprs.resize(C, NumInits, 0); 1813 } 1814 1815 Expr *InitListExpr::updateInit(ASTContext &C, unsigned Init, Expr *expr) { 1816 if (Init >= InitExprs.size()) { 1817 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, 0); 1818 InitExprs.back() = expr; 1819 return 0; 1820 } 1821 1822 Expr *Result = cast_or_null<Expr>(InitExprs[Init]); 1823 InitExprs[Init] = expr; 1824 return Result; 1825 } 1826 1827 void InitListExpr::setArrayFiller(Expr *filler) { 1828 assert(!hasArrayFiller() && "Filler already set!"); 1829 ArrayFillerOrUnionFieldInit = filler; 1830 // Fill out any "holes" in the array due to designated initializers. 1831 Expr **inits = getInits(); 1832 for (unsigned i = 0, e = getNumInits(); i != e; ++i) 1833 if (inits[i] == 0) 1834 inits[i] = filler; 1835 } 1836 1837 bool InitListExpr::isStringLiteralInit() const { 1838 if (getNumInits() != 1) 1839 return false; 1840 const ArrayType *AT = getType()->getAsArrayTypeUnsafe(); 1841 if (!AT || !AT->getElementType()->isIntegerType()) 1842 return false; 1843 const Expr *Init = getInit(0)->IgnoreParens(); 1844 return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init); 1845 } 1846 1847 SourceLocation InitListExpr::getLocStart() const { 1848 if (InitListExpr *SyntacticForm = getSyntacticForm()) 1849 return SyntacticForm->getLocStart(); 1850 SourceLocation Beg = LBraceLoc; 1851 if (Beg.isInvalid()) { 1852 // Find the first non-null initializer. 1853 for (InitExprsTy::const_iterator I = InitExprs.begin(), 1854 E = InitExprs.end(); 1855 I != E; ++I) { 1856 if (Stmt *S = *I) { 1857 Beg = S->getLocStart(); 1858 break; 1859 } 1860 } 1861 } 1862 return Beg; 1863 } 1864 1865 SourceLocation InitListExpr::getLocEnd() const { 1866 if (InitListExpr *SyntacticForm = getSyntacticForm()) 1867 return SyntacticForm->getLocEnd(); 1868 SourceLocation End = RBraceLoc; 1869 if (End.isInvalid()) { 1870 // Find the first non-null initializer from the end. 1871 for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(), 1872 E = InitExprs.rend(); 1873 I != E; ++I) { 1874 if (Stmt *S = *I) { 1875 End = S->getLocEnd(); 1876 break; 1877 } 1878 } 1879 } 1880 return End; 1881 } 1882 1883 /// getFunctionType - Return the underlying function type for this block. 1884 /// 1885 const FunctionProtoType *BlockExpr::getFunctionType() const { 1886 // The block pointer is never sugared, but the function type might be. 1887 return cast<BlockPointerType>(getType()) 1888 ->getPointeeType()->castAs<FunctionProtoType>(); 1889 } 1890 1891 SourceLocation BlockExpr::getCaretLocation() const { 1892 return TheBlock->getCaretLocation(); 1893 } 1894 const Stmt *BlockExpr::getBody() const { 1895 return TheBlock->getBody(); 1896 } 1897 Stmt *BlockExpr::getBody() { 1898 return TheBlock->getBody(); 1899 } 1900 1901 1902 //===----------------------------------------------------------------------===// 1903 // Generic Expression Routines 1904 //===----------------------------------------------------------------------===// 1905 1906 /// isUnusedResultAWarning - Return true if this immediate expression should 1907 /// be warned about if the result is unused. If so, fill in Loc and Ranges 1908 /// with location to warn on and the source range[s] to report with the 1909 /// warning. 1910 bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc, 1911 SourceRange &R1, SourceRange &R2, 1912 ASTContext &Ctx) const { 1913 // Don't warn if the expr is type dependent. The type could end up 1914 // instantiating to void. 1915 if (isTypeDependent()) 1916 return false; 1917 1918 switch (getStmtClass()) { 1919 default: 1920 if (getType()->isVoidType()) 1921 return false; 1922 WarnE = this; 1923 Loc = getExprLoc(); 1924 R1 = getSourceRange(); 1925 return true; 1926 case ParenExprClass: 1927 return cast<ParenExpr>(this)->getSubExpr()-> 1928 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); 1929 case GenericSelectionExprClass: 1930 return cast<GenericSelectionExpr>(this)->getResultExpr()-> 1931 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); 1932 case ChooseExprClass: 1933 return cast<ChooseExpr>(this)->getChosenSubExpr()-> 1934 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); 1935 case UnaryOperatorClass: { 1936 const UnaryOperator *UO = cast<UnaryOperator>(this); 1937 1938 switch (UO->getOpcode()) { 1939 case UO_Plus: 1940 case UO_Minus: 1941 case UO_AddrOf: 1942 case UO_Not: 1943 case UO_LNot: 1944 case UO_Deref: 1945 break; 1946 case UO_PostInc: 1947 case UO_PostDec: 1948 case UO_PreInc: 1949 case UO_PreDec: // ++/-- 1950 return false; // Not a warning. 1951 case UO_Real: 1952 case UO_Imag: 1953 // accessing a piece of a volatile complex is a side-effect. 1954 if (Ctx.getCanonicalType(UO->getSubExpr()->getType()) 1955 .isVolatileQualified()) 1956 return false; 1957 break; 1958 case UO_Extension: 1959 return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); 1960 } 1961 WarnE = this; 1962 Loc = UO->getOperatorLoc(); 1963 R1 = UO->getSubExpr()->getSourceRange(); 1964 return true; 1965 } 1966 case BinaryOperatorClass: { 1967 const BinaryOperator *BO = cast<BinaryOperator>(this); 1968 switch (BO->getOpcode()) { 1969 default: 1970 break; 1971 // Consider the RHS of comma for side effects. LHS was checked by 1972 // Sema::CheckCommaOperands. 1973 case BO_Comma: 1974 // ((foo = <blah>), 0) is an idiom for hiding the result (and 1975 // lvalue-ness) of an assignment written in a macro. 1976 if (IntegerLiteral *IE = 1977 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens())) 1978 if (IE->getValue() == 0) 1979 return false; 1980 return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); 1981 // Consider '||', '&&' to have side effects if the LHS or RHS does. 1982 case BO_LAnd: 1983 case BO_LOr: 1984 if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) || 1985 !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx)) 1986 return false; 1987 break; 1988 } 1989 if (BO->isAssignmentOp()) 1990 return false; 1991 WarnE = this; 1992 Loc = BO->getOperatorLoc(); 1993 R1 = BO->getLHS()->getSourceRange(); 1994 R2 = BO->getRHS()->getSourceRange(); 1995 return true; 1996 } 1997 case CompoundAssignOperatorClass: 1998 case VAArgExprClass: 1999 case AtomicExprClass: 2000 return false; 2001 2002 case ConditionalOperatorClass: { 2003 // If only one of the LHS or RHS is a warning, the operator might 2004 // be being used for control flow. Only warn if both the LHS and 2005 // RHS are warnings. 2006 const ConditionalOperator *Exp = cast<ConditionalOperator>(this); 2007 if (!Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx)) 2008 return false; 2009 if (!Exp->getLHS()) 2010 return true; 2011 return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); 2012 } 2013 2014 case MemberExprClass: 2015 WarnE = this; 2016 Loc = cast<MemberExpr>(this)->getMemberLoc(); 2017 R1 = SourceRange(Loc, Loc); 2018 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange(); 2019 return true; 2020 2021 case ArraySubscriptExprClass: 2022 WarnE = this; 2023 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc(); 2024 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange(); 2025 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange(); 2026 return true; 2027 2028 case CXXOperatorCallExprClass: { 2029 // We warn about operator== and operator!= even when user-defined operator 2030 // overloads as there is no reasonable way to define these such that they 2031 // have non-trivial, desirable side-effects. See the -Wunused-comparison 2032 // warning: these operators are commonly typo'ed, and so warning on them 2033 // provides additional value as well. If this list is updated, 2034 // DiagnoseUnusedComparison should be as well. 2035 const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this); 2036 if (Op->getOperator() == OO_EqualEqual || 2037 Op->getOperator() == OO_ExclaimEqual) { 2038 WarnE = this; 2039 Loc = Op->getOperatorLoc(); 2040 R1 = Op->getSourceRange(); 2041 return true; 2042 } 2043 2044 // Fallthrough for generic call handling. 2045 } 2046 case CallExprClass: 2047 case CXXMemberCallExprClass: 2048 case UserDefinedLiteralClass: { 2049 // If this is a direct call, get the callee. 2050 const CallExpr *CE = cast<CallExpr>(this); 2051 if (const Decl *FD = CE->getCalleeDecl()) { 2052 // If the callee has attribute pure, const, or warn_unused_result, warn 2053 // about it. void foo() { strlen("bar"); } should warn. 2054 // 2055 // Note: If new cases are added here, DiagnoseUnusedExprResult should be 2056 // updated to match for QoI. 2057 if (FD->getAttr<WarnUnusedResultAttr>() || 2058 FD->getAttr<PureAttr>() || FD->getAttr<ConstAttr>()) { 2059 WarnE = this; 2060 Loc = CE->getCallee()->getLocStart(); 2061 R1 = CE->getCallee()->getSourceRange(); 2062 2063 if (unsigned NumArgs = CE->getNumArgs()) 2064 R2 = SourceRange(CE->getArg(0)->getLocStart(), 2065 CE->getArg(NumArgs-1)->getLocEnd()); 2066 return true; 2067 } 2068 } 2069 return false; 2070 } 2071 2072 // If we don't know precisely what we're looking at, let's not warn. 2073 case UnresolvedLookupExprClass: 2074 case CXXUnresolvedConstructExprClass: 2075 return false; 2076 2077 case CXXTemporaryObjectExprClass: 2078 case CXXConstructExprClass: { 2079 if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) { 2080 if (Type->hasAttr<WarnUnusedAttr>()) { 2081 WarnE = this; 2082 Loc = getLocStart(); 2083 R1 = getSourceRange(); 2084 return true; 2085 } 2086 } 2087 return false; 2088 } 2089 2090 case ObjCMessageExprClass: { 2091 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this); 2092 if (Ctx.getLangOpts().ObjCAutoRefCount && 2093 ME->isInstanceMessage() && 2094 !ME->getType()->isVoidType() && 2095 ME->getMethodFamily() == OMF_init) { 2096 WarnE = this; 2097 Loc = getExprLoc(); 2098 R1 = ME->getSourceRange(); 2099 return true; 2100 } 2101 2102 const ObjCMethodDecl *MD = ME->getMethodDecl(); 2103 if (MD && MD->getAttr<WarnUnusedResultAttr>()) { 2104 WarnE = this; 2105 Loc = getExprLoc(); 2106 return true; 2107 } 2108 return false; 2109 } 2110 2111 case ObjCPropertyRefExprClass: 2112 WarnE = this; 2113 Loc = getExprLoc(); 2114 R1 = getSourceRange(); 2115 return true; 2116 2117 case PseudoObjectExprClass: { 2118 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this); 2119 2120 // Only complain about things that have the form of a getter. 2121 if (isa<UnaryOperator>(PO->getSyntacticForm()) || 2122 isa<BinaryOperator>(PO->getSyntacticForm())) 2123 return false; 2124 2125 WarnE = this; 2126 Loc = getExprLoc(); 2127 R1 = getSourceRange(); 2128 return true; 2129 } 2130 2131 case StmtExprClass: { 2132 // Statement exprs don't logically have side effects themselves, but are 2133 // sometimes used in macros in ways that give them a type that is unused. 2134 // For example ({ blah; foo(); }) will end up with a type if foo has a type. 2135 // however, if the result of the stmt expr is dead, we don't want to emit a 2136 // warning. 2137 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt(); 2138 if (!CS->body_empty()) { 2139 if (const Expr *E = dyn_cast<Expr>(CS->body_back())) 2140 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); 2141 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back())) 2142 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt())) 2143 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); 2144 } 2145 2146 if (getType()->isVoidType()) 2147 return false; 2148 WarnE = this; 2149 Loc = cast<StmtExpr>(this)->getLParenLoc(); 2150 R1 = getSourceRange(); 2151 return true; 2152 } 2153 case CXXFunctionalCastExprClass: 2154 case CStyleCastExprClass: { 2155 // Ignore an explicit cast to void unless the operand is a non-trivial 2156 // volatile lvalue. 2157 const CastExpr *CE = cast<CastExpr>(this); 2158 if (CE->getCastKind() == CK_ToVoid) { 2159 if (CE->getSubExpr()->isGLValue() && 2160 CE->getSubExpr()->getType().isVolatileQualified()) { 2161 const DeclRefExpr *DRE = 2162 dyn_cast<DeclRefExpr>(CE->getSubExpr()->IgnoreParens()); 2163 if (!(DRE && isa<VarDecl>(DRE->getDecl()) && 2164 cast<VarDecl>(DRE->getDecl())->hasLocalStorage())) { 2165 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, 2166 R1, R2, Ctx); 2167 } 2168 } 2169 return false; 2170 } 2171 2172 // If this is a cast to a constructor conversion, check the operand. 2173 // Otherwise, the result of the cast is unused. 2174 if (CE->getCastKind() == CK_ConstructorConversion) 2175 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); 2176 2177 WarnE = this; 2178 if (const CXXFunctionalCastExpr *CXXCE = 2179 dyn_cast<CXXFunctionalCastExpr>(this)) { 2180 Loc = CXXCE->getTypeBeginLoc(); 2181 R1 = CXXCE->getSubExpr()->getSourceRange(); 2182 } else { 2183 const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this); 2184 Loc = CStyleCE->getLParenLoc(); 2185 R1 = CStyleCE->getSubExpr()->getSourceRange(); 2186 } 2187 return true; 2188 } 2189 case ImplicitCastExprClass: { 2190 const CastExpr *ICE = cast<ImplicitCastExpr>(this); 2191 2192 // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect. 2193 if (ICE->getCastKind() == CK_LValueToRValue && 2194 ICE->getSubExpr()->getType().isVolatileQualified()) 2195 return false; 2196 2197 return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); 2198 } 2199 case CXXDefaultArgExprClass: 2200 return (cast<CXXDefaultArgExpr>(this) 2201 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx)); 2202 case CXXDefaultInitExprClass: 2203 return (cast<CXXDefaultInitExpr>(this) 2204 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx)); 2205 2206 case CXXNewExprClass: 2207 // FIXME: In theory, there might be new expressions that don't have side 2208 // effects (e.g. a placement new with an uninitialized POD). 2209 case CXXDeleteExprClass: 2210 return false; 2211 case CXXBindTemporaryExprClass: 2212 return (cast<CXXBindTemporaryExpr>(this) 2213 ->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx)); 2214 case ExprWithCleanupsClass: 2215 return (cast<ExprWithCleanups>(this) 2216 ->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx)); 2217 } 2218 } 2219 2220 /// isOBJCGCCandidate - Check if an expression is objc gc'able. 2221 /// returns true, if it is; false otherwise. 2222 bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const { 2223 const Expr *E = IgnoreParens(); 2224 switch (E->getStmtClass()) { 2225 default: 2226 return false; 2227 case ObjCIvarRefExprClass: 2228 return true; 2229 case Expr::UnaryOperatorClass: 2230 return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx); 2231 case ImplicitCastExprClass: 2232 return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx); 2233 case MaterializeTemporaryExprClass: 2234 return cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr() 2235 ->isOBJCGCCandidate(Ctx); 2236 case CStyleCastExprClass: 2237 return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx); 2238 case DeclRefExprClass: { 2239 const Decl *D = cast<DeclRefExpr>(E)->getDecl(); 2240 2241 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2242 if (VD->hasGlobalStorage()) 2243 return true; 2244 QualType T = VD->getType(); 2245 // dereferencing to a pointer is always a gc'able candidate, 2246 // unless it is __weak. 2247 return T->isPointerType() && 2248 (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak); 2249 } 2250 return false; 2251 } 2252 case MemberExprClass: { 2253 const MemberExpr *M = cast<MemberExpr>(E); 2254 return M->getBase()->isOBJCGCCandidate(Ctx); 2255 } 2256 case ArraySubscriptExprClass: 2257 return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx); 2258 } 2259 } 2260 2261 bool Expr::isBoundMemberFunction(ASTContext &Ctx) const { 2262 if (isTypeDependent()) 2263 return false; 2264 return ClassifyLValue(Ctx) == Expr::LV_MemberFunction; 2265 } 2266 2267 QualType Expr::findBoundMemberType(const Expr *expr) { 2268 assert(expr->hasPlaceholderType(BuiltinType::BoundMember)); 2269 2270 // Bound member expressions are always one of these possibilities: 2271 // x->m x.m x->*y x.*y 2272 // (possibly parenthesized) 2273 2274 expr = expr->IgnoreParens(); 2275 if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) { 2276 assert(isa<CXXMethodDecl>(mem->getMemberDecl())); 2277 return mem->getMemberDecl()->getType(); 2278 } 2279 2280 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) { 2281 QualType type = op->getRHS()->getType()->castAs<MemberPointerType>() 2282 ->getPointeeType(); 2283 assert(type->isFunctionType()); 2284 return type; 2285 } 2286 2287 assert(isa<UnresolvedMemberExpr>(expr)); 2288 return QualType(); 2289 } 2290 2291 Expr* Expr::IgnoreParens() { 2292 Expr* E = this; 2293 while (true) { 2294 if (ParenExpr* P = dyn_cast<ParenExpr>(E)) { 2295 E = P->getSubExpr(); 2296 continue; 2297 } 2298 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) { 2299 if (P->getOpcode() == UO_Extension) { 2300 E = P->getSubExpr(); 2301 continue; 2302 } 2303 } 2304 if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) { 2305 if (!P->isResultDependent()) { 2306 E = P->getResultExpr(); 2307 continue; 2308 } 2309 } 2310 if (ChooseExpr* P = dyn_cast<ChooseExpr>(E)) { 2311 if (!P->isConditionDependent()) { 2312 E = P->getChosenSubExpr(); 2313 continue; 2314 } 2315 } 2316 return E; 2317 } 2318 } 2319 2320 /// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr 2321 /// or CastExprs or ImplicitCastExprs, returning their operand. 2322 Expr *Expr::IgnoreParenCasts() { 2323 Expr *E = this; 2324 while (true) { 2325 E = E->IgnoreParens(); 2326 if (CastExpr *P = dyn_cast<CastExpr>(E)) { 2327 E = P->getSubExpr(); 2328 continue; 2329 } 2330 if (MaterializeTemporaryExpr *Materialize 2331 = dyn_cast<MaterializeTemporaryExpr>(E)) { 2332 E = Materialize->GetTemporaryExpr(); 2333 continue; 2334 } 2335 if (SubstNonTypeTemplateParmExpr *NTTP 2336 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) { 2337 E = NTTP->getReplacement(); 2338 continue; 2339 } 2340 return E; 2341 } 2342 } 2343 2344 /// IgnoreParenLValueCasts - Ignore parentheses and lvalue-to-rvalue 2345 /// casts. This is intended purely as a temporary workaround for code 2346 /// that hasn't yet been rewritten to do the right thing about those 2347 /// casts, and may disappear along with the last internal use. 2348 Expr *Expr::IgnoreParenLValueCasts() { 2349 Expr *E = this; 2350 while (true) { 2351 E = E->IgnoreParens(); 2352 if (CastExpr *P = dyn_cast<CastExpr>(E)) { 2353 if (P->getCastKind() == CK_LValueToRValue) { 2354 E = P->getSubExpr(); 2355 continue; 2356 } 2357 } else if (MaterializeTemporaryExpr *Materialize 2358 = dyn_cast<MaterializeTemporaryExpr>(E)) { 2359 E = Materialize->GetTemporaryExpr(); 2360 continue; 2361 } else if (SubstNonTypeTemplateParmExpr *NTTP 2362 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) { 2363 E = NTTP->getReplacement(); 2364 continue; 2365 } 2366 break; 2367 } 2368 return E; 2369 } 2370 2371 Expr *Expr::ignoreParenBaseCasts() { 2372 Expr *E = this; 2373 while (true) { 2374 E = E->IgnoreParens(); 2375 if (CastExpr *CE = dyn_cast<CastExpr>(E)) { 2376 if (CE->getCastKind() == CK_DerivedToBase || 2377 CE->getCastKind() == CK_UncheckedDerivedToBase || 2378 CE->getCastKind() == CK_NoOp) { 2379 E = CE->getSubExpr(); 2380 continue; 2381 } 2382 } 2383 2384 return E; 2385 } 2386 } 2387 2388 Expr *Expr::IgnoreParenImpCasts() { 2389 Expr *E = this; 2390 while (true) { 2391 E = E->IgnoreParens(); 2392 if (ImplicitCastExpr *P = dyn_cast<ImplicitCastExpr>(E)) { 2393 E = P->getSubExpr(); 2394 continue; 2395 } 2396 if (MaterializeTemporaryExpr *Materialize 2397 = dyn_cast<MaterializeTemporaryExpr>(E)) { 2398 E = Materialize->GetTemporaryExpr(); 2399 continue; 2400 } 2401 if (SubstNonTypeTemplateParmExpr *NTTP 2402 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) { 2403 E = NTTP->getReplacement(); 2404 continue; 2405 } 2406 return E; 2407 } 2408 } 2409 2410 Expr *Expr::IgnoreConversionOperator() { 2411 if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(this)) { 2412 if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl())) 2413 return MCE->getImplicitObjectArgument(); 2414 } 2415 return this; 2416 } 2417 2418 /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the 2419 /// value (including ptr->int casts of the same size). Strip off any 2420 /// ParenExpr or CastExprs, returning their operand. 2421 Expr *Expr::IgnoreParenNoopCasts(ASTContext &Ctx) { 2422 Expr *E = this; 2423 while (true) { 2424 E = E->IgnoreParens(); 2425 2426 if (CastExpr *P = dyn_cast<CastExpr>(E)) { 2427 // We ignore integer <-> casts that are of the same width, ptr<->ptr and 2428 // ptr<->int casts of the same width. We also ignore all identity casts. 2429 Expr *SE = P->getSubExpr(); 2430 2431 if (Ctx.hasSameUnqualifiedType(E->getType(), SE->getType())) { 2432 E = SE; 2433 continue; 2434 } 2435 2436 if ((E->getType()->isPointerType() || 2437 E->getType()->isIntegralType(Ctx)) && 2438 (SE->getType()->isPointerType() || 2439 SE->getType()->isIntegralType(Ctx)) && 2440 Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SE->getType())) { 2441 E = SE; 2442 continue; 2443 } 2444 } 2445 2446 if (SubstNonTypeTemplateParmExpr *NTTP 2447 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) { 2448 E = NTTP->getReplacement(); 2449 continue; 2450 } 2451 2452 return E; 2453 } 2454 } 2455 2456 bool Expr::isDefaultArgument() const { 2457 const Expr *E = this; 2458 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E)) 2459 E = M->GetTemporaryExpr(); 2460 2461 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 2462 E = ICE->getSubExprAsWritten(); 2463 2464 return isa<CXXDefaultArgExpr>(E); 2465 } 2466 2467 /// \brief Skip over any no-op casts and any temporary-binding 2468 /// expressions. 2469 static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) { 2470 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E)) 2471 E = M->GetTemporaryExpr(); 2472 2473 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 2474 if (ICE->getCastKind() == CK_NoOp) 2475 E = ICE->getSubExpr(); 2476 else 2477 break; 2478 } 2479 2480 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E)) 2481 E = BE->getSubExpr(); 2482 2483 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 2484 if (ICE->getCastKind() == CK_NoOp) 2485 E = ICE->getSubExpr(); 2486 else 2487 break; 2488 } 2489 2490 return E->IgnoreParens(); 2491 } 2492 2493 /// isTemporaryObject - Determines if this expression produces a 2494 /// temporary of the given class type. 2495 bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const { 2496 if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy))) 2497 return false; 2498 2499 const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this); 2500 2501 // Temporaries are by definition pr-values of class type. 2502 if (!E->Classify(C).isPRValue()) { 2503 // In this context, property reference is a message call and is pr-value. 2504 if (!isa<ObjCPropertyRefExpr>(E)) 2505 return false; 2506 } 2507 2508 // Black-list a few cases which yield pr-values of class type that don't 2509 // refer to temporaries of that type: 2510 2511 // - implicit derived-to-base conversions 2512 if (isa<ImplicitCastExpr>(E)) { 2513 switch (cast<ImplicitCastExpr>(E)->getCastKind()) { 2514 case CK_DerivedToBase: 2515 case CK_UncheckedDerivedToBase: 2516 return false; 2517 default: 2518 break; 2519 } 2520 } 2521 2522 // - member expressions (all) 2523 if (isa<MemberExpr>(E)) 2524 return false; 2525 2526 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) 2527 if (BO->isPtrMemOp()) 2528 return false; 2529 2530 // - opaque values (all) 2531 if (isa<OpaqueValueExpr>(E)) 2532 return false; 2533 2534 return true; 2535 } 2536 2537 bool Expr::isImplicitCXXThis() const { 2538 const Expr *E = this; 2539 2540 // Strip away parentheses and casts we don't care about. 2541 while (true) { 2542 if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) { 2543 E = Paren->getSubExpr(); 2544 continue; 2545 } 2546 2547 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 2548 if (ICE->getCastKind() == CK_NoOp || 2549 ICE->getCastKind() == CK_LValueToRValue || 2550 ICE->getCastKind() == CK_DerivedToBase || 2551 ICE->getCastKind() == CK_UncheckedDerivedToBase) { 2552 E = ICE->getSubExpr(); 2553 continue; 2554 } 2555 } 2556 2557 if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) { 2558 if (UnOp->getOpcode() == UO_Extension) { 2559 E = UnOp->getSubExpr(); 2560 continue; 2561 } 2562 } 2563 2564 if (const MaterializeTemporaryExpr *M 2565 = dyn_cast<MaterializeTemporaryExpr>(E)) { 2566 E = M->GetTemporaryExpr(); 2567 continue; 2568 } 2569 2570 break; 2571 } 2572 2573 if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E)) 2574 return This->isImplicit(); 2575 2576 return false; 2577 } 2578 2579 /// hasAnyTypeDependentArguments - Determines if any of the expressions 2580 /// in Exprs is type-dependent. 2581 bool Expr::hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs) { 2582 for (unsigned I = 0; I < Exprs.size(); ++I) 2583 if (Exprs[I]->isTypeDependent()) 2584 return true; 2585 2586 return false; 2587 } 2588 2589 bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef) const { 2590 // This function is attempting whether an expression is an initializer 2591 // which can be evaluated at compile-time. It very closely parallels 2592 // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it 2593 // will lead to unexpected results. Like ConstExprEmitter, it falls back 2594 // to isEvaluatable most of the time. 2595 // 2596 // If we ever capture reference-binding directly in the AST, we can 2597 // kill the second parameter. 2598 2599 if (IsForRef) { 2600 EvalResult Result; 2601 return EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects; 2602 } 2603 2604 switch (getStmtClass()) { 2605 default: break; 2606 case StringLiteralClass: 2607 case ObjCEncodeExprClass: 2608 return true; 2609 case CXXTemporaryObjectExprClass: 2610 case CXXConstructExprClass: { 2611 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this); 2612 2613 if (CE->getConstructor()->isTrivial() && 2614 CE->getConstructor()->getParent()->hasTrivialDestructor()) { 2615 // Trivial default constructor 2616 if (!CE->getNumArgs()) return true; 2617 2618 // Trivial copy constructor 2619 assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument"); 2620 return CE->getArg(0)->isConstantInitializer(Ctx, false); 2621 } 2622 2623 break; 2624 } 2625 case CompoundLiteralExprClass: { 2626 // This handles gcc's extension that allows global initializers like 2627 // "struct x {int x;} x = (struct x) {};". 2628 // FIXME: This accepts other cases it shouldn't! 2629 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer(); 2630 return Exp->isConstantInitializer(Ctx, false); 2631 } 2632 case InitListExprClass: { 2633 // FIXME: This doesn't deal with fields with reference types correctly. 2634 // FIXME: This incorrectly allows pointers cast to integers to be assigned 2635 // to bitfields. 2636 const InitListExpr *ILE = cast<InitListExpr>(this); 2637 if (ILE->getType()->isArrayType()) { 2638 unsigned numInits = ILE->getNumInits(); 2639 for (unsigned i = 0; i < numInits; i++) { 2640 if (!ILE->getInit(i)->isConstantInitializer(Ctx, false)) 2641 return false; 2642 } 2643 return true; 2644 } 2645 2646 if (ILE->getType()->isRecordType()) { 2647 unsigned ElementNo = 0; 2648 RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl(); 2649 for (RecordDecl::field_iterator Field = RD->field_begin(), 2650 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) { 2651 // If this is a union, skip all the fields that aren't being initialized. 2652 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != *Field) 2653 continue; 2654 2655 // Don't emit anonymous bitfields, they just affect layout. 2656 if (Field->isUnnamedBitfield()) 2657 continue; 2658 2659 if (ElementNo < ILE->getNumInits()) { 2660 const Expr *Elt = ILE->getInit(ElementNo++); 2661 if (Field->isBitField()) { 2662 // Bitfields have to evaluate to an integer. 2663 llvm::APSInt ResultTmp; 2664 if (!Elt->EvaluateAsInt(ResultTmp, Ctx)) 2665 return false; 2666 } else { 2667 bool RefType = Field->getType()->isReferenceType(); 2668 if (!Elt->isConstantInitializer(Ctx, RefType)) 2669 return false; 2670 } 2671 } 2672 } 2673 return true; 2674 } 2675 2676 break; 2677 } 2678 case ImplicitValueInitExprClass: 2679 return true; 2680 case ParenExprClass: 2681 return cast<ParenExpr>(this)->getSubExpr() 2682 ->isConstantInitializer(Ctx, IsForRef); 2683 case GenericSelectionExprClass: 2684 return cast<GenericSelectionExpr>(this)->getResultExpr() 2685 ->isConstantInitializer(Ctx, IsForRef); 2686 case ChooseExprClass: 2687 if (cast<ChooseExpr>(this)->isConditionDependent()) 2688 return false; 2689 return cast<ChooseExpr>(this)->getChosenSubExpr() 2690 ->isConstantInitializer(Ctx, IsForRef); 2691 case UnaryOperatorClass: { 2692 const UnaryOperator* Exp = cast<UnaryOperator>(this); 2693 if (Exp->getOpcode() == UO_Extension) 2694 return Exp->getSubExpr()->isConstantInitializer(Ctx, false); 2695 break; 2696 } 2697 case CXXFunctionalCastExprClass: 2698 case CXXStaticCastExprClass: 2699 case ImplicitCastExprClass: 2700 case CStyleCastExprClass: 2701 case ObjCBridgedCastExprClass: 2702 case CXXDynamicCastExprClass: 2703 case CXXReinterpretCastExprClass: 2704 case CXXConstCastExprClass: { 2705 const CastExpr *CE = cast<CastExpr>(this); 2706 2707 // Handle misc casts we want to ignore. 2708 if (CE->getCastKind() == CK_NoOp || 2709 CE->getCastKind() == CK_LValueToRValue || 2710 CE->getCastKind() == CK_ToUnion || 2711 CE->getCastKind() == CK_ConstructorConversion || 2712 CE->getCastKind() == CK_NonAtomicToAtomic || 2713 CE->getCastKind() == CK_AtomicToNonAtomic) 2714 return CE->getSubExpr()->isConstantInitializer(Ctx, false); 2715 2716 break; 2717 } 2718 case MaterializeTemporaryExprClass: 2719 return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr() 2720 ->isConstantInitializer(Ctx, false); 2721 2722 case SubstNonTypeTemplateParmExprClass: 2723 return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement() 2724 ->isConstantInitializer(Ctx, false); 2725 case CXXDefaultArgExprClass: 2726 return cast<CXXDefaultArgExpr>(this)->getExpr() 2727 ->isConstantInitializer(Ctx, false); 2728 case CXXDefaultInitExprClass: 2729 return cast<CXXDefaultInitExpr>(this)->getExpr() 2730 ->isConstantInitializer(Ctx, false); 2731 } 2732 return isEvaluatable(Ctx); 2733 } 2734 2735 bool Expr::HasSideEffects(const ASTContext &Ctx) const { 2736 if (isInstantiationDependent()) 2737 return true; 2738 2739 switch (getStmtClass()) { 2740 case NoStmtClass: 2741 #define ABSTRACT_STMT(Type) 2742 #define STMT(Type, Base) case Type##Class: 2743 #define EXPR(Type, Base) 2744 #include "clang/AST/StmtNodes.inc" 2745 llvm_unreachable("unexpected Expr kind"); 2746 2747 case DependentScopeDeclRefExprClass: 2748 case CXXUnresolvedConstructExprClass: 2749 case CXXDependentScopeMemberExprClass: 2750 case UnresolvedLookupExprClass: 2751 case UnresolvedMemberExprClass: 2752 case PackExpansionExprClass: 2753 case SubstNonTypeTemplateParmPackExprClass: 2754 case FunctionParmPackExprClass: 2755 llvm_unreachable("shouldn't see dependent / unresolved nodes here"); 2756 2757 case DeclRefExprClass: 2758 case ObjCIvarRefExprClass: 2759 case PredefinedExprClass: 2760 case IntegerLiteralClass: 2761 case FloatingLiteralClass: 2762 case ImaginaryLiteralClass: 2763 case StringLiteralClass: 2764 case CharacterLiteralClass: 2765 case OffsetOfExprClass: 2766 case ImplicitValueInitExprClass: 2767 case UnaryExprOrTypeTraitExprClass: 2768 case AddrLabelExprClass: 2769 case GNUNullExprClass: 2770 case CXXBoolLiteralExprClass: 2771 case CXXNullPtrLiteralExprClass: 2772 case CXXThisExprClass: 2773 case CXXScalarValueInitExprClass: 2774 case TypeTraitExprClass: 2775 case UnaryTypeTraitExprClass: 2776 case BinaryTypeTraitExprClass: 2777 case ArrayTypeTraitExprClass: 2778 case ExpressionTraitExprClass: 2779 case CXXNoexceptExprClass: 2780 case SizeOfPackExprClass: 2781 case ObjCStringLiteralClass: 2782 case ObjCEncodeExprClass: 2783 case ObjCBoolLiteralExprClass: 2784 case CXXUuidofExprClass: 2785 case OpaqueValueExprClass: 2786 // These never have a side-effect. 2787 return false; 2788 2789 case CallExprClass: 2790 case MSPropertyRefExprClass: 2791 case CompoundAssignOperatorClass: 2792 case VAArgExprClass: 2793 case AtomicExprClass: 2794 case StmtExprClass: 2795 case CXXOperatorCallExprClass: 2796 case CXXMemberCallExprClass: 2797 case UserDefinedLiteralClass: 2798 case CXXThrowExprClass: 2799 case CXXNewExprClass: 2800 case CXXDeleteExprClass: 2801 case ExprWithCleanupsClass: 2802 case CXXBindTemporaryExprClass: 2803 case BlockExprClass: 2804 case CUDAKernelCallExprClass: 2805 // These always have a side-effect. 2806 return true; 2807 2808 case ParenExprClass: 2809 case ArraySubscriptExprClass: 2810 case MemberExprClass: 2811 case ConditionalOperatorClass: 2812 case BinaryConditionalOperatorClass: 2813 case CompoundLiteralExprClass: 2814 case ExtVectorElementExprClass: 2815 case DesignatedInitExprClass: 2816 case ParenListExprClass: 2817 case CXXPseudoDestructorExprClass: 2818 case CXXStdInitializerListExprClass: 2819 case SubstNonTypeTemplateParmExprClass: 2820 case MaterializeTemporaryExprClass: 2821 case ShuffleVectorExprClass: 2822 case AsTypeExprClass: 2823 // These have a side-effect if any subexpression does. 2824 break; 2825 2826 case UnaryOperatorClass: 2827 if (cast<UnaryOperator>(this)->isIncrementDecrementOp()) 2828 return true; 2829 break; 2830 2831 case BinaryOperatorClass: 2832 if (cast<BinaryOperator>(this)->isAssignmentOp()) 2833 return true; 2834 break; 2835 2836 case InitListExprClass: 2837 // FIXME: The children for an InitListExpr doesn't include the array filler. 2838 if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller()) 2839 if (E->HasSideEffects(Ctx)) 2840 return true; 2841 break; 2842 2843 case GenericSelectionExprClass: 2844 return cast<GenericSelectionExpr>(this)->getResultExpr()-> 2845 HasSideEffects(Ctx); 2846 2847 case ChooseExprClass: 2848 return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(Ctx); 2849 2850 case CXXDefaultArgExprClass: 2851 return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(Ctx); 2852 2853 case CXXDefaultInitExprClass: 2854 if (const Expr *E = cast<CXXDefaultInitExpr>(this)->getExpr()) 2855 return E->HasSideEffects(Ctx); 2856 // If we've not yet parsed the initializer, assume it has side-effects. 2857 return true; 2858 2859 case CXXDynamicCastExprClass: { 2860 // A dynamic_cast expression has side-effects if it can throw. 2861 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this); 2862 if (DCE->getTypeAsWritten()->isReferenceType() && 2863 DCE->getCastKind() == CK_Dynamic) 2864 return true; 2865 } // Fall through. 2866 case ImplicitCastExprClass: 2867 case CStyleCastExprClass: 2868 case CXXStaticCastExprClass: 2869 case CXXReinterpretCastExprClass: 2870 case CXXConstCastExprClass: 2871 case CXXFunctionalCastExprClass: { 2872 const CastExpr *CE = cast<CastExpr>(this); 2873 if (CE->getCastKind() == CK_LValueToRValue && 2874 CE->getSubExpr()->getType().isVolatileQualified()) 2875 return true; 2876 break; 2877 } 2878 2879 case CXXTypeidExprClass: 2880 // typeid might throw if its subexpression is potentially-evaluated, so has 2881 // side-effects in that case whether or not its subexpression does. 2882 return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated(); 2883 2884 case CXXConstructExprClass: 2885 case CXXTemporaryObjectExprClass: { 2886 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this); 2887 if (!CE->getConstructor()->isTrivial()) 2888 return true; 2889 // A trivial constructor does not add any side-effects of its own. Just look 2890 // at its arguments. 2891 break; 2892 } 2893 2894 case LambdaExprClass: { 2895 const LambdaExpr *LE = cast<LambdaExpr>(this); 2896 for (LambdaExpr::capture_iterator I = LE->capture_begin(), 2897 E = LE->capture_end(); I != E; ++I) 2898 if (I->getCaptureKind() == LCK_ByCopy) 2899 // FIXME: Only has a side-effect if the variable is volatile or if 2900 // the copy would invoke a non-trivial copy constructor. 2901 return true; 2902 return false; 2903 } 2904 2905 case PseudoObjectExprClass: { 2906 // Only look for side-effects in the semantic form, and look past 2907 // OpaqueValueExpr bindings in that form. 2908 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this); 2909 for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(), 2910 E = PO->semantics_end(); 2911 I != E; ++I) { 2912 const Expr *Subexpr = *I; 2913 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr)) 2914 Subexpr = OVE->getSourceExpr(); 2915 if (Subexpr->HasSideEffects(Ctx)) 2916 return true; 2917 } 2918 return false; 2919 } 2920 2921 case ObjCBoxedExprClass: 2922 case ObjCArrayLiteralClass: 2923 case ObjCDictionaryLiteralClass: 2924 case ObjCMessageExprClass: 2925 case ObjCSelectorExprClass: 2926 case ObjCProtocolExprClass: 2927 case ObjCPropertyRefExprClass: 2928 case ObjCIsaExprClass: 2929 case ObjCIndirectCopyRestoreExprClass: 2930 case ObjCSubscriptRefExprClass: 2931 case ObjCBridgedCastExprClass: 2932 // FIXME: Classify these cases better. 2933 return true; 2934 } 2935 2936 // Recurse to children. 2937 for (const_child_range SubStmts = children(); SubStmts; ++SubStmts) 2938 if (const Stmt *S = *SubStmts) 2939 if (cast<Expr>(S)->HasSideEffects(Ctx)) 2940 return true; 2941 2942 return false; 2943 } 2944 2945 namespace { 2946 /// \brief Look for a call to a non-trivial function within an expression. 2947 class NonTrivialCallFinder : public EvaluatedExprVisitor<NonTrivialCallFinder> 2948 { 2949 typedef EvaluatedExprVisitor<NonTrivialCallFinder> Inherited; 2950 2951 bool NonTrivial; 2952 2953 public: 2954 explicit NonTrivialCallFinder(ASTContext &Context) 2955 : Inherited(Context), NonTrivial(false) { } 2956 2957 bool hasNonTrivialCall() const { return NonTrivial; } 2958 2959 void VisitCallExpr(CallExpr *E) { 2960 if (CXXMethodDecl *Method 2961 = dyn_cast_or_null<CXXMethodDecl>(E->getCalleeDecl())) { 2962 if (Method->isTrivial()) { 2963 // Recurse to children of the call. 2964 Inherited::VisitStmt(E); 2965 return; 2966 } 2967 } 2968 2969 NonTrivial = true; 2970 } 2971 2972 void VisitCXXConstructExpr(CXXConstructExpr *E) { 2973 if (E->getConstructor()->isTrivial()) { 2974 // Recurse to children of the call. 2975 Inherited::VisitStmt(E); 2976 return; 2977 } 2978 2979 NonTrivial = true; 2980 } 2981 2982 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 2983 if (E->getTemporary()->getDestructor()->isTrivial()) { 2984 Inherited::VisitStmt(E); 2985 return; 2986 } 2987 2988 NonTrivial = true; 2989 } 2990 }; 2991 } 2992 2993 bool Expr::hasNonTrivialCall(ASTContext &Ctx) { 2994 NonTrivialCallFinder Finder(Ctx); 2995 Finder.Visit(this); 2996 return Finder.hasNonTrivialCall(); 2997 } 2998 2999 /// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null 3000 /// pointer constant or not, as well as the specific kind of constant detected. 3001 /// Null pointer constants can be integer constant expressions with the 3002 /// value zero, casts of zero to void*, nullptr (C++0X), or __null 3003 /// (a GNU extension). 3004 Expr::NullPointerConstantKind 3005 Expr::isNullPointerConstant(ASTContext &Ctx, 3006 NullPointerConstantValueDependence NPC) const { 3007 if (isValueDependent() && !Ctx.getLangOpts().CPlusPlus11) { 3008 switch (NPC) { 3009 case NPC_NeverValueDependent: 3010 llvm_unreachable("Unexpected value dependent expression!"); 3011 case NPC_ValueDependentIsNull: 3012 if (isTypeDependent() || getType()->isIntegralType(Ctx)) 3013 return NPCK_ZeroExpression; 3014 else 3015 return NPCK_NotNull; 3016 3017 case NPC_ValueDependentIsNotNull: 3018 return NPCK_NotNull; 3019 } 3020 } 3021 3022 // Strip off a cast to void*, if it exists. Except in C++. 3023 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) { 3024 if (!Ctx.getLangOpts().CPlusPlus) { 3025 // Check that it is a cast to void*. 3026 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) { 3027 QualType Pointee = PT->getPointeeType(); 3028 if (!Pointee.hasQualifiers() && 3029 Pointee->isVoidType() && // to void* 3030 CE->getSubExpr()->getType()->isIntegerType()) // from int. 3031 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC); 3032 } 3033 } 3034 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) { 3035 // Ignore the ImplicitCastExpr type entirely. 3036 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC); 3037 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) { 3038 // Accept ((void*)0) as a null pointer constant, as many other 3039 // implementations do. 3040 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC); 3041 } else if (const GenericSelectionExpr *GE = 3042 dyn_cast<GenericSelectionExpr>(this)) { 3043 if (GE->isResultDependent()) 3044 return NPCK_NotNull; 3045 return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC); 3046 } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) { 3047 if (CE->isConditionDependent()) 3048 return NPCK_NotNull; 3049 return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC); 3050 } else if (const CXXDefaultArgExpr *DefaultArg 3051 = dyn_cast<CXXDefaultArgExpr>(this)) { 3052 // See through default argument expressions. 3053 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC); 3054 } else if (const CXXDefaultInitExpr *DefaultInit 3055 = dyn_cast<CXXDefaultInitExpr>(this)) { 3056 // See through default initializer expressions. 3057 return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC); 3058 } else if (isa<GNUNullExpr>(this)) { 3059 // The GNU __null extension is always a null pointer constant. 3060 return NPCK_GNUNull; 3061 } else if (const MaterializeTemporaryExpr *M 3062 = dyn_cast<MaterializeTemporaryExpr>(this)) { 3063 return M->GetTemporaryExpr()->isNullPointerConstant(Ctx, NPC); 3064 } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) { 3065 if (const Expr *Source = OVE->getSourceExpr()) 3066 return Source->isNullPointerConstant(Ctx, NPC); 3067 } 3068 3069 // C++11 nullptr_t is always a null pointer constant. 3070 if (getType()->isNullPtrType()) 3071 return NPCK_CXX11_nullptr; 3072 3073 if (const RecordType *UT = getType()->getAsUnionType()) 3074 if (!Ctx.getLangOpts().CPlusPlus11 && 3075 UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) 3076 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){ 3077 const Expr *InitExpr = CLE->getInitializer(); 3078 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr)) 3079 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC); 3080 } 3081 // This expression must be an integer type. 3082 if (!getType()->isIntegerType() || 3083 (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType())) 3084 return NPCK_NotNull; 3085 3086 if (Ctx.getLangOpts().CPlusPlus11) { 3087 // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with 3088 // value zero or a prvalue of type std::nullptr_t. 3089 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this); 3090 return (Lit && !Lit->getValue()) ? NPCK_ZeroLiteral : NPCK_NotNull; 3091 } else { 3092 // If we have an integer constant expression, we need to *evaluate* it and 3093 // test for the value 0. 3094 if (!isIntegerConstantExpr(Ctx)) 3095 return NPCK_NotNull; 3096 } 3097 3098 if (EvaluateKnownConstInt(Ctx) != 0) 3099 return NPCK_NotNull; 3100 3101 if (isa<IntegerLiteral>(this)) 3102 return NPCK_ZeroLiteral; 3103 return NPCK_ZeroExpression; 3104 } 3105 3106 /// \brief If this expression is an l-value for an Objective C 3107 /// property, find the underlying property reference expression. 3108 const ObjCPropertyRefExpr *Expr::getObjCProperty() const { 3109 const Expr *E = this; 3110 while (true) { 3111 assert((E->getValueKind() == VK_LValue && 3112 E->getObjectKind() == OK_ObjCProperty) && 3113 "expression is not a property reference"); 3114 E = E->IgnoreParenCasts(); 3115 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3116 if (BO->getOpcode() == BO_Comma) { 3117 E = BO->getRHS(); 3118 continue; 3119 } 3120 } 3121 3122 break; 3123 } 3124 3125 return cast<ObjCPropertyRefExpr>(E); 3126 } 3127 3128 bool Expr::isObjCSelfExpr() const { 3129 const Expr *E = IgnoreParenImpCasts(); 3130 3131 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 3132 if (!DRE) 3133 return false; 3134 3135 const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl()); 3136 if (!Param) 3137 return false; 3138 3139 const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext()); 3140 if (!M) 3141 return false; 3142 3143 return M->getSelfDecl() == Param; 3144 } 3145 3146 FieldDecl *Expr::getSourceBitField() { 3147 Expr *E = this->IgnoreParens(); 3148 3149 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 3150 if (ICE->getCastKind() == CK_LValueToRValue || 3151 (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp)) 3152 E = ICE->getSubExpr()->IgnoreParens(); 3153 else 3154 break; 3155 } 3156 3157 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E)) 3158 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl())) 3159 if (Field->isBitField()) 3160 return Field; 3161 3162 if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) 3163 if (FieldDecl *Ivar = dyn_cast<FieldDecl>(IvarRef->getDecl())) 3164 if (Ivar->isBitField()) 3165 return Ivar; 3166 3167 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) 3168 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl())) 3169 if (Field->isBitField()) 3170 return Field; 3171 3172 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) { 3173 if (BinOp->isAssignmentOp() && BinOp->getLHS()) 3174 return BinOp->getLHS()->getSourceBitField(); 3175 3176 if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS()) 3177 return BinOp->getRHS()->getSourceBitField(); 3178 } 3179 3180 return 0; 3181 } 3182 3183 bool Expr::refersToVectorElement() const { 3184 const Expr *E = this->IgnoreParens(); 3185 3186 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 3187 if (ICE->getValueKind() != VK_RValue && 3188 ICE->getCastKind() == CK_NoOp) 3189 E = ICE->getSubExpr()->IgnoreParens(); 3190 else 3191 break; 3192 } 3193 3194 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E)) 3195 return ASE->getBase()->getType()->isVectorType(); 3196 3197 if (isa<ExtVectorElementExpr>(E)) 3198 return true; 3199 3200 return false; 3201 } 3202 3203 /// isArrow - Return true if the base expression is a pointer to vector, 3204 /// return false if the base expression is a vector. 3205 bool ExtVectorElementExpr::isArrow() const { 3206 return getBase()->getType()->isPointerType(); 3207 } 3208 3209 unsigned ExtVectorElementExpr::getNumElements() const { 3210 if (const VectorType *VT = getType()->getAs<VectorType>()) 3211 return VT->getNumElements(); 3212 return 1; 3213 } 3214 3215 /// containsDuplicateElements - Return true if any element access is repeated. 3216 bool ExtVectorElementExpr::containsDuplicateElements() const { 3217 // FIXME: Refactor this code to an accessor on the AST node which returns the 3218 // "type" of component access, and share with code below and in Sema. 3219 StringRef Comp = Accessor->getName(); 3220 3221 // Halving swizzles do not contain duplicate elements. 3222 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd") 3223 return false; 3224 3225 // Advance past s-char prefix on hex swizzles. 3226 if (Comp[0] == 's' || Comp[0] == 'S') 3227 Comp = Comp.substr(1); 3228 3229 for (unsigned i = 0, e = Comp.size(); i != e; ++i) 3230 if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos) 3231 return true; 3232 3233 return false; 3234 } 3235 3236 /// getEncodedElementAccess - We encode the fields as a llvm ConstantArray. 3237 void ExtVectorElementExpr::getEncodedElementAccess( 3238 SmallVectorImpl<unsigned> &Elts) const { 3239 StringRef Comp = Accessor->getName(); 3240 if (Comp[0] == 's' || Comp[0] == 'S') 3241 Comp = Comp.substr(1); 3242 3243 bool isHi = Comp == "hi"; 3244 bool isLo = Comp == "lo"; 3245 bool isEven = Comp == "even"; 3246 bool isOdd = Comp == "odd"; 3247 3248 for (unsigned i = 0, e = getNumElements(); i != e; ++i) { 3249 uint64_t Index; 3250 3251 if (isHi) 3252 Index = e + i; 3253 else if (isLo) 3254 Index = i; 3255 else if (isEven) 3256 Index = 2 * i; 3257 else if (isOdd) 3258 Index = 2 * i + 1; 3259 else 3260 Index = ExtVectorType::getAccessorIdx(Comp[i]); 3261 3262 Elts.push_back(Index); 3263 } 3264 } 3265 3266 ObjCMessageExpr::ObjCMessageExpr(QualType T, 3267 ExprValueKind VK, 3268 SourceLocation LBracLoc, 3269 SourceLocation SuperLoc, 3270 bool IsInstanceSuper, 3271 QualType SuperType, 3272 Selector Sel, 3273 ArrayRef<SourceLocation> SelLocs, 3274 SelectorLocationsKind SelLocsK, 3275 ObjCMethodDecl *Method, 3276 ArrayRef<Expr *> Args, 3277 SourceLocation RBracLoc, 3278 bool isImplicit) 3279 : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary, 3280 /*TypeDependent=*/false, /*ValueDependent=*/false, 3281 /*InstantiationDependent=*/false, 3282 /*ContainsUnexpandedParameterPack=*/false), 3283 SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method 3284 : Sel.getAsOpaquePtr())), 3285 Kind(IsInstanceSuper? SuperInstance : SuperClass), 3286 HasMethod(Method != 0), IsDelegateInitCall(false), IsImplicit(isImplicit), 3287 SuperLoc(SuperLoc), LBracLoc(LBracLoc), RBracLoc(RBracLoc) 3288 { 3289 initArgsAndSelLocs(Args, SelLocs, SelLocsK); 3290 setReceiverPointer(SuperType.getAsOpaquePtr()); 3291 } 3292 3293 ObjCMessageExpr::ObjCMessageExpr(QualType T, 3294 ExprValueKind VK, 3295 SourceLocation LBracLoc, 3296 TypeSourceInfo *Receiver, 3297 Selector Sel, 3298 ArrayRef<SourceLocation> SelLocs, 3299 SelectorLocationsKind SelLocsK, 3300 ObjCMethodDecl *Method, 3301 ArrayRef<Expr *> Args, 3302 SourceLocation RBracLoc, 3303 bool isImplicit) 3304 : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary, T->isDependentType(), 3305 T->isDependentType(), T->isInstantiationDependentType(), 3306 T->containsUnexpandedParameterPack()), 3307 SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method 3308 : Sel.getAsOpaquePtr())), 3309 Kind(Class), 3310 HasMethod(Method != 0), IsDelegateInitCall(false), IsImplicit(isImplicit), 3311 LBracLoc(LBracLoc), RBracLoc(RBracLoc) 3312 { 3313 initArgsAndSelLocs(Args, SelLocs, SelLocsK); 3314 setReceiverPointer(Receiver); 3315 } 3316 3317 ObjCMessageExpr::ObjCMessageExpr(QualType T, 3318 ExprValueKind VK, 3319 SourceLocation LBracLoc, 3320 Expr *Receiver, 3321 Selector Sel, 3322 ArrayRef<SourceLocation> SelLocs, 3323 SelectorLocationsKind SelLocsK, 3324 ObjCMethodDecl *Method, 3325 ArrayRef<Expr *> Args, 3326 SourceLocation RBracLoc, 3327 bool isImplicit) 3328 : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary, Receiver->isTypeDependent(), 3329 Receiver->isTypeDependent(), 3330 Receiver->isInstantiationDependent(), 3331 Receiver->containsUnexpandedParameterPack()), 3332 SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method 3333 : Sel.getAsOpaquePtr())), 3334 Kind(Instance), 3335 HasMethod(Method != 0), IsDelegateInitCall(false), IsImplicit(isImplicit), 3336 LBracLoc(LBracLoc), RBracLoc(RBracLoc) 3337 { 3338 initArgsAndSelLocs(Args, SelLocs, SelLocsK); 3339 setReceiverPointer(Receiver); 3340 } 3341 3342 void ObjCMessageExpr::initArgsAndSelLocs(ArrayRef<Expr *> Args, 3343 ArrayRef<SourceLocation> SelLocs, 3344 SelectorLocationsKind SelLocsK) { 3345 setNumArgs(Args.size()); 3346 Expr **MyArgs = getArgs(); 3347 for (unsigned I = 0; I != Args.size(); ++I) { 3348 if (Args[I]->isTypeDependent()) 3349 ExprBits.TypeDependent = true; 3350 if (Args[I]->isValueDependent()) 3351 ExprBits.ValueDependent = true; 3352 if (Args[I]->isInstantiationDependent()) 3353 ExprBits.InstantiationDependent = true; 3354 if (Args[I]->containsUnexpandedParameterPack()) 3355 ExprBits.ContainsUnexpandedParameterPack = true; 3356 3357 MyArgs[I] = Args[I]; 3358 } 3359 3360 SelLocsKind = SelLocsK; 3361 if (!isImplicit()) { 3362 if (SelLocsK == SelLoc_NonStandard) 3363 std::copy(SelLocs.begin(), SelLocs.end(), getStoredSelLocs()); 3364 } 3365 } 3366 3367 ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T, 3368 ExprValueKind VK, 3369 SourceLocation LBracLoc, 3370 SourceLocation SuperLoc, 3371 bool IsInstanceSuper, 3372 QualType SuperType, 3373 Selector Sel, 3374 ArrayRef<SourceLocation> SelLocs, 3375 ObjCMethodDecl *Method, 3376 ArrayRef<Expr *> Args, 3377 SourceLocation RBracLoc, 3378 bool isImplicit) { 3379 assert((!SelLocs.empty() || isImplicit) && 3380 "No selector locs for non-implicit message"); 3381 ObjCMessageExpr *Mem; 3382 SelectorLocationsKind SelLocsK = SelectorLocationsKind(); 3383 if (isImplicit) 3384 Mem = alloc(Context, Args.size(), 0); 3385 else 3386 Mem = alloc(Context, Args, RBracLoc, SelLocs, Sel, SelLocsK); 3387 return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, SuperLoc, IsInstanceSuper, 3388 SuperType, Sel, SelLocs, SelLocsK, 3389 Method, Args, RBracLoc, isImplicit); 3390 } 3391 3392 ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T, 3393 ExprValueKind VK, 3394 SourceLocation LBracLoc, 3395 TypeSourceInfo *Receiver, 3396 Selector Sel, 3397 ArrayRef<SourceLocation> SelLocs, 3398 ObjCMethodDecl *Method, 3399 ArrayRef<Expr *> Args, 3400 SourceLocation RBracLoc, 3401 bool isImplicit) { 3402 assert((!SelLocs.empty() || isImplicit) && 3403 "No selector locs for non-implicit message"); 3404 ObjCMessageExpr *Mem; 3405 SelectorLocationsKind SelLocsK = SelectorLocationsKind(); 3406 if (isImplicit) 3407 Mem = alloc(Context, Args.size(), 0); 3408 else 3409 Mem = alloc(Context, Args, RBracLoc, SelLocs, Sel, SelLocsK); 3410 return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, Receiver, Sel, 3411 SelLocs, SelLocsK, Method, Args, RBracLoc, 3412 isImplicit); 3413 } 3414 3415 ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T, 3416 ExprValueKind VK, 3417 SourceLocation LBracLoc, 3418 Expr *Receiver, 3419 Selector Sel, 3420 ArrayRef<SourceLocation> SelLocs, 3421 ObjCMethodDecl *Method, 3422 ArrayRef<Expr *> Args, 3423 SourceLocation RBracLoc, 3424 bool isImplicit) { 3425 assert((!SelLocs.empty() || isImplicit) && 3426 "No selector locs for non-implicit message"); 3427 ObjCMessageExpr *Mem; 3428 SelectorLocationsKind SelLocsK = SelectorLocationsKind(); 3429 if (isImplicit) 3430 Mem = alloc(Context, Args.size(), 0); 3431 else 3432 Mem = alloc(Context, Args, RBracLoc, SelLocs, Sel, SelLocsK); 3433 return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, Receiver, Sel, 3434 SelLocs, SelLocsK, Method, Args, RBracLoc, 3435 isImplicit); 3436 } 3437 3438 ObjCMessageExpr *ObjCMessageExpr::CreateEmpty(ASTContext &Context, 3439 unsigned NumArgs, 3440 unsigned NumStoredSelLocs) { 3441 ObjCMessageExpr *Mem = alloc(Context, NumArgs, NumStoredSelLocs); 3442 return new (Mem) ObjCMessageExpr(EmptyShell(), NumArgs); 3443 } 3444 3445 ObjCMessageExpr *ObjCMessageExpr::alloc(ASTContext &C, 3446 ArrayRef<Expr *> Args, 3447 SourceLocation RBraceLoc, 3448 ArrayRef<SourceLocation> SelLocs, 3449 Selector Sel, 3450 SelectorLocationsKind &SelLocsK) { 3451 SelLocsK = hasStandardSelectorLocs(Sel, SelLocs, Args, RBraceLoc); 3452 unsigned NumStoredSelLocs = (SelLocsK == SelLoc_NonStandard) ? SelLocs.size() 3453 : 0; 3454 return alloc(C, Args.size(), NumStoredSelLocs); 3455 } 3456 3457 ObjCMessageExpr *ObjCMessageExpr::alloc(ASTContext &C, 3458 unsigned NumArgs, 3459 unsigned NumStoredSelLocs) { 3460 unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) + 3461 NumArgs * sizeof(Expr *) + NumStoredSelLocs * sizeof(SourceLocation); 3462 return (ObjCMessageExpr *)C.Allocate(Size, 3463 llvm::AlignOf<ObjCMessageExpr>::Alignment); 3464 } 3465 3466 void ObjCMessageExpr::getSelectorLocs( 3467 SmallVectorImpl<SourceLocation> &SelLocs) const { 3468 for (unsigned i = 0, e = getNumSelectorLocs(); i != e; ++i) 3469 SelLocs.push_back(getSelectorLoc(i)); 3470 } 3471 3472 SourceRange ObjCMessageExpr::getReceiverRange() const { 3473 switch (getReceiverKind()) { 3474 case Instance: 3475 return getInstanceReceiver()->getSourceRange(); 3476 3477 case Class: 3478 return getClassReceiverTypeInfo()->getTypeLoc().getSourceRange(); 3479 3480 case SuperInstance: 3481 case SuperClass: 3482 return getSuperLoc(); 3483 } 3484 3485 llvm_unreachable("Invalid ReceiverKind!"); 3486 } 3487 3488 Selector ObjCMessageExpr::getSelector() const { 3489 if (HasMethod) 3490 return reinterpret_cast<const ObjCMethodDecl *>(SelectorOrMethod) 3491 ->getSelector(); 3492 return Selector(SelectorOrMethod); 3493 } 3494 3495 QualType ObjCMessageExpr::getReceiverType() const { 3496 switch (getReceiverKind()) { 3497 case Instance: 3498 return getInstanceReceiver()->getType(); 3499 case Class: 3500 return getClassReceiver(); 3501 case SuperInstance: 3502 case SuperClass: 3503 return getSuperType(); 3504 } 3505 3506 llvm_unreachable("unexpected receiver kind"); 3507 } 3508 3509 ObjCInterfaceDecl *ObjCMessageExpr::getReceiverInterface() const { 3510 QualType T = getReceiverType(); 3511 3512 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>()) 3513 return Ptr->getInterfaceDecl(); 3514 3515 if (const ObjCObjectType *Ty = T->getAs<ObjCObjectType>()) 3516 return Ty->getInterface(); 3517 3518 return 0; 3519 } 3520 3521 StringRef ObjCBridgedCastExpr::getBridgeKindName() const { 3522 switch (getBridgeKind()) { 3523 case OBC_Bridge: 3524 return "__bridge"; 3525 case OBC_BridgeTransfer: 3526 return "__bridge_transfer"; 3527 case OBC_BridgeRetained: 3528 return "__bridge_retained"; 3529 } 3530 3531 llvm_unreachable("Invalid BridgeKind!"); 3532 } 3533 3534 ShuffleVectorExpr::ShuffleVectorExpr(ASTContext &C, ArrayRef<Expr*> args, 3535 QualType Type, SourceLocation BLoc, 3536 SourceLocation RP) 3537 : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary, 3538 Type->isDependentType(), Type->isDependentType(), 3539 Type->isInstantiationDependentType(), 3540 Type->containsUnexpandedParameterPack()), 3541 BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size()) 3542 { 3543 SubExprs = new (C) Stmt*[args.size()]; 3544 for (unsigned i = 0; i != args.size(); i++) { 3545 if (args[i]->isTypeDependent()) 3546 ExprBits.TypeDependent = true; 3547 if (args[i]->isValueDependent()) 3548 ExprBits.ValueDependent = true; 3549 if (args[i]->isInstantiationDependent()) 3550 ExprBits.InstantiationDependent = true; 3551 if (args[i]->containsUnexpandedParameterPack()) 3552 ExprBits.ContainsUnexpandedParameterPack = true; 3553 3554 SubExprs[i] = args[i]; 3555 } 3556 } 3557 3558 void ShuffleVectorExpr::setExprs(ASTContext &C, ArrayRef<Expr *> Exprs) { 3559 if (SubExprs) C.Deallocate(SubExprs); 3560 3561 this->NumExprs = Exprs.size(); 3562 SubExprs = new (C) Stmt*[NumExprs]; 3563 memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size()); 3564 } 3565 3566 GenericSelectionExpr::GenericSelectionExpr(ASTContext &Context, 3567 SourceLocation GenericLoc, Expr *ControllingExpr, 3568 ArrayRef<TypeSourceInfo*> AssocTypes, 3569 ArrayRef<Expr*> AssocExprs, 3570 SourceLocation DefaultLoc, 3571 SourceLocation RParenLoc, 3572 bool ContainsUnexpandedParameterPack, 3573 unsigned ResultIndex) 3574 : Expr(GenericSelectionExprClass, 3575 AssocExprs[ResultIndex]->getType(), 3576 AssocExprs[ResultIndex]->getValueKind(), 3577 AssocExprs[ResultIndex]->getObjectKind(), 3578 AssocExprs[ResultIndex]->isTypeDependent(), 3579 AssocExprs[ResultIndex]->isValueDependent(), 3580 AssocExprs[ResultIndex]->isInstantiationDependent(), 3581 ContainsUnexpandedParameterPack), 3582 AssocTypes(new (Context) TypeSourceInfo*[AssocTypes.size()]), 3583 SubExprs(new (Context) Stmt*[END_EXPR+AssocExprs.size()]), 3584 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex), 3585 GenericLoc(GenericLoc), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) { 3586 SubExprs[CONTROLLING] = ControllingExpr; 3587 assert(AssocTypes.size() == AssocExprs.size()); 3588 std::copy(AssocTypes.begin(), AssocTypes.end(), this->AssocTypes); 3589 std::copy(AssocExprs.begin(), AssocExprs.end(), SubExprs+END_EXPR); 3590 } 3591 3592 GenericSelectionExpr::GenericSelectionExpr(ASTContext &Context, 3593 SourceLocation GenericLoc, Expr *ControllingExpr, 3594 ArrayRef<TypeSourceInfo*> AssocTypes, 3595 ArrayRef<Expr*> AssocExprs, 3596 SourceLocation DefaultLoc, 3597 SourceLocation RParenLoc, 3598 bool ContainsUnexpandedParameterPack) 3599 : Expr(GenericSelectionExprClass, 3600 Context.DependentTy, 3601 VK_RValue, 3602 OK_Ordinary, 3603 /*isTypeDependent=*/true, 3604 /*isValueDependent=*/true, 3605 /*isInstantiationDependent=*/true, 3606 ContainsUnexpandedParameterPack), 3607 AssocTypes(new (Context) TypeSourceInfo*[AssocTypes.size()]), 3608 SubExprs(new (Context) Stmt*[END_EXPR+AssocExprs.size()]), 3609 NumAssocs(AssocExprs.size()), ResultIndex(-1U), GenericLoc(GenericLoc), 3610 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) { 3611 SubExprs[CONTROLLING] = ControllingExpr; 3612 assert(AssocTypes.size() == AssocExprs.size()); 3613 std::copy(AssocTypes.begin(), AssocTypes.end(), this->AssocTypes); 3614 std::copy(AssocExprs.begin(), AssocExprs.end(), SubExprs+END_EXPR); 3615 } 3616 3617 //===----------------------------------------------------------------------===// 3618 // DesignatedInitExpr 3619 //===----------------------------------------------------------------------===// 3620 3621 IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const { 3622 assert(Kind == FieldDesignator && "Only valid on a field designator"); 3623 if (Field.NameOrField & 0x01) 3624 return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01); 3625 else 3626 return getField()->getIdentifier(); 3627 } 3628 3629 DesignatedInitExpr::DesignatedInitExpr(ASTContext &C, QualType Ty, 3630 unsigned NumDesignators, 3631 const Designator *Designators, 3632 SourceLocation EqualOrColonLoc, 3633 bool GNUSyntax, 3634 ArrayRef<Expr*> IndexExprs, 3635 Expr *Init) 3636 : Expr(DesignatedInitExprClass, Ty, 3637 Init->getValueKind(), Init->getObjectKind(), 3638 Init->isTypeDependent(), Init->isValueDependent(), 3639 Init->isInstantiationDependent(), 3640 Init->containsUnexpandedParameterPack()), 3641 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax), 3642 NumDesignators(NumDesignators), NumSubExprs(IndexExprs.size() + 1) { 3643 this->Designators = new (C) Designator[NumDesignators]; 3644 3645 // Record the initializer itself. 3646 child_range Child = children(); 3647 *Child++ = Init; 3648 3649 // Copy the designators and their subexpressions, computing 3650 // value-dependence along the way. 3651 unsigned IndexIdx = 0; 3652 for (unsigned I = 0; I != NumDesignators; ++I) { 3653 this->Designators[I] = Designators[I]; 3654 3655 if (this->Designators[I].isArrayDesignator()) { 3656 // Compute type- and value-dependence. 3657 Expr *Index = IndexExprs[IndexIdx]; 3658 if (Index->isTypeDependent() || Index->isValueDependent()) 3659 ExprBits.ValueDependent = true; 3660 if (Index->isInstantiationDependent()) 3661 ExprBits.InstantiationDependent = true; 3662 // Propagate unexpanded parameter packs. 3663 if (Index->containsUnexpandedParameterPack()) 3664 ExprBits.ContainsUnexpandedParameterPack = true; 3665 3666 // Copy the index expressions into permanent storage. 3667 *Child++ = IndexExprs[IndexIdx++]; 3668 } else if (this->Designators[I].isArrayRangeDesignator()) { 3669 // Compute type- and value-dependence. 3670 Expr *Start = IndexExprs[IndexIdx]; 3671 Expr *End = IndexExprs[IndexIdx + 1]; 3672 if (Start->isTypeDependent() || Start->isValueDependent() || 3673 End->isTypeDependent() || End->isValueDependent()) { 3674 ExprBits.ValueDependent = true; 3675 ExprBits.InstantiationDependent = true; 3676 } else if (Start->isInstantiationDependent() || 3677 End->isInstantiationDependent()) { 3678 ExprBits.InstantiationDependent = true; 3679 } 3680 3681 // Propagate unexpanded parameter packs. 3682 if (Start->containsUnexpandedParameterPack() || 3683 End->containsUnexpandedParameterPack()) 3684 ExprBits.ContainsUnexpandedParameterPack = true; 3685 3686 // Copy the start/end expressions into permanent storage. 3687 *Child++ = IndexExprs[IndexIdx++]; 3688 *Child++ = IndexExprs[IndexIdx++]; 3689 } 3690 } 3691 3692 assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions"); 3693 } 3694 3695 DesignatedInitExpr * 3696 DesignatedInitExpr::Create(ASTContext &C, Designator *Designators, 3697 unsigned NumDesignators, 3698 ArrayRef<Expr*> IndexExprs, 3699 SourceLocation ColonOrEqualLoc, 3700 bool UsesColonSyntax, Expr *Init) { 3701 void *Mem = C.Allocate(sizeof(DesignatedInitExpr) + 3702 sizeof(Stmt *) * (IndexExprs.size() + 1), 8); 3703 return new (Mem) DesignatedInitExpr(C, C.VoidTy, NumDesignators, Designators, 3704 ColonOrEqualLoc, UsesColonSyntax, 3705 IndexExprs, Init); 3706 } 3707 3708 DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(ASTContext &C, 3709 unsigned NumIndexExprs) { 3710 void *Mem = C.Allocate(sizeof(DesignatedInitExpr) + 3711 sizeof(Stmt *) * (NumIndexExprs + 1), 8); 3712 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1); 3713 } 3714 3715 void DesignatedInitExpr::setDesignators(ASTContext &C, 3716 const Designator *Desigs, 3717 unsigned NumDesigs) { 3718 Designators = new (C) Designator[NumDesigs]; 3719 NumDesignators = NumDesigs; 3720 for (unsigned I = 0; I != NumDesigs; ++I) 3721 Designators[I] = Desigs[I]; 3722 } 3723 3724 SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const { 3725 DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this); 3726 if (size() == 1) 3727 return DIE->getDesignator(0)->getSourceRange(); 3728 return SourceRange(DIE->getDesignator(0)->getLocStart(), 3729 DIE->getDesignator(size()-1)->getLocEnd()); 3730 } 3731 3732 SourceLocation DesignatedInitExpr::getLocStart() const { 3733 SourceLocation StartLoc; 3734 Designator &First = 3735 *const_cast<DesignatedInitExpr*>(this)->designators_begin(); 3736 if (First.isFieldDesignator()) { 3737 if (GNUSyntax) 3738 StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc); 3739 else 3740 StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc); 3741 } else 3742 StartLoc = 3743 SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc); 3744 return StartLoc; 3745 } 3746 3747 SourceLocation DesignatedInitExpr::getLocEnd() const { 3748 return getInit()->getLocEnd(); 3749 } 3750 3751 Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const { 3752 assert(D.Kind == Designator::ArrayDesignator && "Requires array designator"); 3753 char *Ptr = static_cast<char *>( 3754 const_cast<void *>(static_cast<const void *>(this))); 3755 Ptr += sizeof(DesignatedInitExpr); 3756 Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr)); 3757 return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1)); 3758 } 3759 3760 Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const { 3761 assert(D.Kind == Designator::ArrayRangeDesignator && 3762 "Requires array range designator"); 3763 char *Ptr = static_cast<char *>( 3764 const_cast<void *>(static_cast<const void *>(this))); 3765 Ptr += sizeof(DesignatedInitExpr); 3766 Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr)); 3767 return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1)); 3768 } 3769 3770 Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const { 3771 assert(D.Kind == Designator::ArrayRangeDesignator && 3772 "Requires array range designator"); 3773 char *Ptr = static_cast<char *>( 3774 const_cast<void *>(static_cast<const void *>(this))); 3775 Ptr += sizeof(DesignatedInitExpr); 3776 Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr)); 3777 return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 2)); 3778 } 3779 3780 /// \brief Replaces the designator at index @p Idx with the series 3781 /// of designators in [First, Last). 3782 void DesignatedInitExpr::ExpandDesignator(ASTContext &C, unsigned Idx, 3783 const Designator *First, 3784 const Designator *Last) { 3785 unsigned NumNewDesignators = Last - First; 3786 if (NumNewDesignators == 0) { 3787 std::copy_backward(Designators + Idx + 1, 3788 Designators + NumDesignators, 3789 Designators + Idx); 3790 --NumNewDesignators; 3791 return; 3792 } else if (NumNewDesignators == 1) { 3793 Designators[Idx] = *First; 3794 return; 3795 } 3796 3797 Designator *NewDesignators 3798 = new (C) Designator[NumDesignators - 1 + NumNewDesignators]; 3799 std::copy(Designators, Designators + Idx, NewDesignators); 3800 std::copy(First, Last, NewDesignators + Idx); 3801 std::copy(Designators + Idx + 1, Designators + NumDesignators, 3802 NewDesignators + Idx + NumNewDesignators); 3803 Designators = NewDesignators; 3804 NumDesignators = NumDesignators - 1 + NumNewDesignators; 3805 } 3806 3807 ParenListExpr::ParenListExpr(ASTContext& C, SourceLocation lparenloc, 3808 ArrayRef<Expr*> exprs, 3809 SourceLocation rparenloc) 3810 : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary, 3811 false, false, false, false), 3812 NumExprs(exprs.size()), LParenLoc(lparenloc), RParenLoc(rparenloc) { 3813 Exprs = new (C) Stmt*[exprs.size()]; 3814 for (unsigned i = 0; i != exprs.size(); ++i) { 3815 if (exprs[i]->isTypeDependent()) 3816 ExprBits.TypeDependent = true; 3817 if (exprs[i]->isValueDependent()) 3818 ExprBits.ValueDependent = true; 3819 if (exprs[i]->isInstantiationDependent()) 3820 ExprBits.InstantiationDependent = true; 3821 if (exprs[i]->containsUnexpandedParameterPack()) 3822 ExprBits.ContainsUnexpandedParameterPack = true; 3823 3824 Exprs[i] = exprs[i]; 3825 } 3826 } 3827 3828 const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) { 3829 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e)) 3830 e = ewc->getSubExpr(); 3831 if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e)) 3832 e = m->GetTemporaryExpr(); 3833 e = cast<CXXConstructExpr>(e)->getArg(0); 3834 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e)) 3835 e = ice->getSubExpr(); 3836 return cast<OpaqueValueExpr>(e); 3837 } 3838 3839 PseudoObjectExpr *PseudoObjectExpr::Create(ASTContext &Context, EmptyShell sh, 3840 unsigned numSemanticExprs) { 3841 void *buffer = Context.Allocate(sizeof(PseudoObjectExpr) + 3842 (1 + numSemanticExprs) * sizeof(Expr*), 3843 llvm::alignOf<PseudoObjectExpr>()); 3844 return new(buffer) PseudoObjectExpr(sh, numSemanticExprs); 3845 } 3846 3847 PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs) 3848 : Expr(PseudoObjectExprClass, shell) { 3849 PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1; 3850 } 3851 3852 PseudoObjectExpr *PseudoObjectExpr::Create(ASTContext &C, Expr *syntax, 3853 ArrayRef<Expr*> semantics, 3854 unsigned resultIndex) { 3855 assert(syntax && "no syntactic expression!"); 3856 assert(semantics.size() && "no semantic expressions!"); 3857 3858 QualType type; 3859 ExprValueKind VK; 3860 if (resultIndex == NoResult) { 3861 type = C.VoidTy; 3862 VK = VK_RValue; 3863 } else { 3864 assert(resultIndex < semantics.size()); 3865 type = semantics[resultIndex]->getType(); 3866 VK = semantics[resultIndex]->getValueKind(); 3867 assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary); 3868 } 3869 3870 void *buffer = C.Allocate(sizeof(PseudoObjectExpr) + 3871 (1 + semantics.size()) * sizeof(Expr*), 3872 llvm::alignOf<PseudoObjectExpr>()); 3873 return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics, 3874 resultIndex); 3875 } 3876 3877 PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK, 3878 Expr *syntax, ArrayRef<Expr*> semantics, 3879 unsigned resultIndex) 3880 : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary, 3881 /*filled in at end of ctor*/ false, false, false, false) { 3882 PseudoObjectExprBits.NumSubExprs = semantics.size() + 1; 3883 PseudoObjectExprBits.ResultIndex = resultIndex + 1; 3884 3885 for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) { 3886 Expr *E = (i == 0 ? syntax : semantics[i-1]); 3887 getSubExprsBuffer()[i] = E; 3888 3889 if (E->isTypeDependent()) 3890 ExprBits.TypeDependent = true; 3891 if (E->isValueDependent()) 3892 ExprBits.ValueDependent = true; 3893 if (E->isInstantiationDependent()) 3894 ExprBits.InstantiationDependent = true; 3895 if (E->containsUnexpandedParameterPack()) 3896 ExprBits.ContainsUnexpandedParameterPack = true; 3897 3898 if (isa<OpaqueValueExpr>(E)) 3899 assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != 0 && 3900 "opaque-value semantic expressions for pseudo-object " 3901 "operations must have sources"); 3902 } 3903 } 3904 3905 //===----------------------------------------------------------------------===// 3906 // ExprIterator. 3907 //===----------------------------------------------------------------------===// 3908 3909 Expr* ExprIterator::operator[](size_t idx) { return cast<Expr>(I[idx]); } 3910 Expr* ExprIterator::operator*() const { return cast<Expr>(*I); } 3911 Expr* ExprIterator::operator->() const { return cast<Expr>(*I); } 3912 const Expr* ConstExprIterator::operator[](size_t idx) const { 3913 return cast<Expr>(I[idx]); 3914 } 3915 const Expr* ConstExprIterator::operator*() const { return cast<Expr>(*I); } 3916 const Expr* ConstExprIterator::operator->() const { return cast<Expr>(*I); } 3917 3918 //===----------------------------------------------------------------------===// 3919 // Child Iterators for iterating over subexpressions/substatements 3920 //===----------------------------------------------------------------------===// 3921 3922 // UnaryExprOrTypeTraitExpr 3923 Stmt::child_range UnaryExprOrTypeTraitExpr::children() { 3924 // If this is of a type and the type is a VLA type (and not a typedef), the 3925 // size expression of the VLA needs to be treated as an executable expression. 3926 // Why isn't this weirdness documented better in StmtIterator? 3927 if (isArgumentType()) { 3928 if (const VariableArrayType* T = dyn_cast<VariableArrayType>( 3929 getArgumentType().getTypePtr())) 3930 return child_range(child_iterator(T), child_iterator()); 3931 return child_range(); 3932 } 3933 return child_range(&Argument.Ex, &Argument.Ex + 1); 3934 } 3935 3936 // ObjCMessageExpr 3937 Stmt::child_range ObjCMessageExpr::children() { 3938 Stmt **begin; 3939 if (getReceiverKind() == Instance) 3940 begin = reinterpret_cast<Stmt **>(this + 1); 3941 else 3942 begin = reinterpret_cast<Stmt **>(getArgs()); 3943 return child_range(begin, 3944 reinterpret_cast<Stmt **>(getArgs() + getNumArgs())); 3945 } 3946 3947 ObjCArrayLiteral::ObjCArrayLiteral(ArrayRef<Expr *> Elements, 3948 QualType T, ObjCMethodDecl *Method, 3949 SourceRange SR) 3950 : Expr(ObjCArrayLiteralClass, T, VK_RValue, OK_Ordinary, 3951 false, false, false, false), 3952 NumElements(Elements.size()), Range(SR), ArrayWithObjectsMethod(Method) 3953 { 3954 Expr **SaveElements = getElements(); 3955 for (unsigned I = 0, N = Elements.size(); I != N; ++I) { 3956 if (Elements[I]->isTypeDependent() || Elements[I]->isValueDependent()) 3957 ExprBits.ValueDependent = true; 3958 if (Elements[I]->isInstantiationDependent()) 3959 ExprBits.InstantiationDependent = true; 3960 if (Elements[I]->containsUnexpandedParameterPack()) 3961 ExprBits.ContainsUnexpandedParameterPack = true; 3962 3963 SaveElements[I] = Elements[I]; 3964 } 3965 } 3966 3967 ObjCArrayLiteral *ObjCArrayLiteral::Create(ASTContext &C, 3968 ArrayRef<Expr *> Elements, 3969 QualType T, ObjCMethodDecl * Method, 3970 SourceRange SR) { 3971 void *Mem = C.Allocate(sizeof(ObjCArrayLiteral) 3972 + Elements.size() * sizeof(Expr *)); 3973 return new (Mem) ObjCArrayLiteral(Elements, T, Method, SR); 3974 } 3975 3976 ObjCArrayLiteral *ObjCArrayLiteral::CreateEmpty(ASTContext &C, 3977 unsigned NumElements) { 3978 3979 void *Mem = C.Allocate(sizeof(ObjCArrayLiteral) 3980 + NumElements * sizeof(Expr *)); 3981 return new (Mem) ObjCArrayLiteral(EmptyShell(), NumElements); 3982 } 3983 3984 ObjCDictionaryLiteral::ObjCDictionaryLiteral( 3985 ArrayRef<ObjCDictionaryElement> VK, 3986 bool HasPackExpansions, 3987 QualType T, ObjCMethodDecl *method, 3988 SourceRange SR) 3989 : Expr(ObjCDictionaryLiteralClass, T, VK_RValue, OK_Ordinary, false, false, 3990 false, false), 3991 NumElements(VK.size()), HasPackExpansions(HasPackExpansions), Range(SR), 3992 DictWithObjectsMethod(method) 3993 { 3994 KeyValuePair *KeyValues = getKeyValues(); 3995 ExpansionData *Expansions = getExpansionData(); 3996 for (unsigned I = 0; I < NumElements; I++) { 3997 if (VK[I].Key->isTypeDependent() || VK[I].Key->isValueDependent() || 3998 VK[I].Value->isTypeDependent() || VK[I].Value->isValueDependent()) 3999 ExprBits.ValueDependent = true; 4000 if (VK[I].Key->isInstantiationDependent() || 4001 VK[I].Value->isInstantiationDependent()) 4002 ExprBits.InstantiationDependent = true; 4003 if (VK[I].EllipsisLoc.isInvalid() && 4004 (VK[I].Key->containsUnexpandedParameterPack() || 4005 VK[I].Value->containsUnexpandedParameterPack())) 4006 ExprBits.ContainsUnexpandedParameterPack = true; 4007 4008 KeyValues[I].Key = VK[I].Key; 4009 KeyValues[I].Value = VK[I].Value; 4010 if (Expansions) { 4011 Expansions[I].EllipsisLoc = VK[I].EllipsisLoc; 4012 if (VK[I].NumExpansions) 4013 Expansions[I].NumExpansionsPlusOne = *VK[I].NumExpansions + 1; 4014 else 4015 Expansions[I].NumExpansionsPlusOne = 0; 4016 } 4017 } 4018 } 4019 4020 ObjCDictionaryLiteral * 4021 ObjCDictionaryLiteral::Create(ASTContext &C, 4022 ArrayRef<ObjCDictionaryElement> VK, 4023 bool HasPackExpansions, 4024 QualType T, ObjCMethodDecl *method, 4025 SourceRange SR) { 4026 unsigned ExpansionsSize = 0; 4027 if (HasPackExpansions) 4028 ExpansionsSize = sizeof(ExpansionData) * VK.size(); 4029 4030 void *Mem = C.Allocate(sizeof(ObjCDictionaryLiteral) + 4031 sizeof(KeyValuePair) * VK.size() + ExpansionsSize); 4032 return new (Mem) ObjCDictionaryLiteral(VK, HasPackExpansions, T, method, SR); 4033 } 4034 4035 ObjCDictionaryLiteral * 4036 ObjCDictionaryLiteral::CreateEmpty(ASTContext &C, unsigned NumElements, 4037 bool HasPackExpansions) { 4038 unsigned ExpansionsSize = 0; 4039 if (HasPackExpansions) 4040 ExpansionsSize = sizeof(ExpansionData) * NumElements; 4041 void *Mem = C.Allocate(sizeof(ObjCDictionaryLiteral) + 4042 sizeof(KeyValuePair) * NumElements + ExpansionsSize); 4043 return new (Mem) ObjCDictionaryLiteral(EmptyShell(), NumElements, 4044 HasPackExpansions); 4045 } 4046 4047 ObjCSubscriptRefExpr *ObjCSubscriptRefExpr::Create(ASTContext &C, 4048 Expr *base, 4049 Expr *key, QualType T, 4050 ObjCMethodDecl *getMethod, 4051 ObjCMethodDecl *setMethod, 4052 SourceLocation RB) { 4053 void *Mem = C.Allocate(sizeof(ObjCSubscriptRefExpr)); 4054 return new (Mem) ObjCSubscriptRefExpr(base, key, T, VK_LValue, 4055 OK_ObjCSubscript, 4056 getMethod, setMethod, RB); 4057 } 4058 4059 AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args, 4060 QualType t, AtomicOp op, SourceLocation RP) 4061 : Expr(AtomicExprClass, t, VK_RValue, OK_Ordinary, 4062 false, false, false, false), 4063 NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op) 4064 { 4065 assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions"); 4066 for (unsigned i = 0; i != args.size(); i++) { 4067 if (args[i]->isTypeDependent()) 4068 ExprBits.TypeDependent = true; 4069 if (args[i]->isValueDependent()) 4070 ExprBits.ValueDependent = true; 4071 if (args[i]->isInstantiationDependent()) 4072 ExprBits.InstantiationDependent = true; 4073 if (args[i]->containsUnexpandedParameterPack()) 4074 ExprBits.ContainsUnexpandedParameterPack = true; 4075 4076 SubExprs[i] = args[i]; 4077 } 4078 } 4079 4080 unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) { 4081 switch (Op) { 4082 case AO__c11_atomic_init: 4083 case AO__c11_atomic_load: 4084 case AO__atomic_load_n: 4085 return 2; 4086 4087 case AO__c11_atomic_store: 4088 case AO__c11_atomic_exchange: 4089 case AO__atomic_load: 4090 case AO__atomic_store: 4091 case AO__atomic_store_n: 4092 case AO__atomic_exchange_n: 4093 case AO__c11_atomic_fetch_add: 4094 case AO__c11_atomic_fetch_sub: 4095 case AO__c11_atomic_fetch_and: 4096 case AO__c11_atomic_fetch_or: 4097 case AO__c11_atomic_fetch_xor: 4098 case AO__atomic_fetch_add: 4099 case AO__atomic_fetch_sub: 4100 case AO__atomic_fetch_and: 4101 case AO__atomic_fetch_or: 4102 case AO__atomic_fetch_xor: 4103 case AO__atomic_fetch_nand: 4104 case AO__atomic_add_fetch: 4105 case AO__atomic_sub_fetch: 4106 case AO__atomic_and_fetch: 4107 case AO__atomic_or_fetch: 4108 case AO__atomic_xor_fetch: 4109 case AO__atomic_nand_fetch: 4110 return 3; 4111 4112 case AO__atomic_exchange: 4113 return 4; 4114 4115 case AO__c11_atomic_compare_exchange_strong: 4116 case AO__c11_atomic_compare_exchange_weak: 4117 return 5; 4118 4119 case AO__atomic_compare_exchange: 4120 case AO__atomic_compare_exchange_n: 4121 return 6; 4122 } 4123 llvm_unreachable("unknown atomic op"); 4124 } 4125