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