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