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