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