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