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