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