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 = 1482 dyn_cast_or_null<FunctionDecl>(getCallee()->getReferencedDeclOfCallee()); 1483 return FDecl ? FDecl->getBuiltinID() : 0; 1484 } 1485 1486 bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const { 1487 if (unsigned BI = getBuiltinCallee()) 1488 return Ctx.BuiltinInfo.isUnevaluated(BI); 1489 return false; 1490 } 1491 1492 QualType CallExpr::getCallReturnType(const ASTContext &Ctx) const { 1493 const Expr *Callee = getCallee(); 1494 QualType CalleeType = Callee->getType(); 1495 if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) { 1496 CalleeType = FnTypePtr->getPointeeType(); 1497 } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) { 1498 CalleeType = BPT->getPointeeType(); 1499 } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) { 1500 if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens())) 1501 return Ctx.VoidTy; 1502 1503 if (isa<UnresolvedMemberExpr>(Callee->IgnoreParens())) 1504 return Ctx.DependentTy; 1505 1506 // This should never be overloaded and so should never return null. 1507 CalleeType = Expr::findBoundMemberType(Callee); 1508 assert(!CalleeType.isNull()); 1509 } else if (CalleeType->isDependentType() || 1510 CalleeType->isSpecificPlaceholderType(BuiltinType::Overload)) { 1511 return Ctx.DependentTy; 1512 } 1513 1514 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 1515 return FnType->getReturnType(); 1516 } 1517 1518 const Attr *CallExpr::getUnusedResultAttr(const ASTContext &Ctx) const { 1519 // If the return type is a struct, union, or enum that is marked nodiscard, 1520 // then return the return type attribute. 1521 if (const TagDecl *TD = getCallReturnType(Ctx)->getAsTagDecl()) 1522 if (const auto *A = TD->getAttr<WarnUnusedResultAttr>()) 1523 return A; 1524 1525 // Otherwise, see if the callee is marked nodiscard and return that attribute 1526 // instead. 1527 const Decl *D = getCalleeDecl(); 1528 return D ? D->getAttr<WarnUnusedResultAttr>() : nullptr; 1529 } 1530 1531 SourceLocation CallExpr::getBeginLoc() const { 1532 if (isa<CXXOperatorCallExpr>(this)) 1533 return cast<CXXOperatorCallExpr>(this)->getBeginLoc(); 1534 1535 SourceLocation begin = getCallee()->getBeginLoc(); 1536 if (begin.isInvalid() && getNumArgs() > 0 && getArg(0)) 1537 begin = getArg(0)->getBeginLoc(); 1538 return begin; 1539 } 1540 SourceLocation CallExpr::getEndLoc() const { 1541 if (isa<CXXOperatorCallExpr>(this)) 1542 return cast<CXXOperatorCallExpr>(this)->getEndLoc(); 1543 1544 SourceLocation end = getRParenLoc(); 1545 if (end.isInvalid() && getNumArgs() > 0 && getArg(getNumArgs() - 1)) 1546 end = getArg(getNumArgs() - 1)->getEndLoc(); 1547 return end; 1548 } 1549 1550 OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type, 1551 SourceLocation OperatorLoc, 1552 TypeSourceInfo *tsi, 1553 ArrayRef<OffsetOfNode> comps, 1554 ArrayRef<Expr*> exprs, 1555 SourceLocation RParenLoc) { 1556 void *Mem = C.Allocate( 1557 totalSizeToAlloc<OffsetOfNode, Expr *>(comps.size(), exprs.size())); 1558 1559 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs, 1560 RParenLoc); 1561 } 1562 1563 OffsetOfExpr *OffsetOfExpr::CreateEmpty(const ASTContext &C, 1564 unsigned numComps, unsigned numExprs) { 1565 void *Mem = 1566 C.Allocate(totalSizeToAlloc<OffsetOfNode, Expr *>(numComps, numExprs)); 1567 return new (Mem) OffsetOfExpr(numComps, numExprs); 1568 } 1569 1570 OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type, 1571 SourceLocation OperatorLoc, TypeSourceInfo *tsi, 1572 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr *> exprs, 1573 SourceLocation RParenLoc) 1574 : Expr(OffsetOfExprClass, type, VK_PRValue, OK_Ordinary), 1575 OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi), 1576 NumComps(comps.size()), NumExprs(exprs.size()) { 1577 for (unsigned i = 0; i != comps.size(); ++i) 1578 setComponent(i, comps[i]); 1579 for (unsigned i = 0; i != exprs.size(); ++i) 1580 setIndexExpr(i, exprs[i]); 1581 1582 setDependence(computeDependence(this)); 1583 } 1584 1585 IdentifierInfo *OffsetOfNode::getFieldName() const { 1586 assert(getKind() == Field || getKind() == Identifier); 1587 if (getKind() == Field) 1588 return getField()->getIdentifier(); 1589 1590 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask); 1591 } 1592 1593 UnaryExprOrTypeTraitExpr::UnaryExprOrTypeTraitExpr( 1594 UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType, 1595 SourceLocation op, SourceLocation rp) 1596 : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_PRValue, OK_Ordinary), 1597 OpLoc(op), RParenLoc(rp) { 1598 assert(ExprKind <= UETT_Last && "invalid enum value!"); 1599 UnaryExprOrTypeTraitExprBits.Kind = ExprKind; 1600 assert(static_cast<unsigned>(ExprKind) == UnaryExprOrTypeTraitExprBits.Kind && 1601 "UnaryExprOrTypeTraitExprBits.Kind overflow!"); 1602 UnaryExprOrTypeTraitExprBits.IsType = false; 1603 Argument.Ex = E; 1604 setDependence(computeDependence(this)); 1605 } 1606 1607 MemberExpr::MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc, 1608 ValueDecl *MemberDecl, 1609 const DeclarationNameInfo &NameInfo, QualType T, 1610 ExprValueKind VK, ExprObjectKind OK, 1611 NonOdrUseReason NOUR) 1612 : Expr(MemberExprClass, T, VK, OK), Base(Base), MemberDecl(MemberDecl), 1613 MemberDNLoc(NameInfo.getInfo()), MemberLoc(NameInfo.getLoc()) { 1614 assert(!NameInfo.getName() || 1615 MemberDecl->getDeclName() == NameInfo.getName()); 1616 MemberExprBits.IsArrow = IsArrow; 1617 MemberExprBits.HasQualifierOrFoundDecl = false; 1618 MemberExprBits.HasTemplateKWAndArgsInfo = false; 1619 MemberExprBits.HadMultipleCandidates = false; 1620 MemberExprBits.NonOdrUseReason = NOUR; 1621 MemberExprBits.OperatorLoc = OperatorLoc; 1622 setDependence(computeDependence(this)); 1623 } 1624 1625 MemberExpr *MemberExpr::Create( 1626 const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc, 1627 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, 1628 ValueDecl *MemberDecl, DeclAccessPair FoundDecl, 1629 DeclarationNameInfo NameInfo, const TemplateArgumentListInfo *TemplateArgs, 1630 QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR) { 1631 bool HasQualOrFound = QualifierLoc || FoundDecl.getDecl() != MemberDecl || 1632 FoundDecl.getAccess() != MemberDecl->getAccess(); 1633 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid(); 1634 std::size_t Size = 1635 totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo, 1636 TemplateArgumentLoc>( 1637 HasQualOrFound ? 1 : 0, HasTemplateKWAndArgsInfo ? 1 : 0, 1638 TemplateArgs ? TemplateArgs->size() : 0); 1639 1640 void *Mem = C.Allocate(Size, alignof(MemberExpr)); 1641 MemberExpr *E = new (Mem) MemberExpr(Base, IsArrow, OperatorLoc, MemberDecl, 1642 NameInfo, T, VK, OK, NOUR); 1643 1644 // FIXME: remove remaining dependence computation to computeDependence(). 1645 auto Deps = E->getDependence(); 1646 if (HasQualOrFound) { 1647 // FIXME: Wrong. We should be looking at the member declaration we found. 1648 if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent()) 1649 Deps |= ExprDependence::TypeValueInstantiation; 1650 else if (QualifierLoc && 1651 QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent()) 1652 Deps |= ExprDependence::Instantiation; 1653 1654 E->MemberExprBits.HasQualifierOrFoundDecl = true; 1655 1656 MemberExprNameQualifier *NQ = 1657 E->getTrailingObjects<MemberExprNameQualifier>(); 1658 NQ->QualifierLoc = QualifierLoc; 1659 NQ->FoundDecl = FoundDecl; 1660 } 1661 1662 E->MemberExprBits.HasTemplateKWAndArgsInfo = 1663 TemplateArgs || TemplateKWLoc.isValid(); 1664 1665 if (TemplateArgs) { 1666 auto TemplateArgDeps = TemplateArgumentDependence::None; 1667 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom( 1668 TemplateKWLoc, *TemplateArgs, 1669 E->getTrailingObjects<TemplateArgumentLoc>(), TemplateArgDeps); 1670 if (TemplateArgDeps & TemplateArgumentDependence::Instantiation) 1671 Deps |= ExprDependence::Instantiation; 1672 } else if (TemplateKWLoc.isValid()) { 1673 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom( 1674 TemplateKWLoc); 1675 } 1676 E->setDependence(Deps); 1677 1678 return E; 1679 } 1680 1681 MemberExpr *MemberExpr::CreateEmpty(const ASTContext &Context, 1682 bool HasQualifier, bool HasFoundDecl, 1683 bool HasTemplateKWAndArgsInfo, 1684 unsigned NumTemplateArgs) { 1685 assert((!NumTemplateArgs || HasTemplateKWAndArgsInfo) && 1686 "template args but no template arg info?"); 1687 bool HasQualOrFound = HasQualifier || HasFoundDecl; 1688 std::size_t Size = 1689 totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo, 1690 TemplateArgumentLoc>(HasQualOrFound ? 1 : 0, 1691 HasTemplateKWAndArgsInfo ? 1 : 0, 1692 NumTemplateArgs); 1693 void *Mem = Context.Allocate(Size, alignof(MemberExpr)); 1694 return new (Mem) MemberExpr(EmptyShell()); 1695 } 1696 1697 void MemberExpr::setMemberDecl(ValueDecl *NewD) { 1698 MemberDecl = NewD; 1699 if (getType()->isUndeducedType()) 1700 setType(NewD->getType()); 1701 setDependence(computeDependence(this)); 1702 } 1703 1704 SourceLocation MemberExpr::getBeginLoc() const { 1705 if (isImplicitAccess()) { 1706 if (hasQualifier()) 1707 return getQualifierLoc().getBeginLoc(); 1708 return MemberLoc; 1709 } 1710 1711 // FIXME: We don't want this to happen. Rather, we should be able to 1712 // detect all kinds of implicit accesses more cleanly. 1713 SourceLocation BaseStartLoc = getBase()->getBeginLoc(); 1714 if (BaseStartLoc.isValid()) 1715 return BaseStartLoc; 1716 return MemberLoc; 1717 } 1718 SourceLocation MemberExpr::getEndLoc() const { 1719 SourceLocation EndLoc = getMemberNameInfo().getEndLoc(); 1720 if (hasExplicitTemplateArgs()) 1721 EndLoc = getRAngleLoc(); 1722 else if (EndLoc.isInvalid()) 1723 EndLoc = getBase()->getEndLoc(); 1724 return EndLoc; 1725 } 1726 1727 bool CastExpr::CastConsistency() const { 1728 switch (getCastKind()) { 1729 case CK_DerivedToBase: 1730 case CK_UncheckedDerivedToBase: 1731 case CK_DerivedToBaseMemberPointer: 1732 case CK_BaseToDerived: 1733 case CK_BaseToDerivedMemberPointer: 1734 assert(!path_empty() && "Cast kind should have a base path!"); 1735 break; 1736 1737 case CK_CPointerToObjCPointerCast: 1738 assert(getType()->isObjCObjectPointerType()); 1739 assert(getSubExpr()->getType()->isPointerType()); 1740 goto CheckNoBasePath; 1741 1742 case CK_BlockPointerToObjCPointerCast: 1743 assert(getType()->isObjCObjectPointerType()); 1744 assert(getSubExpr()->getType()->isBlockPointerType()); 1745 goto CheckNoBasePath; 1746 1747 case CK_ReinterpretMemberPointer: 1748 assert(getType()->isMemberPointerType()); 1749 assert(getSubExpr()->getType()->isMemberPointerType()); 1750 goto CheckNoBasePath; 1751 1752 case CK_BitCast: 1753 // Arbitrary casts to C pointer types count as bitcasts. 1754 // Otherwise, we should only have block and ObjC pointer casts 1755 // here if they stay within the type kind. 1756 if (!getType()->isPointerType()) { 1757 assert(getType()->isObjCObjectPointerType() == 1758 getSubExpr()->getType()->isObjCObjectPointerType()); 1759 assert(getType()->isBlockPointerType() == 1760 getSubExpr()->getType()->isBlockPointerType()); 1761 } 1762 goto CheckNoBasePath; 1763 1764 case CK_AnyPointerToBlockPointerCast: 1765 assert(getType()->isBlockPointerType()); 1766 assert(getSubExpr()->getType()->isAnyPointerType() && 1767 !getSubExpr()->getType()->isBlockPointerType()); 1768 goto CheckNoBasePath; 1769 1770 case CK_CopyAndAutoreleaseBlockObject: 1771 assert(getType()->isBlockPointerType()); 1772 assert(getSubExpr()->getType()->isBlockPointerType()); 1773 goto CheckNoBasePath; 1774 1775 case CK_FunctionToPointerDecay: 1776 assert(getType()->isPointerType()); 1777 assert(getSubExpr()->getType()->isFunctionType()); 1778 goto CheckNoBasePath; 1779 1780 case CK_AddressSpaceConversion: { 1781 auto Ty = getType(); 1782 auto SETy = getSubExpr()->getType(); 1783 assert(getValueKindForType(Ty) == Expr::getValueKindForType(SETy)); 1784 if (isPRValue() && !Ty->isDependentType() && !SETy->isDependentType()) { 1785 Ty = Ty->getPointeeType(); 1786 SETy = SETy->getPointeeType(); 1787 } 1788 assert((Ty->isDependentType() || SETy->isDependentType()) || 1789 (!Ty.isNull() && !SETy.isNull() && 1790 Ty.getAddressSpace() != SETy.getAddressSpace())); 1791 goto CheckNoBasePath; 1792 } 1793 // These should not have an inheritance path. 1794 case CK_Dynamic: 1795 case CK_ToUnion: 1796 case CK_ArrayToPointerDecay: 1797 case CK_NullToMemberPointer: 1798 case CK_NullToPointer: 1799 case CK_ConstructorConversion: 1800 case CK_IntegralToPointer: 1801 case CK_PointerToIntegral: 1802 case CK_ToVoid: 1803 case CK_VectorSplat: 1804 case CK_IntegralCast: 1805 case CK_BooleanToSignedIntegral: 1806 case CK_IntegralToFloating: 1807 case CK_FloatingToIntegral: 1808 case CK_FloatingCast: 1809 case CK_ObjCObjectLValueCast: 1810 case CK_FloatingRealToComplex: 1811 case CK_FloatingComplexToReal: 1812 case CK_FloatingComplexCast: 1813 case CK_FloatingComplexToIntegralComplex: 1814 case CK_IntegralRealToComplex: 1815 case CK_IntegralComplexToReal: 1816 case CK_IntegralComplexCast: 1817 case CK_IntegralComplexToFloatingComplex: 1818 case CK_ARCProduceObject: 1819 case CK_ARCConsumeObject: 1820 case CK_ARCReclaimReturnedObject: 1821 case CK_ARCExtendBlockObject: 1822 case CK_ZeroToOCLOpaqueType: 1823 case CK_IntToOCLSampler: 1824 case CK_FloatingToFixedPoint: 1825 case CK_FixedPointToFloating: 1826 case CK_FixedPointCast: 1827 case CK_FixedPointToIntegral: 1828 case CK_IntegralToFixedPoint: 1829 case CK_MatrixCast: 1830 assert(!getType()->isBooleanType() && "unheralded conversion to bool"); 1831 goto CheckNoBasePath; 1832 1833 case CK_Dependent: 1834 case CK_LValueToRValue: 1835 case CK_NoOp: 1836 case CK_AtomicToNonAtomic: 1837 case CK_NonAtomicToAtomic: 1838 case CK_PointerToBoolean: 1839 case CK_IntegralToBoolean: 1840 case CK_FloatingToBoolean: 1841 case CK_MemberPointerToBoolean: 1842 case CK_FloatingComplexToBoolean: 1843 case CK_IntegralComplexToBoolean: 1844 case CK_LValueBitCast: // -> bool& 1845 case CK_LValueToRValueBitCast: 1846 case CK_UserDefinedConversion: // operator bool() 1847 case CK_BuiltinFnToFnPtr: 1848 case CK_FixedPointToBoolean: 1849 CheckNoBasePath: 1850 assert(path_empty() && "Cast kind should not have a base path!"); 1851 break; 1852 } 1853 return true; 1854 } 1855 1856 const char *CastExpr::getCastKindName(CastKind CK) { 1857 switch (CK) { 1858 #define CAST_OPERATION(Name) case CK_##Name: return #Name; 1859 #include "clang/AST/OperationKinds.def" 1860 } 1861 llvm_unreachable("Unhandled cast kind!"); 1862 } 1863 1864 namespace { 1865 // Skip over implicit nodes produced as part of semantic analysis. 1866 // Designed for use with IgnoreExprNodes. 1867 Expr *ignoreImplicitSemaNodes(Expr *E) { 1868 if (auto *Materialize = dyn_cast<MaterializeTemporaryExpr>(E)) 1869 return Materialize->getSubExpr(); 1870 1871 if (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E)) 1872 return Binder->getSubExpr(); 1873 1874 if (auto *Full = dyn_cast<FullExpr>(E)) 1875 return Full->getSubExpr(); 1876 1877 return E; 1878 } 1879 } // namespace 1880 1881 Expr *CastExpr::getSubExprAsWritten() { 1882 const Expr *SubExpr = nullptr; 1883 1884 for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) { 1885 SubExpr = IgnoreExprNodes(E->getSubExpr(), ignoreImplicitSemaNodes); 1886 1887 // Conversions by constructor and conversion functions have a 1888 // subexpression describing the call; strip it off. 1889 if (E->getCastKind() == CK_ConstructorConversion) { 1890 SubExpr = IgnoreExprNodes(cast<CXXConstructExpr>(SubExpr)->getArg(0), 1891 ignoreImplicitSemaNodes); 1892 } else if (E->getCastKind() == CK_UserDefinedConversion) { 1893 assert((isa<CXXMemberCallExpr>(SubExpr) || isa<BlockExpr>(SubExpr)) && 1894 "Unexpected SubExpr for CK_UserDefinedConversion."); 1895 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr)) 1896 SubExpr = MCE->getImplicitObjectArgument(); 1897 } 1898 } 1899 1900 return const_cast<Expr *>(SubExpr); 1901 } 1902 1903 NamedDecl *CastExpr::getConversionFunction() const { 1904 const Expr *SubExpr = nullptr; 1905 1906 for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) { 1907 SubExpr = IgnoreExprNodes(E->getSubExpr(), ignoreImplicitSemaNodes); 1908 1909 if (E->getCastKind() == CK_ConstructorConversion) 1910 return cast<CXXConstructExpr>(SubExpr)->getConstructor(); 1911 1912 if (E->getCastKind() == CK_UserDefinedConversion) { 1913 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr)) 1914 return MCE->getMethodDecl(); 1915 } 1916 } 1917 1918 return nullptr; 1919 } 1920 1921 CXXBaseSpecifier **CastExpr::path_buffer() { 1922 switch (getStmtClass()) { 1923 #define ABSTRACT_STMT(x) 1924 #define CASTEXPR(Type, Base) \ 1925 case Stmt::Type##Class: \ 1926 return static_cast<Type *>(this)->getTrailingObjects<CXXBaseSpecifier *>(); 1927 #define STMT(Type, Base) 1928 #include "clang/AST/StmtNodes.inc" 1929 default: 1930 llvm_unreachable("non-cast expressions not possible here"); 1931 } 1932 } 1933 1934 const FieldDecl *CastExpr::getTargetFieldForToUnionCast(QualType unionType, 1935 QualType opType) { 1936 auto RD = unionType->castAs<RecordType>()->getDecl(); 1937 return getTargetFieldForToUnionCast(RD, opType); 1938 } 1939 1940 const FieldDecl *CastExpr::getTargetFieldForToUnionCast(const RecordDecl *RD, 1941 QualType OpType) { 1942 auto &Ctx = RD->getASTContext(); 1943 RecordDecl::field_iterator Field, FieldEnd; 1944 for (Field = RD->field_begin(), FieldEnd = RD->field_end(); 1945 Field != FieldEnd; ++Field) { 1946 if (Ctx.hasSameUnqualifiedType(Field->getType(), OpType) && 1947 !Field->isUnnamedBitfield()) { 1948 return *Field; 1949 } 1950 } 1951 return nullptr; 1952 } 1953 1954 FPOptionsOverride *CastExpr::getTrailingFPFeatures() { 1955 assert(hasStoredFPFeatures()); 1956 switch (getStmtClass()) { 1957 case ImplicitCastExprClass: 1958 return static_cast<ImplicitCastExpr *>(this) 1959 ->getTrailingObjects<FPOptionsOverride>(); 1960 case CStyleCastExprClass: 1961 return static_cast<CStyleCastExpr *>(this) 1962 ->getTrailingObjects<FPOptionsOverride>(); 1963 case CXXFunctionalCastExprClass: 1964 return static_cast<CXXFunctionalCastExpr *>(this) 1965 ->getTrailingObjects<FPOptionsOverride>(); 1966 case CXXStaticCastExprClass: 1967 return static_cast<CXXStaticCastExpr *>(this) 1968 ->getTrailingObjects<FPOptionsOverride>(); 1969 default: 1970 llvm_unreachable("Cast does not have FPFeatures"); 1971 } 1972 } 1973 1974 ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T, 1975 CastKind Kind, Expr *Operand, 1976 const CXXCastPath *BasePath, 1977 ExprValueKind VK, 1978 FPOptionsOverride FPO) { 1979 unsigned PathSize = (BasePath ? BasePath->size() : 0); 1980 void *Buffer = 1981 C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>( 1982 PathSize, FPO.requiresTrailingStorage())); 1983 // Per C++ [conv.lval]p3, lvalue-to-rvalue conversions on class and 1984 // std::nullptr_t have special semantics not captured by CK_LValueToRValue. 1985 assert((Kind != CK_LValueToRValue || 1986 !(T->isNullPtrType() || T->getAsCXXRecordDecl())) && 1987 "invalid type for lvalue-to-rvalue conversion"); 1988 ImplicitCastExpr *E = 1989 new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, FPO, VK); 1990 if (PathSize) 1991 std::uninitialized_copy_n(BasePath->data(), BasePath->size(), 1992 E->getTrailingObjects<CXXBaseSpecifier *>()); 1993 return E; 1994 } 1995 1996 ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C, 1997 unsigned PathSize, 1998 bool HasFPFeatures) { 1999 void *Buffer = 2000 C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>( 2001 PathSize, HasFPFeatures)); 2002 return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize, HasFPFeatures); 2003 } 2004 2005 CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T, 2006 ExprValueKind VK, CastKind K, Expr *Op, 2007 const CXXCastPath *BasePath, 2008 FPOptionsOverride FPO, 2009 TypeSourceInfo *WrittenTy, 2010 SourceLocation L, SourceLocation R) { 2011 unsigned PathSize = (BasePath ? BasePath->size() : 0); 2012 void *Buffer = 2013 C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>( 2014 PathSize, FPO.requiresTrailingStorage())); 2015 CStyleCastExpr *E = 2016 new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, FPO, WrittenTy, L, R); 2017 if (PathSize) 2018 std::uninitialized_copy_n(BasePath->data(), BasePath->size(), 2019 E->getTrailingObjects<CXXBaseSpecifier *>()); 2020 return E; 2021 } 2022 2023 CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C, 2024 unsigned PathSize, 2025 bool HasFPFeatures) { 2026 void *Buffer = 2027 C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>( 2028 PathSize, HasFPFeatures)); 2029 return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize, HasFPFeatures); 2030 } 2031 2032 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it 2033 /// corresponds to, e.g. "<<=". 2034 StringRef BinaryOperator::getOpcodeStr(Opcode Op) { 2035 switch (Op) { 2036 #define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling; 2037 #include "clang/AST/OperationKinds.def" 2038 } 2039 llvm_unreachable("Invalid OpCode!"); 2040 } 2041 2042 BinaryOperatorKind 2043 BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) { 2044 switch (OO) { 2045 default: llvm_unreachable("Not an overloadable binary operator"); 2046 case OO_Plus: return BO_Add; 2047 case OO_Minus: return BO_Sub; 2048 case OO_Star: return BO_Mul; 2049 case OO_Slash: return BO_Div; 2050 case OO_Percent: return BO_Rem; 2051 case OO_Caret: return BO_Xor; 2052 case OO_Amp: return BO_And; 2053 case OO_Pipe: return BO_Or; 2054 case OO_Equal: return BO_Assign; 2055 case OO_Spaceship: return BO_Cmp; 2056 case OO_Less: return BO_LT; 2057 case OO_Greater: return BO_GT; 2058 case OO_PlusEqual: return BO_AddAssign; 2059 case OO_MinusEqual: return BO_SubAssign; 2060 case OO_StarEqual: return BO_MulAssign; 2061 case OO_SlashEqual: return BO_DivAssign; 2062 case OO_PercentEqual: return BO_RemAssign; 2063 case OO_CaretEqual: return BO_XorAssign; 2064 case OO_AmpEqual: return BO_AndAssign; 2065 case OO_PipeEqual: return BO_OrAssign; 2066 case OO_LessLess: return BO_Shl; 2067 case OO_GreaterGreater: return BO_Shr; 2068 case OO_LessLessEqual: return BO_ShlAssign; 2069 case OO_GreaterGreaterEqual: return BO_ShrAssign; 2070 case OO_EqualEqual: return BO_EQ; 2071 case OO_ExclaimEqual: return BO_NE; 2072 case OO_LessEqual: return BO_LE; 2073 case OO_GreaterEqual: return BO_GE; 2074 case OO_AmpAmp: return BO_LAnd; 2075 case OO_PipePipe: return BO_LOr; 2076 case OO_Comma: return BO_Comma; 2077 case OO_ArrowStar: return BO_PtrMemI; 2078 } 2079 } 2080 2081 OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) { 2082 static const OverloadedOperatorKind OverOps[] = { 2083 /* .* Cannot be overloaded */OO_None, OO_ArrowStar, 2084 OO_Star, OO_Slash, OO_Percent, 2085 OO_Plus, OO_Minus, 2086 OO_LessLess, OO_GreaterGreater, 2087 OO_Spaceship, 2088 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual, 2089 OO_EqualEqual, OO_ExclaimEqual, 2090 OO_Amp, 2091 OO_Caret, 2092 OO_Pipe, 2093 OO_AmpAmp, 2094 OO_PipePipe, 2095 OO_Equal, OO_StarEqual, 2096 OO_SlashEqual, OO_PercentEqual, 2097 OO_PlusEqual, OO_MinusEqual, 2098 OO_LessLessEqual, OO_GreaterGreaterEqual, 2099 OO_AmpEqual, OO_CaretEqual, 2100 OO_PipeEqual, 2101 OO_Comma 2102 }; 2103 return OverOps[Opc]; 2104 } 2105 2106 bool BinaryOperator::isNullPointerArithmeticExtension(ASTContext &Ctx, 2107 Opcode Opc, 2108 Expr *LHS, Expr *RHS) { 2109 if (Opc != BO_Add) 2110 return false; 2111 2112 // Check that we have one pointer and one integer operand. 2113 Expr *PExp; 2114 if (LHS->getType()->isPointerType()) { 2115 if (!RHS->getType()->isIntegerType()) 2116 return false; 2117 PExp = LHS; 2118 } else if (RHS->getType()->isPointerType()) { 2119 if (!LHS->getType()->isIntegerType()) 2120 return false; 2121 PExp = RHS; 2122 } else { 2123 return false; 2124 } 2125 2126 // Check that the pointer is a nullptr. 2127 if (!PExp->IgnoreParenCasts() 2128 ->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull)) 2129 return false; 2130 2131 // Check that the pointee type is char-sized. 2132 const PointerType *PTy = PExp->getType()->getAs<PointerType>(); 2133 if (!PTy || !PTy->getPointeeType()->isCharType()) 2134 return false; 2135 2136 return true; 2137 } 2138 2139 static QualType getDecayedSourceLocExprType(const ASTContext &Ctx, 2140 SourceLocExpr::IdentKind Kind) { 2141 switch (Kind) { 2142 case SourceLocExpr::File: 2143 case SourceLocExpr::Function: { 2144 QualType ArrTy = Ctx.getStringLiteralArrayType(Ctx.CharTy, 0); 2145 return Ctx.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType()); 2146 } 2147 case SourceLocExpr::Line: 2148 case SourceLocExpr::Column: 2149 return Ctx.UnsignedIntTy; 2150 } 2151 llvm_unreachable("unhandled case"); 2152 } 2153 2154 SourceLocExpr::SourceLocExpr(const ASTContext &Ctx, IdentKind Kind, 2155 SourceLocation BLoc, SourceLocation RParenLoc, 2156 DeclContext *ParentContext) 2157 : Expr(SourceLocExprClass, getDecayedSourceLocExprType(Ctx, Kind), 2158 VK_PRValue, OK_Ordinary), 2159 BuiltinLoc(BLoc), RParenLoc(RParenLoc), ParentContext(ParentContext) { 2160 SourceLocExprBits.Kind = Kind; 2161 setDependence(ExprDependence::None); 2162 } 2163 2164 StringRef SourceLocExpr::getBuiltinStr() const { 2165 switch (getIdentKind()) { 2166 case File: 2167 return "__builtin_FILE"; 2168 case Function: 2169 return "__builtin_FUNCTION"; 2170 case Line: 2171 return "__builtin_LINE"; 2172 case Column: 2173 return "__builtin_COLUMN"; 2174 } 2175 llvm_unreachable("unexpected IdentKind!"); 2176 } 2177 2178 APValue SourceLocExpr::EvaluateInContext(const ASTContext &Ctx, 2179 const Expr *DefaultExpr) const { 2180 SourceLocation Loc; 2181 const DeclContext *Context; 2182 2183 std::tie(Loc, 2184 Context) = [&]() -> std::pair<SourceLocation, const DeclContext *> { 2185 if (auto *DIE = dyn_cast_or_null<CXXDefaultInitExpr>(DefaultExpr)) 2186 return {DIE->getUsedLocation(), DIE->getUsedContext()}; 2187 if (auto *DAE = dyn_cast_or_null<CXXDefaultArgExpr>(DefaultExpr)) 2188 return {DAE->getUsedLocation(), DAE->getUsedContext()}; 2189 return {this->getLocation(), this->getParentContext()}; 2190 }(); 2191 2192 PresumedLoc PLoc = Ctx.getSourceManager().getPresumedLoc( 2193 Ctx.getSourceManager().getExpansionRange(Loc).getEnd()); 2194 2195 auto MakeStringLiteral = [&](StringRef Tmp) { 2196 using LValuePathEntry = APValue::LValuePathEntry; 2197 StringLiteral *Res = Ctx.getPredefinedStringLiteralFromCache(Tmp); 2198 // Decay the string to a pointer to the first character. 2199 LValuePathEntry Path[1] = {LValuePathEntry::ArrayIndex(0)}; 2200 return APValue(Res, CharUnits::Zero(), Path, /*OnePastTheEnd=*/false); 2201 }; 2202 2203 switch (getIdentKind()) { 2204 case SourceLocExpr::File: { 2205 SmallString<256> Path(PLoc.getFilename()); 2206 Ctx.getLangOpts().remapPathPrefix(Path); 2207 return MakeStringLiteral(Path); 2208 } 2209 case SourceLocExpr::Function: { 2210 const Decl *CurDecl = dyn_cast_or_null<Decl>(Context); 2211 return MakeStringLiteral( 2212 CurDecl ? PredefinedExpr::ComputeName(PredefinedExpr::Function, CurDecl) 2213 : std::string("")); 2214 } 2215 case SourceLocExpr::Line: 2216 case SourceLocExpr::Column: { 2217 llvm::APSInt IntVal(Ctx.getIntWidth(Ctx.UnsignedIntTy), 2218 /*isUnsigned=*/true); 2219 IntVal = getIdentKind() == SourceLocExpr::Line ? PLoc.getLine() 2220 : PLoc.getColumn(); 2221 return APValue(IntVal); 2222 } 2223 } 2224 llvm_unreachable("unhandled case"); 2225 } 2226 2227 InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc, 2228 ArrayRef<Expr *> initExprs, SourceLocation rbraceloc) 2229 : Expr(InitListExprClass, QualType(), VK_PRValue, OK_Ordinary), 2230 InitExprs(C, initExprs.size()), LBraceLoc(lbraceloc), 2231 RBraceLoc(rbraceloc), AltForm(nullptr, true) { 2232 sawArrayRangeDesignator(false); 2233 InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end()); 2234 2235 setDependence(computeDependence(this)); 2236 } 2237 2238 void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) { 2239 if (NumInits > InitExprs.size()) 2240 InitExprs.reserve(C, NumInits); 2241 } 2242 2243 void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) { 2244 InitExprs.resize(C, NumInits, nullptr); 2245 } 2246 2247 Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) { 2248 if (Init >= InitExprs.size()) { 2249 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr); 2250 setInit(Init, expr); 2251 return nullptr; 2252 } 2253 2254 Expr *Result = cast_or_null<Expr>(InitExprs[Init]); 2255 setInit(Init, expr); 2256 return Result; 2257 } 2258 2259 void InitListExpr::setArrayFiller(Expr *filler) { 2260 assert(!hasArrayFiller() && "Filler already set!"); 2261 ArrayFillerOrUnionFieldInit = filler; 2262 // Fill out any "holes" in the array due to designated initializers. 2263 Expr **inits = getInits(); 2264 for (unsigned i = 0, e = getNumInits(); i != e; ++i) 2265 if (inits[i] == nullptr) 2266 inits[i] = filler; 2267 } 2268 2269 bool InitListExpr::isStringLiteralInit() const { 2270 if (getNumInits() != 1) 2271 return false; 2272 const ArrayType *AT = getType()->getAsArrayTypeUnsafe(); 2273 if (!AT || !AT->getElementType()->isIntegerType()) 2274 return false; 2275 // It is possible for getInit() to return null. 2276 const Expr *Init = getInit(0); 2277 if (!Init) 2278 return false; 2279 Init = Init->IgnoreParenImpCasts(); 2280 return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init); 2281 } 2282 2283 bool InitListExpr::isTransparent() const { 2284 assert(isSemanticForm() && "syntactic form never semantically transparent"); 2285 2286 // A glvalue InitListExpr is always just sugar. 2287 if (isGLValue()) { 2288 assert(getNumInits() == 1 && "multiple inits in glvalue init list"); 2289 return true; 2290 } 2291 2292 // Otherwise, we're sugar if and only if we have exactly one initializer that 2293 // is of the same type. 2294 if (getNumInits() != 1 || !getInit(0)) 2295 return false; 2296 2297 // Don't confuse aggregate initialization of a struct X { X &x; }; with a 2298 // transparent struct copy. 2299 if (!getInit(0)->isPRValue() && getType()->isRecordType()) 2300 return false; 2301 2302 return getType().getCanonicalType() == 2303 getInit(0)->getType().getCanonicalType(); 2304 } 2305 2306 bool InitListExpr::isIdiomaticZeroInitializer(const LangOptions &LangOpts) const { 2307 assert(isSyntacticForm() && "only test syntactic form as zero initializer"); 2308 2309 if (LangOpts.CPlusPlus || getNumInits() != 1 || !getInit(0)) { 2310 return false; 2311 } 2312 2313 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(getInit(0)->IgnoreImplicit()); 2314 return Lit && Lit->getValue() == 0; 2315 } 2316 2317 SourceLocation InitListExpr::getBeginLoc() const { 2318 if (InitListExpr *SyntacticForm = getSyntacticForm()) 2319 return SyntacticForm->getBeginLoc(); 2320 SourceLocation Beg = LBraceLoc; 2321 if (Beg.isInvalid()) { 2322 // Find the first non-null initializer. 2323 for (InitExprsTy::const_iterator I = InitExprs.begin(), 2324 E = InitExprs.end(); 2325 I != E; ++I) { 2326 if (Stmt *S = *I) { 2327 Beg = S->getBeginLoc(); 2328 break; 2329 } 2330 } 2331 } 2332 return Beg; 2333 } 2334 2335 SourceLocation InitListExpr::getEndLoc() const { 2336 if (InitListExpr *SyntacticForm = getSyntacticForm()) 2337 return SyntacticForm->getEndLoc(); 2338 SourceLocation End = RBraceLoc; 2339 if (End.isInvalid()) { 2340 // Find the first non-null initializer from the end. 2341 for (Stmt *S : llvm::reverse(InitExprs)) { 2342 if (S) { 2343 End = S->getEndLoc(); 2344 break; 2345 } 2346 } 2347 } 2348 return End; 2349 } 2350 2351 /// getFunctionType - Return the underlying function type for this block. 2352 /// 2353 const FunctionProtoType *BlockExpr::getFunctionType() const { 2354 // The block pointer is never sugared, but the function type might be. 2355 return cast<BlockPointerType>(getType()) 2356 ->getPointeeType()->castAs<FunctionProtoType>(); 2357 } 2358 2359 SourceLocation BlockExpr::getCaretLocation() const { 2360 return TheBlock->getCaretLocation(); 2361 } 2362 const Stmt *BlockExpr::getBody() const { 2363 return TheBlock->getBody(); 2364 } 2365 Stmt *BlockExpr::getBody() { 2366 return TheBlock->getBody(); 2367 } 2368 2369 2370 //===----------------------------------------------------------------------===// 2371 // Generic Expression Routines 2372 //===----------------------------------------------------------------------===// 2373 2374 bool Expr::isReadIfDiscardedInCPlusPlus11() const { 2375 // In C++11, discarded-value expressions of a certain form are special, 2376 // according to [expr]p10: 2377 // The lvalue-to-rvalue conversion (4.1) is applied only if the 2378 // expression is a glvalue of volatile-qualified type and it has 2379 // one of the following forms: 2380 if (!isGLValue() || !getType().isVolatileQualified()) 2381 return false; 2382 2383 const Expr *E = IgnoreParens(); 2384 2385 // - id-expression (5.1.1), 2386 if (isa<DeclRefExpr>(E)) 2387 return true; 2388 2389 // - subscripting (5.2.1), 2390 if (isa<ArraySubscriptExpr>(E)) 2391 return true; 2392 2393 // - class member access (5.2.5), 2394 if (isa<MemberExpr>(E)) 2395 return true; 2396 2397 // - indirection (5.3.1), 2398 if (auto *UO = dyn_cast<UnaryOperator>(E)) 2399 if (UO->getOpcode() == UO_Deref) 2400 return true; 2401 2402 if (auto *BO = dyn_cast<BinaryOperator>(E)) { 2403 // - pointer-to-member operation (5.5), 2404 if (BO->isPtrMemOp()) 2405 return true; 2406 2407 // - comma expression (5.18) where the right operand is one of the above. 2408 if (BO->getOpcode() == BO_Comma) 2409 return BO->getRHS()->isReadIfDiscardedInCPlusPlus11(); 2410 } 2411 2412 // - conditional expression (5.16) where both the second and the third 2413 // operands are one of the above, or 2414 if (auto *CO = dyn_cast<ConditionalOperator>(E)) 2415 return CO->getTrueExpr()->isReadIfDiscardedInCPlusPlus11() && 2416 CO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11(); 2417 // The related edge case of "*x ?: *x". 2418 if (auto *BCO = 2419 dyn_cast<BinaryConditionalOperator>(E)) { 2420 if (auto *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr())) 2421 return OVE->getSourceExpr()->isReadIfDiscardedInCPlusPlus11() && 2422 BCO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11(); 2423 } 2424 2425 // Objective-C++ extensions to the rule. 2426 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E)) 2427 return true; 2428 2429 return false; 2430 } 2431 2432 /// isUnusedResultAWarning - Return true if this immediate expression should 2433 /// be warned about if the result is unused. If so, fill in Loc and Ranges 2434 /// with location to warn on and the source range[s] to report with the 2435 /// warning. 2436 bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc, 2437 SourceRange &R1, SourceRange &R2, 2438 ASTContext &Ctx) const { 2439 // Don't warn if the expr is type dependent. The type could end up 2440 // instantiating to void. 2441 if (isTypeDependent()) 2442 return false; 2443 2444 switch (getStmtClass()) { 2445 default: 2446 if (getType()->isVoidType()) 2447 return false; 2448 WarnE = this; 2449 Loc = getExprLoc(); 2450 R1 = getSourceRange(); 2451 return true; 2452 case ParenExprClass: 2453 return cast<ParenExpr>(this)->getSubExpr()-> 2454 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); 2455 case GenericSelectionExprClass: 2456 return cast<GenericSelectionExpr>(this)->getResultExpr()-> 2457 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); 2458 case CoawaitExprClass: 2459 case CoyieldExprClass: 2460 return cast<CoroutineSuspendExpr>(this)->getResumeExpr()-> 2461 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); 2462 case ChooseExprClass: 2463 return cast<ChooseExpr>(this)->getChosenSubExpr()-> 2464 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); 2465 case UnaryOperatorClass: { 2466 const UnaryOperator *UO = cast<UnaryOperator>(this); 2467 2468 switch (UO->getOpcode()) { 2469 case UO_Plus: 2470 case UO_Minus: 2471 case UO_AddrOf: 2472 case UO_Not: 2473 case UO_LNot: 2474 case UO_Deref: 2475 break; 2476 case UO_Coawait: 2477 // This is just the 'operator co_await' call inside the guts of a 2478 // dependent co_await call. 2479 case UO_PostInc: 2480 case UO_PostDec: 2481 case UO_PreInc: 2482 case UO_PreDec: // ++/-- 2483 return false; // Not a warning. 2484 case UO_Real: 2485 case UO_Imag: 2486 // accessing a piece of a volatile complex is a side-effect. 2487 if (Ctx.getCanonicalType(UO->getSubExpr()->getType()) 2488 .isVolatileQualified()) 2489 return false; 2490 break; 2491 case UO_Extension: 2492 return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); 2493 } 2494 WarnE = this; 2495 Loc = UO->getOperatorLoc(); 2496 R1 = UO->getSubExpr()->getSourceRange(); 2497 return true; 2498 } 2499 case BinaryOperatorClass: { 2500 const BinaryOperator *BO = cast<BinaryOperator>(this); 2501 switch (BO->getOpcode()) { 2502 default: 2503 break; 2504 // Consider the RHS of comma for side effects. LHS was checked by 2505 // Sema::CheckCommaOperands. 2506 case BO_Comma: 2507 // ((foo = <blah>), 0) is an idiom for hiding the result (and 2508 // lvalue-ness) of an assignment written in a macro. 2509 if (IntegerLiteral *IE = 2510 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens())) 2511 if (IE->getValue() == 0) 2512 return false; 2513 return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); 2514 // Consider '||', '&&' to have side effects if the LHS or RHS does. 2515 case BO_LAnd: 2516 case BO_LOr: 2517 if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) || 2518 !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx)) 2519 return false; 2520 break; 2521 } 2522 if (BO->isAssignmentOp()) 2523 return false; 2524 WarnE = this; 2525 Loc = BO->getOperatorLoc(); 2526 R1 = BO->getLHS()->getSourceRange(); 2527 R2 = BO->getRHS()->getSourceRange(); 2528 return true; 2529 } 2530 case CompoundAssignOperatorClass: 2531 case VAArgExprClass: 2532 case AtomicExprClass: 2533 return false; 2534 2535 case ConditionalOperatorClass: { 2536 // If only one of the LHS or RHS is a warning, the operator might 2537 // be being used for control flow. Only warn if both the LHS and 2538 // RHS are warnings. 2539 const auto *Exp = cast<ConditionalOperator>(this); 2540 return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) && 2541 Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); 2542 } 2543 case BinaryConditionalOperatorClass: { 2544 const auto *Exp = cast<BinaryConditionalOperator>(this); 2545 return Exp->getFalseExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); 2546 } 2547 2548 case MemberExprClass: 2549 WarnE = this; 2550 Loc = cast<MemberExpr>(this)->getMemberLoc(); 2551 R1 = SourceRange(Loc, Loc); 2552 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange(); 2553 return true; 2554 2555 case ArraySubscriptExprClass: 2556 WarnE = this; 2557 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc(); 2558 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange(); 2559 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange(); 2560 return true; 2561 2562 case CXXOperatorCallExprClass: { 2563 // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator 2564 // overloads as there is no reasonable way to define these such that they 2565 // have non-trivial, desirable side-effects. See the -Wunused-comparison 2566 // warning: operators == and != are commonly typo'ed, and so warning on them 2567 // provides additional value as well. If this list is updated, 2568 // DiagnoseUnusedComparison should be as well. 2569 const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this); 2570 switch (Op->getOperator()) { 2571 default: 2572 break; 2573 case OO_EqualEqual: 2574 case OO_ExclaimEqual: 2575 case OO_Less: 2576 case OO_Greater: 2577 case OO_GreaterEqual: 2578 case OO_LessEqual: 2579 if (Op->getCallReturnType(Ctx)->isReferenceType() || 2580 Op->getCallReturnType(Ctx)->isVoidType()) 2581 break; 2582 WarnE = this; 2583 Loc = Op->getOperatorLoc(); 2584 R1 = Op->getSourceRange(); 2585 return true; 2586 } 2587 2588 // Fallthrough for generic call handling. 2589 LLVM_FALLTHROUGH; 2590 } 2591 case CallExprClass: 2592 case CXXMemberCallExprClass: 2593 case UserDefinedLiteralClass: { 2594 // If this is a direct call, get the callee. 2595 const CallExpr *CE = cast<CallExpr>(this); 2596 if (const Decl *FD = CE->getCalleeDecl()) { 2597 // If the callee has attribute pure, const, or warn_unused_result, warn 2598 // about it. void foo() { strlen("bar"); } should warn. 2599 // 2600 // Note: If new cases are added here, DiagnoseUnusedExprResult should be 2601 // updated to match for QoI. 2602 if (CE->hasUnusedResultAttr(Ctx) || 2603 FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) { 2604 WarnE = this; 2605 Loc = CE->getCallee()->getBeginLoc(); 2606 R1 = CE->getCallee()->getSourceRange(); 2607 2608 if (unsigned NumArgs = CE->getNumArgs()) 2609 R2 = SourceRange(CE->getArg(0)->getBeginLoc(), 2610 CE->getArg(NumArgs - 1)->getEndLoc()); 2611 return true; 2612 } 2613 } 2614 return false; 2615 } 2616 2617 // If we don't know precisely what we're looking at, let's not warn. 2618 case UnresolvedLookupExprClass: 2619 case CXXUnresolvedConstructExprClass: 2620 case RecoveryExprClass: 2621 return false; 2622 2623 case CXXTemporaryObjectExprClass: 2624 case CXXConstructExprClass: { 2625 if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) { 2626 const auto *WarnURAttr = Type->getAttr<WarnUnusedResultAttr>(); 2627 if (Type->hasAttr<WarnUnusedAttr>() || 2628 (WarnURAttr && WarnURAttr->IsCXX11NoDiscard())) { 2629 WarnE = this; 2630 Loc = getBeginLoc(); 2631 R1 = getSourceRange(); 2632 return true; 2633 } 2634 } 2635 2636 const auto *CE = cast<CXXConstructExpr>(this); 2637 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) { 2638 const auto *WarnURAttr = Ctor->getAttr<WarnUnusedResultAttr>(); 2639 if (WarnURAttr && WarnURAttr->IsCXX11NoDiscard()) { 2640 WarnE = this; 2641 Loc = getBeginLoc(); 2642 R1 = getSourceRange(); 2643 2644 if (unsigned NumArgs = CE->getNumArgs()) 2645 R2 = SourceRange(CE->getArg(0)->getBeginLoc(), 2646 CE->getArg(NumArgs - 1)->getEndLoc()); 2647 return true; 2648 } 2649 } 2650 2651 return false; 2652 } 2653 2654 case ObjCMessageExprClass: { 2655 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this); 2656 if (Ctx.getLangOpts().ObjCAutoRefCount && 2657 ME->isInstanceMessage() && 2658 !ME->getType()->isVoidType() && 2659 ME->getMethodFamily() == OMF_init) { 2660 WarnE = this; 2661 Loc = getExprLoc(); 2662 R1 = ME->getSourceRange(); 2663 return true; 2664 } 2665 2666 if (const ObjCMethodDecl *MD = ME->getMethodDecl()) 2667 if (MD->hasAttr<WarnUnusedResultAttr>()) { 2668 WarnE = this; 2669 Loc = getExprLoc(); 2670 return true; 2671 } 2672 2673 return false; 2674 } 2675 2676 case ObjCPropertyRefExprClass: 2677 WarnE = this; 2678 Loc = getExprLoc(); 2679 R1 = getSourceRange(); 2680 return true; 2681 2682 case PseudoObjectExprClass: { 2683 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this); 2684 2685 // Only complain about things that have the form of a getter. 2686 if (isa<UnaryOperator>(PO->getSyntacticForm()) || 2687 isa<BinaryOperator>(PO->getSyntacticForm())) 2688 return false; 2689 2690 WarnE = this; 2691 Loc = getExprLoc(); 2692 R1 = getSourceRange(); 2693 return true; 2694 } 2695 2696 case StmtExprClass: { 2697 // Statement exprs don't logically have side effects themselves, but are 2698 // sometimes used in macros in ways that give them a type that is unused. 2699 // For example ({ blah; foo(); }) will end up with a type if foo has a type. 2700 // however, if the result of the stmt expr is dead, we don't want to emit a 2701 // warning. 2702 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt(); 2703 if (!CS->body_empty()) { 2704 if (const Expr *E = dyn_cast<Expr>(CS->body_back())) 2705 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); 2706 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back())) 2707 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt())) 2708 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); 2709 } 2710 2711 if (getType()->isVoidType()) 2712 return false; 2713 WarnE = this; 2714 Loc = cast<StmtExpr>(this)->getLParenLoc(); 2715 R1 = getSourceRange(); 2716 return true; 2717 } 2718 case CXXFunctionalCastExprClass: 2719 case CStyleCastExprClass: { 2720 // Ignore an explicit cast to void, except in C++98 if the operand is a 2721 // volatile glvalue for which we would trigger an implicit read in any 2722 // other language mode. (Such an implicit read always happens as part of 2723 // the lvalue conversion in C, and happens in C++ for expressions of all 2724 // forms where it seems likely the user intended to trigger a volatile 2725 // load.) 2726 const CastExpr *CE = cast<CastExpr>(this); 2727 const Expr *SubE = CE->getSubExpr()->IgnoreParens(); 2728 if (CE->getCastKind() == CK_ToVoid) { 2729 if (Ctx.getLangOpts().CPlusPlus && !Ctx.getLangOpts().CPlusPlus11 && 2730 SubE->isReadIfDiscardedInCPlusPlus11()) { 2731 // Suppress the "unused value" warning for idiomatic usage of 2732 // '(void)var;' used to suppress "unused variable" warnings. 2733 if (auto *DRE = dyn_cast<DeclRefExpr>(SubE)) 2734 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 2735 if (!VD->isExternallyVisible()) 2736 return false; 2737 2738 // The lvalue-to-rvalue conversion would have no effect for an array. 2739 // It's implausible that the programmer expected this to result in a 2740 // volatile array load, so don't warn. 2741 if (SubE->getType()->isArrayType()) 2742 return false; 2743 2744 return SubE->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); 2745 } 2746 return false; 2747 } 2748 2749 // If this is a cast to a constructor conversion, check the operand. 2750 // Otherwise, the result of the cast is unused. 2751 if (CE->getCastKind() == CK_ConstructorConversion) 2752 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); 2753 if (CE->getCastKind() == CK_Dependent) 2754 return false; 2755 2756 WarnE = this; 2757 if (const CXXFunctionalCastExpr *CXXCE = 2758 dyn_cast<CXXFunctionalCastExpr>(this)) { 2759 Loc = CXXCE->getBeginLoc(); 2760 R1 = CXXCE->getSubExpr()->getSourceRange(); 2761 } else { 2762 const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this); 2763 Loc = CStyleCE->getLParenLoc(); 2764 R1 = CStyleCE->getSubExpr()->getSourceRange(); 2765 } 2766 return true; 2767 } 2768 case ImplicitCastExprClass: { 2769 const CastExpr *ICE = cast<ImplicitCastExpr>(this); 2770 2771 // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect. 2772 if (ICE->getCastKind() == CK_LValueToRValue && 2773 ICE->getSubExpr()->getType().isVolatileQualified()) 2774 return false; 2775 2776 return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); 2777 } 2778 case CXXDefaultArgExprClass: 2779 return (cast<CXXDefaultArgExpr>(this) 2780 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx)); 2781 case CXXDefaultInitExprClass: 2782 return (cast<CXXDefaultInitExpr>(this) 2783 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx)); 2784 2785 case CXXNewExprClass: 2786 // FIXME: In theory, there might be new expressions that don't have side 2787 // effects (e.g. a placement new with an uninitialized POD). 2788 case CXXDeleteExprClass: 2789 return false; 2790 case MaterializeTemporaryExprClass: 2791 return cast<MaterializeTemporaryExpr>(this) 2792 ->getSubExpr() 2793 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); 2794 case CXXBindTemporaryExprClass: 2795 return cast<CXXBindTemporaryExpr>(this)->getSubExpr() 2796 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); 2797 case ExprWithCleanupsClass: 2798 return cast<ExprWithCleanups>(this)->getSubExpr() 2799 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); 2800 } 2801 } 2802 2803 /// isOBJCGCCandidate - Check if an expression is objc gc'able. 2804 /// returns true, if it is; false otherwise. 2805 bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const { 2806 const Expr *E = IgnoreParens(); 2807 switch (E->getStmtClass()) { 2808 default: 2809 return false; 2810 case ObjCIvarRefExprClass: 2811 return true; 2812 case Expr::UnaryOperatorClass: 2813 return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx); 2814 case ImplicitCastExprClass: 2815 return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx); 2816 case MaterializeTemporaryExprClass: 2817 return cast<MaterializeTemporaryExpr>(E)->getSubExpr()->isOBJCGCCandidate( 2818 Ctx); 2819 case CStyleCastExprClass: 2820 return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx); 2821 case DeclRefExprClass: { 2822 const Decl *D = cast<DeclRefExpr>(E)->getDecl(); 2823 2824 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2825 if (VD->hasGlobalStorage()) 2826 return true; 2827 QualType T = VD->getType(); 2828 // dereferencing to a pointer is always a gc'able candidate, 2829 // unless it is __weak. 2830 return T->isPointerType() && 2831 (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak); 2832 } 2833 return false; 2834 } 2835 case MemberExprClass: { 2836 const MemberExpr *M = cast<MemberExpr>(E); 2837 return M->getBase()->isOBJCGCCandidate(Ctx); 2838 } 2839 case ArraySubscriptExprClass: 2840 return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx); 2841 } 2842 } 2843 2844 bool Expr::isBoundMemberFunction(ASTContext &Ctx) const { 2845 if (isTypeDependent()) 2846 return false; 2847 return ClassifyLValue(Ctx) == Expr::LV_MemberFunction; 2848 } 2849 2850 QualType Expr::findBoundMemberType(const Expr *expr) { 2851 assert(expr->hasPlaceholderType(BuiltinType::BoundMember)); 2852 2853 // Bound member expressions are always one of these possibilities: 2854 // x->m x.m x->*y x.*y 2855 // (possibly parenthesized) 2856 2857 expr = expr->IgnoreParens(); 2858 if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) { 2859 assert(isa<CXXMethodDecl>(mem->getMemberDecl())); 2860 return mem->getMemberDecl()->getType(); 2861 } 2862 2863 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) { 2864 QualType type = op->getRHS()->getType()->castAs<MemberPointerType>() 2865 ->getPointeeType(); 2866 assert(type->isFunctionType()); 2867 return type; 2868 } 2869 2870 assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr)); 2871 return QualType(); 2872 } 2873 2874 Expr *Expr::IgnoreImpCasts() { 2875 return IgnoreExprNodes(this, IgnoreImplicitCastsSingleStep); 2876 } 2877 2878 Expr *Expr::IgnoreCasts() { 2879 return IgnoreExprNodes(this, IgnoreCastsSingleStep); 2880 } 2881 2882 Expr *Expr::IgnoreImplicit() { 2883 return IgnoreExprNodes(this, IgnoreImplicitSingleStep); 2884 } 2885 2886 Expr *Expr::IgnoreImplicitAsWritten() { 2887 return IgnoreExprNodes(this, IgnoreImplicitAsWrittenSingleStep); 2888 } 2889 2890 Expr *Expr::IgnoreParens() { 2891 return IgnoreExprNodes(this, IgnoreParensSingleStep); 2892 } 2893 2894 Expr *Expr::IgnoreParenImpCasts() { 2895 return IgnoreExprNodes(this, IgnoreParensSingleStep, 2896 IgnoreImplicitCastsExtraSingleStep); 2897 } 2898 2899 Expr *Expr::IgnoreParenCasts() { 2900 return IgnoreExprNodes(this, IgnoreParensSingleStep, IgnoreCastsSingleStep); 2901 } 2902 2903 Expr *Expr::IgnoreConversionOperatorSingleStep() { 2904 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(this)) { 2905 if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl())) 2906 return MCE->getImplicitObjectArgument(); 2907 } 2908 return this; 2909 } 2910 2911 Expr *Expr::IgnoreParenLValueCasts() { 2912 return IgnoreExprNodes(this, IgnoreParensSingleStep, 2913 IgnoreLValueCastsSingleStep); 2914 } 2915 2916 Expr *Expr::IgnoreParenBaseCasts() { 2917 return IgnoreExprNodes(this, IgnoreParensSingleStep, 2918 IgnoreBaseCastsSingleStep); 2919 } 2920 2921 Expr *Expr::IgnoreParenNoopCasts(const ASTContext &Ctx) { 2922 auto IgnoreNoopCastsSingleStep = [&Ctx](Expr *E) { 2923 if (auto *CE = dyn_cast<CastExpr>(E)) { 2924 // We ignore integer <-> casts that are of the same width, ptr<->ptr and 2925 // ptr<->int casts of the same width. We also ignore all identity casts. 2926 Expr *SubExpr = CE->getSubExpr(); 2927 bool IsIdentityCast = 2928 Ctx.hasSameUnqualifiedType(E->getType(), SubExpr->getType()); 2929 bool IsSameWidthCast = (E->getType()->isPointerType() || 2930 E->getType()->isIntegralType(Ctx)) && 2931 (SubExpr->getType()->isPointerType() || 2932 SubExpr->getType()->isIntegralType(Ctx)) && 2933 (Ctx.getTypeSize(E->getType()) == 2934 Ctx.getTypeSize(SubExpr->getType())); 2935 2936 if (IsIdentityCast || IsSameWidthCast) 2937 return SubExpr; 2938 } else if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) 2939 return NTTP->getReplacement(); 2940 2941 return E; 2942 }; 2943 return IgnoreExprNodes(this, IgnoreParensSingleStep, 2944 IgnoreNoopCastsSingleStep); 2945 } 2946 2947 Expr *Expr::IgnoreUnlessSpelledInSource() { 2948 auto IgnoreImplicitConstructorSingleStep = [](Expr *E) { 2949 if (auto *Cast = dyn_cast<CXXFunctionalCastExpr>(E)) { 2950 auto *SE = Cast->getSubExpr(); 2951 if (SE->getSourceRange() == E->getSourceRange()) 2952 return SE; 2953 } 2954 2955 if (auto *C = dyn_cast<CXXConstructExpr>(E)) { 2956 auto NumArgs = C->getNumArgs(); 2957 if (NumArgs == 1 || 2958 (NumArgs > 1 && isa<CXXDefaultArgExpr>(C->getArg(1)))) { 2959 Expr *A = C->getArg(0); 2960 if (A->getSourceRange() == E->getSourceRange() || C->isElidable()) 2961 return A; 2962 } 2963 } 2964 return E; 2965 }; 2966 auto IgnoreImplicitMemberCallSingleStep = [](Expr *E) { 2967 if (auto *C = dyn_cast<CXXMemberCallExpr>(E)) { 2968 Expr *ExprNode = C->getImplicitObjectArgument(); 2969 if (ExprNode->getSourceRange() == E->getSourceRange()) { 2970 return ExprNode; 2971 } 2972 if (auto *PE = dyn_cast<ParenExpr>(ExprNode)) { 2973 if (PE->getSourceRange() == C->getSourceRange()) { 2974 return cast<Expr>(PE); 2975 } 2976 } 2977 ExprNode = ExprNode->IgnoreParenImpCasts(); 2978 if (ExprNode->getSourceRange() == E->getSourceRange()) 2979 return ExprNode; 2980 } 2981 return E; 2982 }; 2983 return IgnoreExprNodes( 2984 this, IgnoreImplicitSingleStep, IgnoreImplicitCastsExtraSingleStep, 2985 IgnoreParensOnlySingleStep, IgnoreImplicitConstructorSingleStep, 2986 IgnoreImplicitMemberCallSingleStep); 2987 } 2988 2989 bool Expr::isDefaultArgument() const { 2990 const Expr *E = this; 2991 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E)) 2992 E = M->getSubExpr(); 2993 2994 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 2995 E = ICE->getSubExprAsWritten(); 2996 2997 return isa<CXXDefaultArgExpr>(E); 2998 } 2999 3000 /// Skip over any no-op casts and any temporary-binding 3001 /// expressions. 3002 static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) { 3003 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E)) 3004 E = M->getSubExpr(); 3005 3006 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 3007 if (ICE->getCastKind() == CK_NoOp) 3008 E = ICE->getSubExpr(); 3009 else 3010 break; 3011 } 3012 3013 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E)) 3014 E = BE->getSubExpr(); 3015 3016 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 3017 if (ICE->getCastKind() == CK_NoOp) 3018 E = ICE->getSubExpr(); 3019 else 3020 break; 3021 } 3022 3023 return E->IgnoreParens(); 3024 } 3025 3026 /// isTemporaryObject - Determines if this expression produces a 3027 /// temporary of the given class type. 3028 bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const { 3029 if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy))) 3030 return false; 3031 3032 const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this); 3033 3034 // Temporaries are by definition pr-values of class type. 3035 if (!E->Classify(C).isPRValue()) { 3036 // In this context, property reference is a message call and is pr-value. 3037 if (!isa<ObjCPropertyRefExpr>(E)) 3038 return false; 3039 } 3040 3041 // Black-list a few cases which yield pr-values of class type that don't 3042 // refer to temporaries of that type: 3043 3044 // - implicit derived-to-base conversions 3045 if (isa<ImplicitCastExpr>(E)) { 3046 switch (cast<ImplicitCastExpr>(E)->getCastKind()) { 3047 case CK_DerivedToBase: 3048 case CK_UncheckedDerivedToBase: 3049 return false; 3050 default: 3051 break; 3052 } 3053 } 3054 3055 // - member expressions (all) 3056 if (isa<MemberExpr>(E)) 3057 return false; 3058 3059 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) 3060 if (BO->isPtrMemOp()) 3061 return false; 3062 3063 // - opaque values (all) 3064 if (isa<OpaqueValueExpr>(E)) 3065 return false; 3066 3067 return true; 3068 } 3069 3070 bool Expr::isImplicitCXXThis() const { 3071 const Expr *E = this; 3072 3073 // Strip away parentheses and casts we don't care about. 3074 while (true) { 3075 if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) { 3076 E = Paren->getSubExpr(); 3077 continue; 3078 } 3079 3080 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 3081 if (ICE->getCastKind() == CK_NoOp || 3082 ICE->getCastKind() == CK_LValueToRValue || 3083 ICE->getCastKind() == CK_DerivedToBase || 3084 ICE->getCastKind() == CK_UncheckedDerivedToBase) { 3085 E = ICE->getSubExpr(); 3086 continue; 3087 } 3088 } 3089 3090 if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) { 3091 if (UnOp->getOpcode() == UO_Extension) { 3092 E = UnOp->getSubExpr(); 3093 continue; 3094 } 3095 } 3096 3097 if (const MaterializeTemporaryExpr *M 3098 = dyn_cast<MaterializeTemporaryExpr>(E)) { 3099 E = M->getSubExpr(); 3100 continue; 3101 } 3102 3103 break; 3104 } 3105 3106 if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E)) 3107 return This->isImplicit(); 3108 3109 return false; 3110 } 3111 3112 /// hasAnyTypeDependentArguments - Determines if any of the expressions 3113 /// in Exprs is type-dependent. 3114 bool Expr::hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs) { 3115 for (unsigned I = 0; I < Exprs.size(); ++I) 3116 if (Exprs[I]->isTypeDependent()) 3117 return true; 3118 3119 return false; 3120 } 3121 3122 bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef, 3123 const Expr **Culprit) const { 3124 assert(!isValueDependent() && 3125 "Expression evaluator can't be called on a dependent expression."); 3126 3127 // This function is attempting whether an expression is an initializer 3128 // which can be evaluated at compile-time. It very closely parallels 3129 // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it 3130 // will lead to unexpected results. Like ConstExprEmitter, it falls back 3131 // to isEvaluatable most of the time. 3132 // 3133 // If we ever capture reference-binding directly in the AST, we can 3134 // kill the second parameter. 3135 3136 if (IsForRef) { 3137 EvalResult Result; 3138 if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects) 3139 return true; 3140 if (Culprit) 3141 *Culprit = this; 3142 return false; 3143 } 3144 3145 switch (getStmtClass()) { 3146 default: break; 3147 case Stmt::ExprWithCleanupsClass: 3148 return cast<ExprWithCleanups>(this)->getSubExpr()->isConstantInitializer( 3149 Ctx, IsForRef, Culprit); 3150 case StringLiteralClass: 3151 case ObjCEncodeExprClass: 3152 return true; 3153 case CXXTemporaryObjectExprClass: 3154 case CXXConstructExprClass: { 3155 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this); 3156 3157 if (CE->getConstructor()->isTrivial() && 3158 CE->getConstructor()->getParent()->hasTrivialDestructor()) { 3159 // Trivial default constructor 3160 if (!CE->getNumArgs()) return true; 3161 3162 // Trivial copy constructor 3163 assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument"); 3164 return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit); 3165 } 3166 3167 break; 3168 } 3169 case ConstantExprClass: { 3170 // FIXME: We should be able to return "true" here, but it can lead to extra 3171 // error messages. E.g. in Sema/array-init.c. 3172 const Expr *Exp = cast<ConstantExpr>(this)->getSubExpr(); 3173 return Exp->isConstantInitializer(Ctx, false, Culprit); 3174 } 3175 case CompoundLiteralExprClass: { 3176 // This handles gcc's extension that allows global initializers like 3177 // "struct x {int x;} x = (struct x) {};". 3178 // FIXME: This accepts other cases it shouldn't! 3179 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer(); 3180 return Exp->isConstantInitializer(Ctx, false, Culprit); 3181 } 3182 case DesignatedInitUpdateExprClass: { 3183 const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this); 3184 return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) && 3185 DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit); 3186 } 3187 case InitListExprClass: { 3188 const InitListExpr *ILE = cast<InitListExpr>(this); 3189 assert(ILE->isSemanticForm() && "InitListExpr must be in semantic form"); 3190 if (ILE->getType()->isArrayType()) { 3191 unsigned numInits = ILE->getNumInits(); 3192 for (unsigned i = 0; i < numInits; i++) { 3193 if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit)) 3194 return false; 3195 } 3196 return true; 3197 } 3198 3199 if (ILE->getType()->isRecordType()) { 3200 unsigned ElementNo = 0; 3201 RecordDecl *RD = ILE->getType()->castAs<RecordType>()->getDecl(); 3202 for (const auto *Field : RD->fields()) { 3203 // If this is a union, skip all the fields that aren't being initialized. 3204 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field) 3205 continue; 3206 3207 // Don't emit anonymous bitfields, they just affect layout. 3208 if (Field->isUnnamedBitfield()) 3209 continue; 3210 3211 if (ElementNo < ILE->getNumInits()) { 3212 const Expr *Elt = ILE->getInit(ElementNo++); 3213 if (Field->isBitField()) { 3214 // Bitfields have to evaluate to an integer. 3215 EvalResult Result; 3216 if (!Elt->EvaluateAsInt(Result, Ctx)) { 3217 if (Culprit) 3218 *Culprit = Elt; 3219 return false; 3220 } 3221 } else { 3222 bool RefType = Field->getType()->isReferenceType(); 3223 if (!Elt->isConstantInitializer(Ctx, RefType, Culprit)) 3224 return false; 3225 } 3226 } 3227 } 3228 return true; 3229 } 3230 3231 break; 3232 } 3233 case ImplicitValueInitExprClass: 3234 case NoInitExprClass: 3235 return true; 3236 case ParenExprClass: 3237 return cast<ParenExpr>(this)->getSubExpr() 3238 ->isConstantInitializer(Ctx, IsForRef, Culprit); 3239 case GenericSelectionExprClass: 3240 return cast<GenericSelectionExpr>(this)->getResultExpr() 3241 ->isConstantInitializer(Ctx, IsForRef, Culprit); 3242 case ChooseExprClass: 3243 if (cast<ChooseExpr>(this)->isConditionDependent()) { 3244 if (Culprit) 3245 *Culprit = this; 3246 return false; 3247 } 3248 return cast<ChooseExpr>(this)->getChosenSubExpr() 3249 ->isConstantInitializer(Ctx, IsForRef, Culprit); 3250 case UnaryOperatorClass: { 3251 const UnaryOperator* Exp = cast<UnaryOperator>(this); 3252 if (Exp->getOpcode() == UO_Extension) 3253 return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit); 3254 break; 3255 } 3256 case CXXFunctionalCastExprClass: 3257 case CXXStaticCastExprClass: 3258 case ImplicitCastExprClass: 3259 case CStyleCastExprClass: 3260 case ObjCBridgedCastExprClass: 3261 case CXXDynamicCastExprClass: 3262 case CXXReinterpretCastExprClass: 3263 case CXXAddrspaceCastExprClass: 3264 case CXXConstCastExprClass: { 3265 const CastExpr *CE = cast<CastExpr>(this); 3266 3267 // Handle misc casts we want to ignore. 3268 if (CE->getCastKind() == CK_NoOp || 3269 CE->getCastKind() == CK_LValueToRValue || 3270 CE->getCastKind() == CK_ToUnion || 3271 CE->getCastKind() == CK_ConstructorConversion || 3272 CE->getCastKind() == CK_NonAtomicToAtomic || 3273 CE->getCastKind() == CK_AtomicToNonAtomic || 3274 CE->getCastKind() == CK_IntToOCLSampler) 3275 return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit); 3276 3277 break; 3278 } 3279 case MaterializeTemporaryExprClass: 3280 return cast<MaterializeTemporaryExpr>(this) 3281 ->getSubExpr() 3282 ->isConstantInitializer(Ctx, false, Culprit); 3283 3284 case SubstNonTypeTemplateParmExprClass: 3285 return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement() 3286 ->isConstantInitializer(Ctx, false, Culprit); 3287 case CXXDefaultArgExprClass: 3288 return cast<CXXDefaultArgExpr>(this)->getExpr() 3289 ->isConstantInitializer(Ctx, false, Culprit); 3290 case CXXDefaultInitExprClass: 3291 return cast<CXXDefaultInitExpr>(this)->getExpr() 3292 ->isConstantInitializer(Ctx, false, Culprit); 3293 } 3294 // Allow certain forms of UB in constant initializers: signed integer 3295 // overflow and floating-point division by zero. We'll give a warning on 3296 // these, but they're common enough that we have to accept them. 3297 if (isEvaluatable(Ctx, SE_AllowUndefinedBehavior)) 3298 return true; 3299 if (Culprit) 3300 *Culprit = this; 3301 return false; 3302 } 3303 3304 bool CallExpr::isBuiltinAssumeFalse(const ASTContext &Ctx) const { 3305 const FunctionDecl* FD = getDirectCallee(); 3306 if (!FD || (FD->getBuiltinID() != Builtin::BI__assume && 3307 FD->getBuiltinID() != Builtin::BI__builtin_assume)) 3308 return false; 3309 3310 const Expr* Arg = getArg(0); 3311 bool ArgVal; 3312 return !Arg->isValueDependent() && 3313 Arg->EvaluateAsBooleanCondition(ArgVal, Ctx) && !ArgVal; 3314 } 3315 3316 namespace { 3317 /// Look for any side effects within a Stmt. 3318 class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> { 3319 typedef ConstEvaluatedExprVisitor<SideEffectFinder> Inherited; 3320 const bool IncludePossibleEffects; 3321 bool HasSideEffects; 3322 3323 public: 3324 explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible) 3325 : Inherited(Context), 3326 IncludePossibleEffects(IncludePossible), HasSideEffects(false) { } 3327 3328 bool hasSideEffects() const { return HasSideEffects; } 3329 3330 void VisitDecl(const Decl *D) { 3331 if (!D) 3332 return; 3333 3334 // We assume the caller checks subexpressions (eg, the initializer, VLA 3335 // bounds) for side-effects on our behalf. 3336 if (auto *VD = dyn_cast<VarDecl>(D)) { 3337 // Registering a destructor is a side-effect. 3338 if (IncludePossibleEffects && VD->isThisDeclarationADefinition() && 3339 VD->needsDestruction(Context)) 3340 HasSideEffects = true; 3341 } 3342 } 3343 3344 void VisitDeclStmt(const DeclStmt *DS) { 3345 for (auto *D : DS->decls()) 3346 VisitDecl(D); 3347 Inherited::VisitDeclStmt(DS); 3348 } 3349 3350 void VisitExpr(const Expr *E) { 3351 if (!HasSideEffects && 3352 E->HasSideEffects(Context, IncludePossibleEffects)) 3353 HasSideEffects = true; 3354 } 3355 }; 3356 } 3357 3358 bool Expr::HasSideEffects(const ASTContext &Ctx, 3359 bool IncludePossibleEffects) const { 3360 // In circumstances where we care about definite side effects instead of 3361 // potential side effects, we want to ignore expressions that are part of a 3362 // macro expansion as a potential side effect. 3363 if (!IncludePossibleEffects && getExprLoc().isMacroID()) 3364 return false; 3365 3366 switch (getStmtClass()) { 3367 case NoStmtClass: 3368 #define ABSTRACT_STMT(Type) 3369 #define STMT(Type, Base) case Type##Class: 3370 #define EXPR(Type, Base) 3371 #include "clang/AST/StmtNodes.inc" 3372 llvm_unreachable("unexpected Expr kind"); 3373 3374 case DependentScopeDeclRefExprClass: 3375 case CXXUnresolvedConstructExprClass: 3376 case CXXDependentScopeMemberExprClass: 3377 case UnresolvedLookupExprClass: 3378 case UnresolvedMemberExprClass: 3379 case PackExpansionExprClass: 3380 case SubstNonTypeTemplateParmPackExprClass: 3381 case FunctionParmPackExprClass: 3382 case TypoExprClass: 3383 case RecoveryExprClass: 3384 case CXXFoldExprClass: 3385 // Make a conservative assumption for dependent nodes. 3386 return IncludePossibleEffects; 3387 3388 case DeclRefExprClass: 3389 case ObjCIvarRefExprClass: 3390 case PredefinedExprClass: 3391 case IntegerLiteralClass: 3392 case FixedPointLiteralClass: 3393 case FloatingLiteralClass: 3394 case ImaginaryLiteralClass: 3395 case StringLiteralClass: 3396 case CharacterLiteralClass: 3397 case OffsetOfExprClass: 3398 case ImplicitValueInitExprClass: 3399 case UnaryExprOrTypeTraitExprClass: 3400 case AddrLabelExprClass: 3401 case GNUNullExprClass: 3402 case ArrayInitIndexExprClass: 3403 case NoInitExprClass: 3404 case CXXBoolLiteralExprClass: 3405 case CXXNullPtrLiteralExprClass: 3406 case CXXThisExprClass: 3407 case CXXScalarValueInitExprClass: 3408 case TypeTraitExprClass: 3409 case ArrayTypeTraitExprClass: 3410 case ExpressionTraitExprClass: 3411 case CXXNoexceptExprClass: 3412 case SizeOfPackExprClass: 3413 case ObjCStringLiteralClass: 3414 case ObjCEncodeExprClass: 3415 case ObjCBoolLiteralExprClass: 3416 case ObjCAvailabilityCheckExprClass: 3417 case CXXUuidofExprClass: 3418 case OpaqueValueExprClass: 3419 case SourceLocExprClass: 3420 case ConceptSpecializationExprClass: 3421 case RequiresExprClass: 3422 case SYCLUniqueStableNameExprClass: 3423 // These never have a side-effect. 3424 return false; 3425 3426 case ConstantExprClass: 3427 // FIXME: Move this into the "return false;" block above. 3428 return cast<ConstantExpr>(this)->getSubExpr()->HasSideEffects( 3429 Ctx, IncludePossibleEffects); 3430 3431 case CallExprClass: 3432 case CXXOperatorCallExprClass: 3433 case CXXMemberCallExprClass: 3434 case CUDAKernelCallExprClass: 3435 case UserDefinedLiteralClass: { 3436 // We don't know a call definitely has side effects, except for calls 3437 // to pure/const functions that definitely don't. 3438 // If the call itself is considered side-effect free, check the operands. 3439 const Decl *FD = cast<CallExpr>(this)->getCalleeDecl(); 3440 bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>()); 3441 if (IsPure || !IncludePossibleEffects) 3442 break; 3443 return true; 3444 } 3445 3446 case BlockExprClass: 3447 case CXXBindTemporaryExprClass: 3448 if (!IncludePossibleEffects) 3449 break; 3450 return true; 3451 3452 case MSPropertyRefExprClass: 3453 case MSPropertySubscriptExprClass: 3454 case CompoundAssignOperatorClass: 3455 case VAArgExprClass: 3456 case AtomicExprClass: 3457 case CXXThrowExprClass: 3458 case CXXNewExprClass: 3459 case CXXDeleteExprClass: 3460 case CoawaitExprClass: 3461 case DependentCoawaitExprClass: 3462 case CoyieldExprClass: 3463 // These always have a side-effect. 3464 return true; 3465 3466 case StmtExprClass: { 3467 // StmtExprs have a side-effect if any substatement does. 3468 SideEffectFinder Finder(Ctx, IncludePossibleEffects); 3469 Finder.Visit(cast<StmtExpr>(this)->getSubStmt()); 3470 return Finder.hasSideEffects(); 3471 } 3472 3473 case ExprWithCleanupsClass: 3474 if (IncludePossibleEffects) 3475 if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects()) 3476 return true; 3477 break; 3478 3479 case ParenExprClass: 3480 case ArraySubscriptExprClass: 3481 case MatrixSubscriptExprClass: 3482 case OMPArraySectionExprClass: 3483 case OMPArrayShapingExprClass: 3484 case OMPIteratorExprClass: 3485 case MemberExprClass: 3486 case ConditionalOperatorClass: 3487 case BinaryConditionalOperatorClass: 3488 case CompoundLiteralExprClass: 3489 case ExtVectorElementExprClass: 3490 case DesignatedInitExprClass: 3491 case DesignatedInitUpdateExprClass: 3492 case ArrayInitLoopExprClass: 3493 case ParenListExprClass: 3494 case CXXPseudoDestructorExprClass: 3495 case CXXRewrittenBinaryOperatorClass: 3496 case CXXStdInitializerListExprClass: 3497 case SubstNonTypeTemplateParmExprClass: 3498 case MaterializeTemporaryExprClass: 3499 case ShuffleVectorExprClass: 3500 case ConvertVectorExprClass: 3501 case AsTypeExprClass: 3502 // These have a side-effect if any subexpression does. 3503 break; 3504 3505 case UnaryOperatorClass: 3506 if (cast<UnaryOperator>(this)->isIncrementDecrementOp()) 3507 return true; 3508 break; 3509 3510 case BinaryOperatorClass: 3511 if (cast<BinaryOperator>(this)->isAssignmentOp()) 3512 return true; 3513 break; 3514 3515 case InitListExprClass: 3516 // FIXME: The children for an InitListExpr doesn't include the array filler. 3517 if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller()) 3518 if (E->HasSideEffects(Ctx, IncludePossibleEffects)) 3519 return true; 3520 break; 3521 3522 case GenericSelectionExprClass: 3523 return cast<GenericSelectionExpr>(this)->getResultExpr()-> 3524 HasSideEffects(Ctx, IncludePossibleEffects); 3525 3526 case ChooseExprClass: 3527 return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects( 3528 Ctx, IncludePossibleEffects); 3529 3530 case CXXDefaultArgExprClass: 3531 return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects( 3532 Ctx, IncludePossibleEffects); 3533 3534 case CXXDefaultInitExprClass: { 3535 const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField(); 3536 if (const Expr *E = FD->getInClassInitializer()) 3537 return E->HasSideEffects(Ctx, IncludePossibleEffects); 3538 // If we've not yet parsed the initializer, assume it has side-effects. 3539 return true; 3540 } 3541 3542 case CXXDynamicCastExprClass: { 3543 // A dynamic_cast expression has side-effects if it can throw. 3544 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this); 3545 if (DCE->getTypeAsWritten()->isReferenceType() && 3546 DCE->getCastKind() == CK_Dynamic) 3547 return true; 3548 } 3549 LLVM_FALLTHROUGH; 3550 case ImplicitCastExprClass: 3551 case CStyleCastExprClass: 3552 case CXXStaticCastExprClass: 3553 case CXXReinterpretCastExprClass: 3554 case CXXConstCastExprClass: 3555 case CXXAddrspaceCastExprClass: 3556 case CXXFunctionalCastExprClass: 3557 case BuiltinBitCastExprClass: { 3558 // While volatile reads are side-effecting in both C and C++, we treat them 3559 // as having possible (not definite) side-effects. This allows idiomatic 3560 // code to behave without warning, such as sizeof(*v) for a volatile- 3561 // qualified pointer. 3562 if (!IncludePossibleEffects) 3563 break; 3564 3565 const CastExpr *CE = cast<CastExpr>(this); 3566 if (CE->getCastKind() == CK_LValueToRValue && 3567 CE->getSubExpr()->getType().isVolatileQualified()) 3568 return true; 3569 break; 3570 } 3571 3572 case CXXTypeidExprClass: 3573 // typeid might throw if its subexpression is potentially-evaluated, so has 3574 // side-effects in that case whether or not its subexpression does. 3575 return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated(); 3576 3577 case CXXConstructExprClass: 3578 case CXXTemporaryObjectExprClass: { 3579 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this); 3580 if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects) 3581 return true; 3582 // A trivial constructor does not add any side-effects of its own. Just look 3583 // at its arguments. 3584 break; 3585 } 3586 3587 case CXXInheritedCtorInitExprClass: { 3588 const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this); 3589 if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects) 3590 return true; 3591 break; 3592 } 3593 3594 case LambdaExprClass: { 3595 const LambdaExpr *LE = cast<LambdaExpr>(this); 3596 for (Expr *E : LE->capture_inits()) 3597 if (E && E->HasSideEffects(Ctx, IncludePossibleEffects)) 3598 return true; 3599 return false; 3600 } 3601 3602 case PseudoObjectExprClass: { 3603 // Only look for side-effects in the semantic form, and look past 3604 // OpaqueValueExpr bindings in that form. 3605 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this); 3606 for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(), 3607 E = PO->semantics_end(); 3608 I != E; ++I) { 3609 const Expr *Subexpr = *I; 3610 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr)) 3611 Subexpr = OVE->getSourceExpr(); 3612 if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects)) 3613 return true; 3614 } 3615 return false; 3616 } 3617 3618 case ObjCBoxedExprClass: 3619 case ObjCArrayLiteralClass: 3620 case ObjCDictionaryLiteralClass: 3621 case ObjCSelectorExprClass: 3622 case ObjCProtocolExprClass: 3623 case ObjCIsaExprClass: 3624 case ObjCIndirectCopyRestoreExprClass: 3625 case ObjCSubscriptRefExprClass: 3626 case ObjCBridgedCastExprClass: 3627 case ObjCMessageExprClass: 3628 case ObjCPropertyRefExprClass: 3629 // FIXME: Classify these cases better. 3630 if (IncludePossibleEffects) 3631 return true; 3632 break; 3633 } 3634 3635 // Recurse to children. 3636 for (const Stmt *SubStmt : children()) 3637 if (SubStmt && 3638 cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects)) 3639 return true; 3640 3641 return false; 3642 } 3643 3644 FPOptions Expr::getFPFeaturesInEffect(const LangOptions &LO) const { 3645 if (auto Call = dyn_cast<CallExpr>(this)) 3646 return Call->getFPFeaturesInEffect(LO); 3647 if (auto UO = dyn_cast<UnaryOperator>(this)) 3648 return UO->getFPFeaturesInEffect(LO); 3649 if (auto BO = dyn_cast<BinaryOperator>(this)) 3650 return BO->getFPFeaturesInEffect(LO); 3651 if (auto Cast = dyn_cast<CastExpr>(this)) 3652 return Cast->getFPFeaturesInEffect(LO); 3653 return FPOptions::defaultWithoutTrailingStorage(LO); 3654 } 3655 3656 namespace { 3657 /// Look for a call to a non-trivial function within an expression. 3658 class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder> 3659 { 3660 typedef ConstEvaluatedExprVisitor<NonTrivialCallFinder> Inherited; 3661 3662 bool NonTrivial; 3663 3664 public: 3665 explicit NonTrivialCallFinder(const ASTContext &Context) 3666 : Inherited(Context), NonTrivial(false) { } 3667 3668 bool hasNonTrivialCall() const { return NonTrivial; } 3669 3670 void VisitCallExpr(const CallExpr *E) { 3671 if (const CXXMethodDecl *Method 3672 = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) { 3673 if (Method->isTrivial()) { 3674 // Recurse to children of the call. 3675 Inherited::VisitStmt(E); 3676 return; 3677 } 3678 } 3679 3680 NonTrivial = true; 3681 } 3682 3683 void VisitCXXConstructExpr(const CXXConstructExpr *E) { 3684 if (E->getConstructor()->isTrivial()) { 3685 // Recurse to children of the call. 3686 Inherited::VisitStmt(E); 3687 return; 3688 } 3689 3690 NonTrivial = true; 3691 } 3692 3693 void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { 3694 if (E->getTemporary()->getDestructor()->isTrivial()) { 3695 Inherited::VisitStmt(E); 3696 return; 3697 } 3698 3699 NonTrivial = true; 3700 } 3701 }; 3702 } 3703 3704 bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const { 3705 NonTrivialCallFinder Finder(Ctx); 3706 Finder.Visit(this); 3707 return Finder.hasNonTrivialCall(); 3708 } 3709 3710 /// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null 3711 /// pointer constant or not, as well as the specific kind of constant detected. 3712 /// Null pointer constants can be integer constant expressions with the 3713 /// value zero, casts of zero to void*, nullptr (C++0X), or __null 3714 /// (a GNU extension). 3715 Expr::NullPointerConstantKind 3716 Expr::isNullPointerConstant(ASTContext &Ctx, 3717 NullPointerConstantValueDependence NPC) const { 3718 if (isValueDependent() && 3719 (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) { 3720 // Error-dependent expr should never be a null pointer. 3721 if (containsErrors()) 3722 return NPCK_NotNull; 3723 switch (NPC) { 3724 case NPC_NeverValueDependent: 3725 llvm_unreachable("Unexpected value dependent expression!"); 3726 case NPC_ValueDependentIsNull: 3727 if (isTypeDependent() || getType()->isIntegralType(Ctx)) 3728 return NPCK_ZeroExpression; 3729 else 3730 return NPCK_NotNull; 3731 3732 case NPC_ValueDependentIsNotNull: 3733 return NPCK_NotNull; 3734 } 3735 } 3736 3737 // Strip off a cast to void*, if it exists. Except in C++. 3738 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) { 3739 if (!Ctx.getLangOpts().CPlusPlus) { 3740 // Check that it is a cast to void*. 3741 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) { 3742 QualType Pointee = PT->getPointeeType(); 3743 Qualifiers Qs = Pointee.getQualifiers(); 3744 // Only (void*)0 or equivalent are treated as nullptr. If pointee type 3745 // has non-default address space it is not treated as nullptr. 3746 // (__generic void*)0 in OpenCL 2.0 should not be treated as nullptr 3747 // since it cannot be assigned to a pointer to constant address space. 3748 if (Ctx.getLangOpts().OpenCL && 3749 Pointee.getAddressSpace() == Ctx.getDefaultOpenCLPointeeAddrSpace()) 3750 Qs.removeAddressSpace(); 3751 3752 if (Pointee->isVoidType() && Qs.empty() && // to void* 3753 CE->getSubExpr()->getType()->isIntegerType()) // from int 3754 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC); 3755 } 3756 } 3757 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) { 3758 // Ignore the ImplicitCastExpr type entirely. 3759 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC); 3760 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) { 3761 // Accept ((void*)0) as a null pointer constant, as many other 3762 // implementations do. 3763 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC); 3764 } else if (const GenericSelectionExpr *GE = 3765 dyn_cast<GenericSelectionExpr>(this)) { 3766 if (GE->isResultDependent()) 3767 return NPCK_NotNull; 3768 return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC); 3769 } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) { 3770 if (CE->isConditionDependent()) 3771 return NPCK_NotNull; 3772 return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC); 3773 } else if (const CXXDefaultArgExpr *DefaultArg 3774 = dyn_cast<CXXDefaultArgExpr>(this)) { 3775 // See through default argument expressions. 3776 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC); 3777 } else if (const CXXDefaultInitExpr *DefaultInit 3778 = dyn_cast<CXXDefaultInitExpr>(this)) { 3779 // See through default initializer expressions. 3780 return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC); 3781 } else if (isa<GNUNullExpr>(this)) { 3782 // The GNU __null extension is always a null pointer constant. 3783 return NPCK_GNUNull; 3784 } else if (const MaterializeTemporaryExpr *M 3785 = dyn_cast<MaterializeTemporaryExpr>(this)) { 3786 return M->getSubExpr()->isNullPointerConstant(Ctx, NPC); 3787 } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) { 3788 if (const Expr *Source = OVE->getSourceExpr()) 3789 return Source->isNullPointerConstant(Ctx, NPC); 3790 } 3791 3792 // If the expression has no type information, it cannot be a null pointer 3793 // constant. 3794 if (getType().isNull()) 3795 return NPCK_NotNull; 3796 3797 // C++11 nullptr_t is always a null pointer constant. 3798 if (getType()->isNullPtrType()) 3799 return NPCK_CXX11_nullptr; 3800 3801 if (const RecordType *UT = getType()->getAsUnionType()) 3802 if (!Ctx.getLangOpts().CPlusPlus11 && 3803 UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) 3804 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){ 3805 const Expr *InitExpr = CLE->getInitializer(); 3806 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr)) 3807 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC); 3808 } 3809 // This expression must be an integer type. 3810 if (!getType()->isIntegerType() || 3811 (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType())) 3812 return NPCK_NotNull; 3813 3814 if (Ctx.getLangOpts().CPlusPlus11) { 3815 // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with 3816 // value zero or a prvalue of type std::nullptr_t. 3817 // Microsoft mode permits C++98 rules reflecting MSVC behavior. 3818 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this); 3819 if (Lit && !Lit->getValue()) 3820 return NPCK_ZeroLiteral; 3821 if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx)) 3822 return NPCK_NotNull; 3823 } else { 3824 // If we have an integer constant expression, we need to *evaluate* it and 3825 // test for the value 0. 3826 if (!isIntegerConstantExpr(Ctx)) 3827 return NPCK_NotNull; 3828 } 3829 3830 if (EvaluateKnownConstInt(Ctx) != 0) 3831 return NPCK_NotNull; 3832 3833 if (isa<IntegerLiteral>(this)) 3834 return NPCK_ZeroLiteral; 3835 return NPCK_ZeroExpression; 3836 } 3837 3838 /// If this expression is an l-value for an Objective C 3839 /// property, find the underlying property reference expression. 3840 const ObjCPropertyRefExpr *Expr::getObjCProperty() const { 3841 const Expr *E = this; 3842 while (true) { 3843 assert((E->isLValue() && E->getObjectKind() == OK_ObjCProperty) && 3844 "expression is not a property reference"); 3845 E = E->IgnoreParenCasts(); 3846 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3847 if (BO->getOpcode() == BO_Comma) { 3848 E = BO->getRHS(); 3849 continue; 3850 } 3851 } 3852 3853 break; 3854 } 3855 3856 return cast<ObjCPropertyRefExpr>(E); 3857 } 3858 3859 bool Expr::isObjCSelfExpr() const { 3860 const Expr *E = IgnoreParenImpCasts(); 3861 3862 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 3863 if (!DRE) 3864 return false; 3865 3866 const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl()); 3867 if (!Param) 3868 return false; 3869 3870 const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext()); 3871 if (!M) 3872 return false; 3873 3874 return M->getSelfDecl() == Param; 3875 } 3876 3877 FieldDecl *Expr::getSourceBitField() { 3878 Expr *E = this->IgnoreParens(); 3879 3880 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 3881 if (ICE->getCastKind() == CK_LValueToRValue || 3882 (ICE->isGLValue() && ICE->getCastKind() == CK_NoOp)) 3883 E = ICE->getSubExpr()->IgnoreParens(); 3884 else 3885 break; 3886 } 3887 3888 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E)) 3889 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl())) 3890 if (Field->isBitField()) 3891 return Field; 3892 3893 if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) { 3894 FieldDecl *Ivar = IvarRef->getDecl(); 3895 if (Ivar->isBitField()) 3896 return Ivar; 3897 } 3898 3899 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) { 3900 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl())) 3901 if (Field->isBitField()) 3902 return Field; 3903 3904 if (BindingDecl *BD = dyn_cast<BindingDecl>(DeclRef->getDecl())) 3905 if (Expr *E = BD->getBinding()) 3906 return E->getSourceBitField(); 3907 } 3908 3909 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) { 3910 if (BinOp->isAssignmentOp() && BinOp->getLHS()) 3911 return BinOp->getLHS()->getSourceBitField(); 3912 3913 if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS()) 3914 return BinOp->getRHS()->getSourceBitField(); 3915 } 3916 3917 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) 3918 if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp()) 3919 return UnOp->getSubExpr()->getSourceBitField(); 3920 3921 return nullptr; 3922 } 3923 3924 bool Expr::refersToVectorElement() const { 3925 // FIXME: Why do we not just look at the ObjectKind here? 3926 const Expr *E = this->IgnoreParens(); 3927 3928 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 3929 if (ICE->isGLValue() && ICE->getCastKind() == CK_NoOp) 3930 E = ICE->getSubExpr()->IgnoreParens(); 3931 else 3932 break; 3933 } 3934 3935 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E)) 3936 return ASE->getBase()->getType()->isVectorType(); 3937 3938 if (isa<ExtVectorElementExpr>(E)) 3939 return true; 3940 3941 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 3942 if (auto *BD = dyn_cast<BindingDecl>(DRE->getDecl())) 3943 if (auto *E = BD->getBinding()) 3944 return E->refersToVectorElement(); 3945 3946 return false; 3947 } 3948 3949 bool Expr::refersToGlobalRegisterVar() const { 3950 const Expr *E = this->IgnoreParenImpCasts(); 3951 3952 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 3953 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 3954 if (VD->getStorageClass() == SC_Register && 3955 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl()) 3956 return true; 3957 3958 return false; 3959 } 3960 3961 bool Expr::isSameComparisonOperand(const Expr* E1, const Expr* E2) { 3962 E1 = E1->IgnoreParens(); 3963 E2 = E2->IgnoreParens(); 3964 3965 if (E1->getStmtClass() != E2->getStmtClass()) 3966 return false; 3967 3968 switch (E1->getStmtClass()) { 3969 default: 3970 return false; 3971 case CXXThisExprClass: 3972 return true; 3973 case DeclRefExprClass: { 3974 // DeclRefExpr without an ImplicitCastExpr can happen for integral 3975 // template parameters. 3976 const auto *DRE1 = cast<DeclRefExpr>(E1); 3977 const auto *DRE2 = cast<DeclRefExpr>(E2); 3978 return DRE1->isPRValue() && DRE2->isPRValue() && 3979 DRE1->getDecl() == DRE2->getDecl(); 3980 } 3981 case ImplicitCastExprClass: { 3982 // Peel off implicit casts. 3983 while (true) { 3984 const auto *ICE1 = dyn_cast<ImplicitCastExpr>(E1); 3985 const auto *ICE2 = dyn_cast<ImplicitCastExpr>(E2); 3986 if (!ICE1 || !ICE2) 3987 return false; 3988 if (ICE1->getCastKind() != ICE2->getCastKind()) 3989 return false; 3990 E1 = ICE1->getSubExpr()->IgnoreParens(); 3991 E2 = ICE2->getSubExpr()->IgnoreParens(); 3992 // The final cast must be one of these types. 3993 if (ICE1->getCastKind() == CK_LValueToRValue || 3994 ICE1->getCastKind() == CK_ArrayToPointerDecay || 3995 ICE1->getCastKind() == CK_FunctionToPointerDecay) { 3996 break; 3997 } 3998 } 3999 4000 const auto *DRE1 = dyn_cast<DeclRefExpr>(E1); 4001 const auto *DRE2 = dyn_cast<DeclRefExpr>(E2); 4002 if (DRE1 && DRE2) 4003 return declaresSameEntity(DRE1->getDecl(), DRE2->getDecl()); 4004 4005 const auto *Ivar1 = dyn_cast<ObjCIvarRefExpr>(E1); 4006 const auto *Ivar2 = dyn_cast<ObjCIvarRefExpr>(E2); 4007 if (Ivar1 && Ivar2) { 4008 return Ivar1->isFreeIvar() && Ivar2->isFreeIvar() && 4009 declaresSameEntity(Ivar1->getDecl(), Ivar2->getDecl()); 4010 } 4011 4012 const auto *Array1 = dyn_cast<ArraySubscriptExpr>(E1); 4013 const auto *Array2 = dyn_cast<ArraySubscriptExpr>(E2); 4014 if (Array1 && Array2) { 4015 if (!isSameComparisonOperand(Array1->getBase(), Array2->getBase())) 4016 return false; 4017 4018 auto Idx1 = Array1->getIdx(); 4019 auto Idx2 = Array2->getIdx(); 4020 const auto Integer1 = dyn_cast<IntegerLiteral>(Idx1); 4021 const auto Integer2 = dyn_cast<IntegerLiteral>(Idx2); 4022 if (Integer1 && Integer2) { 4023 if (!llvm::APInt::isSameValue(Integer1->getValue(), 4024 Integer2->getValue())) 4025 return false; 4026 } else { 4027 if (!isSameComparisonOperand(Idx1, Idx2)) 4028 return false; 4029 } 4030 4031 return true; 4032 } 4033 4034 // Walk the MemberExpr chain. 4035 while (isa<MemberExpr>(E1) && isa<MemberExpr>(E2)) { 4036 const auto *ME1 = cast<MemberExpr>(E1); 4037 const auto *ME2 = cast<MemberExpr>(E2); 4038 if (!declaresSameEntity(ME1->getMemberDecl(), ME2->getMemberDecl())) 4039 return false; 4040 if (const auto *D = dyn_cast<VarDecl>(ME1->getMemberDecl())) 4041 if (D->isStaticDataMember()) 4042 return true; 4043 E1 = ME1->getBase()->IgnoreParenImpCasts(); 4044 E2 = ME2->getBase()->IgnoreParenImpCasts(); 4045 } 4046 4047 if (isa<CXXThisExpr>(E1) && isa<CXXThisExpr>(E2)) 4048 return true; 4049 4050 // A static member variable can end the MemberExpr chain with either 4051 // a MemberExpr or a DeclRefExpr. 4052 auto getAnyDecl = [](const Expr *E) -> const ValueDecl * { 4053 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 4054 return DRE->getDecl(); 4055 if (const auto *ME = dyn_cast<MemberExpr>(E)) 4056 return ME->getMemberDecl(); 4057 return nullptr; 4058 }; 4059 4060 const ValueDecl *VD1 = getAnyDecl(E1); 4061 const ValueDecl *VD2 = getAnyDecl(E2); 4062 return declaresSameEntity(VD1, VD2); 4063 } 4064 } 4065 } 4066 4067 /// isArrow - Return true if the base expression is a pointer to vector, 4068 /// return false if the base expression is a vector. 4069 bool ExtVectorElementExpr::isArrow() const { 4070 return getBase()->getType()->isPointerType(); 4071 } 4072 4073 unsigned ExtVectorElementExpr::getNumElements() const { 4074 if (const VectorType *VT = getType()->getAs<VectorType>()) 4075 return VT->getNumElements(); 4076 return 1; 4077 } 4078 4079 /// containsDuplicateElements - Return true if any element access is repeated. 4080 bool ExtVectorElementExpr::containsDuplicateElements() const { 4081 // FIXME: Refactor this code to an accessor on the AST node which returns the 4082 // "type" of component access, and share with code below and in Sema. 4083 StringRef Comp = Accessor->getName(); 4084 4085 // Halving swizzles do not contain duplicate elements. 4086 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd") 4087 return false; 4088 4089 // Advance past s-char prefix on hex swizzles. 4090 if (Comp[0] == 's' || Comp[0] == 'S') 4091 Comp = Comp.substr(1); 4092 4093 for (unsigned i = 0, e = Comp.size(); i != e; ++i) 4094 if (Comp.substr(i + 1).contains(Comp[i])) 4095 return true; 4096 4097 return false; 4098 } 4099 4100 /// getEncodedElementAccess - We encode the fields as a llvm ConstantArray. 4101 void ExtVectorElementExpr::getEncodedElementAccess( 4102 SmallVectorImpl<uint32_t> &Elts) const { 4103 StringRef Comp = Accessor->getName(); 4104 bool isNumericAccessor = false; 4105 if (Comp[0] == 's' || Comp[0] == 'S') { 4106 Comp = Comp.substr(1); 4107 isNumericAccessor = true; 4108 } 4109 4110 bool isHi = Comp == "hi"; 4111 bool isLo = Comp == "lo"; 4112 bool isEven = Comp == "even"; 4113 bool isOdd = Comp == "odd"; 4114 4115 for (unsigned i = 0, e = getNumElements(); i != e; ++i) { 4116 uint64_t Index; 4117 4118 if (isHi) 4119 Index = e + i; 4120 else if (isLo) 4121 Index = i; 4122 else if (isEven) 4123 Index = 2 * i; 4124 else if (isOdd) 4125 Index = 2 * i + 1; 4126 else 4127 Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor); 4128 4129 Elts.push_back(Index); 4130 } 4131 } 4132 4133 ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr *> args, 4134 QualType Type, SourceLocation BLoc, 4135 SourceLocation RP) 4136 : Expr(ShuffleVectorExprClass, Type, VK_PRValue, OK_Ordinary), 4137 BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size()) { 4138 SubExprs = new (C) Stmt*[args.size()]; 4139 for (unsigned i = 0; i != args.size(); i++) 4140 SubExprs[i] = args[i]; 4141 4142 setDependence(computeDependence(this)); 4143 } 4144 4145 void ShuffleVectorExpr::setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs) { 4146 if (SubExprs) C.Deallocate(SubExprs); 4147 4148 this->NumExprs = Exprs.size(); 4149 SubExprs = new (C) Stmt*[NumExprs]; 4150 memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size()); 4151 } 4152 4153 GenericSelectionExpr::GenericSelectionExpr( 4154 const ASTContext &, SourceLocation GenericLoc, Expr *ControllingExpr, 4155 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs, 4156 SourceLocation DefaultLoc, SourceLocation RParenLoc, 4157 bool ContainsUnexpandedParameterPack, unsigned ResultIndex) 4158 : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(), 4159 AssocExprs[ResultIndex]->getValueKind(), 4160 AssocExprs[ResultIndex]->getObjectKind()), 4161 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex), 4162 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) { 4163 assert(AssocTypes.size() == AssocExprs.size() && 4164 "Must have the same number of association expressions" 4165 " and TypeSourceInfo!"); 4166 assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!"); 4167 4168 GenericSelectionExprBits.GenericLoc = GenericLoc; 4169 getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr; 4170 std::copy(AssocExprs.begin(), AssocExprs.end(), 4171 getTrailingObjects<Stmt *>() + AssocExprStartIndex); 4172 std::copy(AssocTypes.begin(), AssocTypes.end(), 4173 getTrailingObjects<TypeSourceInfo *>()); 4174 4175 setDependence(computeDependence(this, ContainsUnexpandedParameterPack)); 4176 } 4177 4178 GenericSelectionExpr::GenericSelectionExpr( 4179 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr, 4180 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs, 4181 SourceLocation DefaultLoc, SourceLocation RParenLoc, 4182 bool ContainsUnexpandedParameterPack) 4183 : Expr(GenericSelectionExprClass, Context.DependentTy, VK_PRValue, 4184 OK_Ordinary), 4185 NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex), 4186 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) { 4187 assert(AssocTypes.size() == AssocExprs.size() && 4188 "Must have the same number of association expressions" 4189 " and TypeSourceInfo!"); 4190 4191 GenericSelectionExprBits.GenericLoc = GenericLoc; 4192 getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr; 4193 std::copy(AssocExprs.begin(), AssocExprs.end(), 4194 getTrailingObjects<Stmt *>() + AssocExprStartIndex); 4195 std::copy(AssocTypes.begin(), AssocTypes.end(), 4196 getTrailingObjects<TypeSourceInfo *>()); 4197 4198 setDependence(computeDependence(this, ContainsUnexpandedParameterPack)); 4199 } 4200 4201 GenericSelectionExpr::GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs) 4202 : Expr(GenericSelectionExprClass, Empty), NumAssocs(NumAssocs) {} 4203 4204 GenericSelectionExpr *GenericSelectionExpr::Create( 4205 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr, 4206 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs, 4207 SourceLocation DefaultLoc, SourceLocation RParenLoc, 4208 bool ContainsUnexpandedParameterPack, unsigned ResultIndex) { 4209 unsigned NumAssocs = AssocExprs.size(); 4210 void *Mem = Context.Allocate( 4211 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs), 4212 alignof(GenericSelectionExpr)); 4213 return new (Mem) GenericSelectionExpr( 4214 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc, 4215 RParenLoc, ContainsUnexpandedParameterPack, ResultIndex); 4216 } 4217 4218 GenericSelectionExpr *GenericSelectionExpr::Create( 4219 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr, 4220 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs, 4221 SourceLocation DefaultLoc, SourceLocation RParenLoc, 4222 bool ContainsUnexpandedParameterPack) { 4223 unsigned NumAssocs = AssocExprs.size(); 4224 void *Mem = Context.Allocate( 4225 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs), 4226 alignof(GenericSelectionExpr)); 4227 return new (Mem) GenericSelectionExpr( 4228 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc, 4229 RParenLoc, ContainsUnexpandedParameterPack); 4230 } 4231 4232 GenericSelectionExpr * 4233 GenericSelectionExpr::CreateEmpty(const ASTContext &Context, 4234 unsigned NumAssocs) { 4235 void *Mem = Context.Allocate( 4236 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs), 4237 alignof(GenericSelectionExpr)); 4238 return new (Mem) GenericSelectionExpr(EmptyShell(), NumAssocs); 4239 } 4240 4241 //===----------------------------------------------------------------------===// 4242 // DesignatedInitExpr 4243 //===----------------------------------------------------------------------===// 4244 4245 IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const { 4246 assert(Kind == FieldDesignator && "Only valid on a field designator"); 4247 if (Field.NameOrField & 0x01) 4248 return reinterpret_cast<IdentifierInfo *>(Field.NameOrField & ~0x01); 4249 return getField()->getIdentifier(); 4250 } 4251 4252 DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty, 4253 llvm::ArrayRef<Designator> Designators, 4254 SourceLocation EqualOrColonLoc, 4255 bool GNUSyntax, 4256 ArrayRef<Expr *> IndexExprs, Expr *Init) 4257 : Expr(DesignatedInitExprClass, Ty, Init->getValueKind(), 4258 Init->getObjectKind()), 4259 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax), 4260 NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) { 4261 this->Designators = new (C) Designator[NumDesignators]; 4262 4263 // Record the initializer itself. 4264 child_iterator Child = child_begin(); 4265 *Child++ = Init; 4266 4267 // Copy the designators and their subexpressions, computing 4268 // value-dependence along the way. 4269 unsigned IndexIdx = 0; 4270 for (unsigned I = 0; I != NumDesignators; ++I) { 4271 this->Designators[I] = Designators[I]; 4272 if (this->Designators[I].isArrayDesignator()) { 4273 // Copy the index expressions into permanent storage. 4274 *Child++ = IndexExprs[IndexIdx++]; 4275 } else if (this->Designators[I].isArrayRangeDesignator()) { 4276 // Copy the start/end expressions into permanent storage. 4277 *Child++ = IndexExprs[IndexIdx++]; 4278 *Child++ = IndexExprs[IndexIdx++]; 4279 } 4280 } 4281 4282 assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions"); 4283 setDependence(computeDependence(this)); 4284 } 4285 4286 DesignatedInitExpr * 4287 DesignatedInitExpr::Create(const ASTContext &C, 4288 llvm::ArrayRef<Designator> Designators, 4289 ArrayRef<Expr*> IndexExprs, 4290 SourceLocation ColonOrEqualLoc, 4291 bool UsesColonSyntax, Expr *Init) { 4292 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1), 4293 alignof(DesignatedInitExpr)); 4294 return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators, 4295 ColonOrEqualLoc, UsesColonSyntax, 4296 IndexExprs, Init); 4297 } 4298 4299 DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(const ASTContext &C, 4300 unsigned NumIndexExprs) { 4301 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1), 4302 alignof(DesignatedInitExpr)); 4303 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1); 4304 } 4305 4306 void DesignatedInitExpr::setDesignators(const ASTContext &C, 4307 const Designator *Desigs, 4308 unsigned NumDesigs) { 4309 Designators = new (C) Designator[NumDesigs]; 4310 NumDesignators = NumDesigs; 4311 for (unsigned I = 0; I != NumDesigs; ++I) 4312 Designators[I] = Desigs[I]; 4313 } 4314 4315 SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const { 4316 DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this); 4317 if (size() == 1) 4318 return DIE->getDesignator(0)->getSourceRange(); 4319 return SourceRange(DIE->getDesignator(0)->getBeginLoc(), 4320 DIE->getDesignator(size() - 1)->getEndLoc()); 4321 } 4322 4323 SourceLocation DesignatedInitExpr::getBeginLoc() const { 4324 SourceLocation StartLoc; 4325 auto *DIE = const_cast<DesignatedInitExpr *>(this); 4326 Designator &First = *DIE->getDesignator(0); 4327 if (First.isFieldDesignator()) 4328 StartLoc = GNUSyntax ? First.Field.FieldLoc : First.Field.DotLoc; 4329 else 4330 StartLoc = First.ArrayOrRange.LBracketLoc; 4331 return StartLoc; 4332 } 4333 4334 SourceLocation DesignatedInitExpr::getEndLoc() const { 4335 return getInit()->getEndLoc(); 4336 } 4337 4338 Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const { 4339 assert(D.Kind == Designator::ArrayDesignator && "Requires array designator"); 4340 return getSubExpr(D.ArrayOrRange.Index + 1); 4341 } 4342 4343 Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const { 4344 assert(D.Kind == Designator::ArrayRangeDesignator && 4345 "Requires array range designator"); 4346 return getSubExpr(D.ArrayOrRange.Index + 1); 4347 } 4348 4349 Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const { 4350 assert(D.Kind == Designator::ArrayRangeDesignator && 4351 "Requires array range designator"); 4352 return getSubExpr(D.ArrayOrRange.Index + 2); 4353 } 4354 4355 /// Replaces the designator at index @p Idx with the series 4356 /// of designators in [First, Last). 4357 void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx, 4358 const Designator *First, 4359 const Designator *Last) { 4360 unsigned NumNewDesignators = Last - First; 4361 if (NumNewDesignators == 0) { 4362 std::copy_backward(Designators + Idx + 1, 4363 Designators + NumDesignators, 4364 Designators + Idx); 4365 --NumNewDesignators; 4366 return; 4367 } 4368 if (NumNewDesignators == 1) { 4369 Designators[Idx] = *First; 4370 return; 4371 } 4372 4373 Designator *NewDesignators 4374 = new (C) Designator[NumDesignators - 1 + NumNewDesignators]; 4375 std::copy(Designators, Designators + Idx, NewDesignators); 4376 std::copy(First, Last, NewDesignators + Idx); 4377 std::copy(Designators + Idx + 1, Designators + NumDesignators, 4378 NewDesignators + Idx + NumNewDesignators); 4379 Designators = NewDesignators; 4380 NumDesignators = NumDesignators - 1 + NumNewDesignators; 4381 } 4382 4383 DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(const ASTContext &C, 4384 SourceLocation lBraceLoc, 4385 Expr *baseExpr, 4386 SourceLocation rBraceLoc) 4387 : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_PRValue, 4388 OK_Ordinary) { 4389 BaseAndUpdaterExprs[0] = baseExpr; 4390 4391 InitListExpr *ILE = new (C) InitListExpr(C, lBraceLoc, None, rBraceLoc); 4392 ILE->setType(baseExpr->getType()); 4393 BaseAndUpdaterExprs[1] = ILE; 4394 4395 // FIXME: this is wrong, set it correctly. 4396 setDependence(ExprDependence::None); 4397 } 4398 4399 SourceLocation DesignatedInitUpdateExpr::getBeginLoc() const { 4400 return getBase()->getBeginLoc(); 4401 } 4402 4403 SourceLocation DesignatedInitUpdateExpr::getEndLoc() const { 4404 return getBase()->getEndLoc(); 4405 } 4406 4407 ParenListExpr::ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs, 4408 SourceLocation RParenLoc) 4409 : Expr(ParenListExprClass, QualType(), VK_PRValue, OK_Ordinary), 4410 LParenLoc(LParenLoc), RParenLoc(RParenLoc) { 4411 ParenListExprBits.NumExprs = Exprs.size(); 4412 4413 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) 4414 getTrailingObjects<Stmt *>()[I] = Exprs[I]; 4415 setDependence(computeDependence(this)); 4416 } 4417 4418 ParenListExpr::ParenListExpr(EmptyShell Empty, unsigned NumExprs) 4419 : Expr(ParenListExprClass, Empty) { 4420 ParenListExprBits.NumExprs = NumExprs; 4421 } 4422 4423 ParenListExpr *ParenListExpr::Create(const ASTContext &Ctx, 4424 SourceLocation LParenLoc, 4425 ArrayRef<Expr *> Exprs, 4426 SourceLocation RParenLoc) { 4427 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(Exprs.size()), 4428 alignof(ParenListExpr)); 4429 return new (Mem) ParenListExpr(LParenLoc, Exprs, RParenLoc); 4430 } 4431 4432 ParenListExpr *ParenListExpr::CreateEmpty(const ASTContext &Ctx, 4433 unsigned NumExprs) { 4434 void *Mem = 4435 Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumExprs), alignof(ParenListExpr)); 4436 return new (Mem) ParenListExpr(EmptyShell(), NumExprs); 4437 } 4438 4439 BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, 4440 Opcode opc, QualType ResTy, ExprValueKind VK, 4441 ExprObjectKind OK, SourceLocation opLoc, 4442 FPOptionsOverride FPFeatures) 4443 : Expr(BinaryOperatorClass, ResTy, VK, OK) { 4444 BinaryOperatorBits.Opc = opc; 4445 assert(!isCompoundAssignmentOp() && 4446 "Use CompoundAssignOperator for compound assignments"); 4447 BinaryOperatorBits.OpLoc = opLoc; 4448 SubExprs[LHS] = lhs; 4449 SubExprs[RHS] = rhs; 4450 BinaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage(); 4451 if (hasStoredFPFeatures()) 4452 setStoredFPFeatures(FPFeatures); 4453 setDependence(computeDependence(this)); 4454 } 4455 4456 BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, 4457 Opcode opc, QualType ResTy, ExprValueKind VK, 4458 ExprObjectKind OK, SourceLocation opLoc, 4459 FPOptionsOverride FPFeatures, bool dead2) 4460 : Expr(CompoundAssignOperatorClass, ResTy, VK, OK) { 4461 BinaryOperatorBits.Opc = opc; 4462 assert(isCompoundAssignmentOp() && 4463 "Use CompoundAssignOperator for compound assignments"); 4464 BinaryOperatorBits.OpLoc = opLoc; 4465 SubExprs[LHS] = lhs; 4466 SubExprs[RHS] = rhs; 4467 BinaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage(); 4468 if (hasStoredFPFeatures()) 4469 setStoredFPFeatures(FPFeatures); 4470 setDependence(computeDependence(this)); 4471 } 4472 4473 BinaryOperator *BinaryOperator::CreateEmpty(const ASTContext &C, 4474 bool HasFPFeatures) { 4475 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures); 4476 void *Mem = 4477 C.Allocate(sizeof(BinaryOperator) + Extra, alignof(BinaryOperator)); 4478 return new (Mem) BinaryOperator(EmptyShell()); 4479 } 4480 4481 BinaryOperator *BinaryOperator::Create(const ASTContext &C, Expr *lhs, 4482 Expr *rhs, Opcode opc, QualType ResTy, 4483 ExprValueKind VK, ExprObjectKind OK, 4484 SourceLocation opLoc, 4485 FPOptionsOverride FPFeatures) { 4486 bool HasFPFeatures = FPFeatures.requiresTrailingStorage(); 4487 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures); 4488 void *Mem = 4489 C.Allocate(sizeof(BinaryOperator) + Extra, alignof(BinaryOperator)); 4490 return new (Mem) 4491 BinaryOperator(C, lhs, rhs, opc, ResTy, VK, OK, opLoc, FPFeatures); 4492 } 4493 4494 CompoundAssignOperator * 4495 CompoundAssignOperator::CreateEmpty(const ASTContext &C, bool HasFPFeatures) { 4496 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures); 4497 void *Mem = C.Allocate(sizeof(CompoundAssignOperator) + Extra, 4498 alignof(CompoundAssignOperator)); 4499 return new (Mem) CompoundAssignOperator(C, EmptyShell(), HasFPFeatures); 4500 } 4501 4502 CompoundAssignOperator * 4503 CompoundAssignOperator::Create(const ASTContext &C, Expr *lhs, Expr *rhs, 4504 Opcode opc, QualType ResTy, ExprValueKind VK, 4505 ExprObjectKind OK, SourceLocation opLoc, 4506 FPOptionsOverride FPFeatures, 4507 QualType CompLHSType, QualType CompResultType) { 4508 bool HasFPFeatures = FPFeatures.requiresTrailingStorage(); 4509 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures); 4510 void *Mem = C.Allocate(sizeof(CompoundAssignOperator) + Extra, 4511 alignof(CompoundAssignOperator)); 4512 return new (Mem) 4513 CompoundAssignOperator(C, lhs, rhs, opc, ResTy, VK, OK, opLoc, FPFeatures, 4514 CompLHSType, CompResultType); 4515 } 4516 4517 UnaryOperator *UnaryOperator::CreateEmpty(const ASTContext &C, 4518 bool hasFPFeatures) { 4519 void *Mem = C.Allocate(totalSizeToAlloc<FPOptionsOverride>(hasFPFeatures), 4520 alignof(UnaryOperator)); 4521 return new (Mem) UnaryOperator(hasFPFeatures, EmptyShell()); 4522 } 4523 4524 UnaryOperator::UnaryOperator(const ASTContext &Ctx, Expr *input, Opcode opc, 4525 QualType type, ExprValueKind VK, ExprObjectKind OK, 4526 SourceLocation l, bool CanOverflow, 4527 FPOptionsOverride FPFeatures) 4528 : Expr(UnaryOperatorClass, type, VK, OK), Val(input) { 4529 UnaryOperatorBits.Opc = opc; 4530 UnaryOperatorBits.CanOverflow = CanOverflow; 4531 UnaryOperatorBits.Loc = l; 4532 UnaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage(); 4533 if (hasStoredFPFeatures()) 4534 setStoredFPFeatures(FPFeatures); 4535 setDependence(computeDependence(this, Ctx)); 4536 } 4537 4538 UnaryOperator *UnaryOperator::Create(const ASTContext &C, Expr *input, 4539 Opcode opc, QualType type, 4540 ExprValueKind VK, ExprObjectKind OK, 4541 SourceLocation l, bool CanOverflow, 4542 FPOptionsOverride FPFeatures) { 4543 bool HasFPFeatures = FPFeatures.requiresTrailingStorage(); 4544 unsigned Size = totalSizeToAlloc<FPOptionsOverride>(HasFPFeatures); 4545 void *Mem = C.Allocate(Size, alignof(UnaryOperator)); 4546 return new (Mem) 4547 UnaryOperator(C, input, opc, type, VK, OK, l, CanOverflow, FPFeatures); 4548 } 4549 4550 const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) { 4551 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e)) 4552 e = ewc->getSubExpr(); 4553 if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e)) 4554 e = m->getSubExpr(); 4555 e = cast<CXXConstructExpr>(e)->getArg(0); 4556 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e)) 4557 e = ice->getSubExpr(); 4558 return cast<OpaqueValueExpr>(e); 4559 } 4560 4561 PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context, 4562 EmptyShell sh, 4563 unsigned numSemanticExprs) { 4564 void *buffer = 4565 Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs), 4566 alignof(PseudoObjectExpr)); 4567 return new(buffer) PseudoObjectExpr(sh, numSemanticExprs); 4568 } 4569 4570 PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs) 4571 : Expr(PseudoObjectExprClass, shell) { 4572 PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1; 4573 } 4574 4575 PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &C, Expr *syntax, 4576 ArrayRef<Expr*> semantics, 4577 unsigned resultIndex) { 4578 assert(syntax && "no syntactic expression!"); 4579 assert(semantics.size() && "no semantic expressions!"); 4580 4581 QualType type; 4582 ExprValueKind VK; 4583 if (resultIndex == NoResult) { 4584 type = C.VoidTy; 4585 VK = VK_PRValue; 4586 } else { 4587 assert(resultIndex < semantics.size()); 4588 type = semantics[resultIndex]->getType(); 4589 VK = semantics[resultIndex]->getValueKind(); 4590 assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary); 4591 } 4592 4593 void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1), 4594 alignof(PseudoObjectExpr)); 4595 return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics, 4596 resultIndex); 4597 } 4598 4599 PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK, 4600 Expr *syntax, ArrayRef<Expr *> semantics, 4601 unsigned resultIndex) 4602 : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary) { 4603 PseudoObjectExprBits.NumSubExprs = semantics.size() + 1; 4604 PseudoObjectExprBits.ResultIndex = resultIndex + 1; 4605 4606 for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) { 4607 Expr *E = (i == 0 ? syntax : semantics[i-1]); 4608 getSubExprsBuffer()[i] = E; 4609 4610 if (isa<OpaqueValueExpr>(E)) 4611 assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr && 4612 "opaque-value semantic expressions for pseudo-object " 4613 "operations must have sources"); 4614 } 4615 4616 setDependence(computeDependence(this)); 4617 } 4618 4619 //===----------------------------------------------------------------------===// 4620 // Child Iterators for iterating over subexpressions/substatements 4621 //===----------------------------------------------------------------------===// 4622 4623 // UnaryExprOrTypeTraitExpr 4624 Stmt::child_range UnaryExprOrTypeTraitExpr::children() { 4625 const_child_range CCR = 4626 const_cast<const UnaryExprOrTypeTraitExpr *>(this)->children(); 4627 return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end())); 4628 } 4629 4630 Stmt::const_child_range UnaryExprOrTypeTraitExpr::children() const { 4631 // If this is of a type and the type is a VLA type (and not a typedef), the 4632 // size expression of the VLA needs to be treated as an executable expression. 4633 // Why isn't this weirdness documented better in StmtIterator? 4634 if (isArgumentType()) { 4635 if (const VariableArrayType *T = 4636 dyn_cast<VariableArrayType>(getArgumentType().getTypePtr())) 4637 return const_child_range(const_child_iterator(T), const_child_iterator()); 4638 return const_child_range(const_child_iterator(), const_child_iterator()); 4639 } 4640 return const_child_range(&Argument.Ex, &Argument.Ex + 1); 4641 } 4642 4643 AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr *> args, QualType t, 4644 AtomicOp op, SourceLocation RP) 4645 : Expr(AtomicExprClass, t, VK_PRValue, OK_Ordinary), 4646 NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op) { 4647 assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions"); 4648 for (unsigned i = 0; i != args.size(); i++) 4649 SubExprs[i] = args[i]; 4650 setDependence(computeDependence(this)); 4651 } 4652 4653 unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) { 4654 switch (Op) { 4655 case AO__c11_atomic_init: 4656 case AO__opencl_atomic_init: 4657 case AO__c11_atomic_load: 4658 case AO__atomic_load_n: 4659 return 2; 4660 4661 case AO__opencl_atomic_load: 4662 case AO__hip_atomic_load: 4663 case AO__c11_atomic_store: 4664 case AO__c11_atomic_exchange: 4665 case AO__atomic_load: 4666 case AO__atomic_store: 4667 case AO__atomic_store_n: 4668 case AO__atomic_exchange_n: 4669 case AO__c11_atomic_fetch_add: 4670 case AO__c11_atomic_fetch_sub: 4671 case AO__c11_atomic_fetch_and: 4672 case AO__c11_atomic_fetch_or: 4673 case AO__c11_atomic_fetch_xor: 4674 case AO__c11_atomic_fetch_nand: 4675 case AO__c11_atomic_fetch_max: 4676 case AO__c11_atomic_fetch_min: 4677 case AO__atomic_fetch_add: 4678 case AO__atomic_fetch_sub: 4679 case AO__atomic_fetch_and: 4680 case AO__atomic_fetch_or: 4681 case AO__atomic_fetch_xor: 4682 case AO__atomic_fetch_nand: 4683 case AO__atomic_add_fetch: 4684 case AO__atomic_sub_fetch: 4685 case AO__atomic_and_fetch: 4686 case AO__atomic_or_fetch: 4687 case AO__atomic_xor_fetch: 4688 case AO__atomic_nand_fetch: 4689 case AO__atomic_min_fetch: 4690 case AO__atomic_max_fetch: 4691 case AO__atomic_fetch_min: 4692 case AO__atomic_fetch_max: 4693 return 3; 4694 4695 case AO__hip_atomic_exchange: 4696 case AO__hip_atomic_fetch_add: 4697 case AO__hip_atomic_fetch_and: 4698 case AO__hip_atomic_fetch_or: 4699 case AO__hip_atomic_fetch_xor: 4700 case AO__hip_atomic_fetch_min: 4701 case AO__hip_atomic_fetch_max: 4702 case AO__opencl_atomic_store: 4703 case AO__hip_atomic_store: 4704 case AO__opencl_atomic_exchange: 4705 case AO__opencl_atomic_fetch_add: 4706 case AO__opencl_atomic_fetch_sub: 4707 case AO__opencl_atomic_fetch_and: 4708 case AO__opencl_atomic_fetch_or: 4709 case AO__opencl_atomic_fetch_xor: 4710 case AO__opencl_atomic_fetch_min: 4711 case AO__opencl_atomic_fetch_max: 4712 case AO__atomic_exchange: 4713 return 4; 4714 4715 case AO__c11_atomic_compare_exchange_strong: 4716 case AO__c11_atomic_compare_exchange_weak: 4717 return 5; 4718 case AO__hip_atomic_compare_exchange_strong: 4719 case AO__opencl_atomic_compare_exchange_strong: 4720 case AO__opencl_atomic_compare_exchange_weak: 4721 case AO__hip_atomic_compare_exchange_weak: 4722 case AO__atomic_compare_exchange: 4723 case AO__atomic_compare_exchange_n: 4724 return 6; 4725 } 4726 llvm_unreachable("unknown atomic op"); 4727 } 4728 4729 QualType AtomicExpr::getValueType() const { 4730 auto T = getPtr()->getType()->castAs<PointerType>()->getPointeeType(); 4731 if (auto AT = T->getAs<AtomicType>()) 4732 return AT->getValueType(); 4733 return T; 4734 } 4735 4736 QualType OMPArraySectionExpr::getBaseOriginalType(const Expr *Base) { 4737 unsigned ArraySectionCount = 0; 4738 while (auto *OASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParens())) { 4739 Base = OASE->getBase(); 4740 ++ArraySectionCount; 4741 } 4742 while (auto *ASE = 4743 dyn_cast<ArraySubscriptExpr>(Base->IgnoreParenImpCasts())) { 4744 Base = ASE->getBase(); 4745 ++ArraySectionCount; 4746 } 4747 Base = Base->IgnoreParenImpCasts(); 4748 auto OriginalTy = Base->getType(); 4749 if (auto *DRE = dyn_cast<DeclRefExpr>(Base)) 4750 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) 4751 OriginalTy = PVD->getOriginalType().getNonReferenceType(); 4752 4753 for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) { 4754 if (OriginalTy->isAnyPointerType()) 4755 OriginalTy = OriginalTy->getPointeeType(); 4756 else { 4757 assert (OriginalTy->isArrayType()); 4758 OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType(); 4759 } 4760 } 4761 return OriginalTy; 4762 } 4763 4764 RecoveryExpr::RecoveryExpr(ASTContext &Ctx, QualType T, SourceLocation BeginLoc, 4765 SourceLocation EndLoc, ArrayRef<Expr *> SubExprs) 4766 : Expr(RecoveryExprClass, T.getNonReferenceType(), 4767 T->isDependentType() ? VK_LValue : getValueKindForType(T), 4768 OK_Ordinary), 4769 BeginLoc(BeginLoc), EndLoc(EndLoc), NumExprs(SubExprs.size()) { 4770 assert(!T.isNull()); 4771 assert(llvm::all_of(SubExprs, [](Expr* E) { return E != nullptr; })); 4772 4773 llvm::copy(SubExprs, getTrailingObjects<Expr *>()); 4774 setDependence(computeDependence(this)); 4775 } 4776 4777 RecoveryExpr *RecoveryExpr::Create(ASTContext &Ctx, QualType T, 4778 SourceLocation BeginLoc, 4779 SourceLocation EndLoc, 4780 ArrayRef<Expr *> SubExprs) { 4781 void *Mem = Ctx.Allocate(totalSizeToAlloc<Expr *>(SubExprs.size()), 4782 alignof(RecoveryExpr)); 4783 return new (Mem) RecoveryExpr(Ctx, T, BeginLoc, EndLoc, SubExprs); 4784 } 4785 4786 RecoveryExpr *RecoveryExpr::CreateEmpty(ASTContext &Ctx, unsigned NumSubExprs) { 4787 void *Mem = Ctx.Allocate(totalSizeToAlloc<Expr *>(NumSubExprs), 4788 alignof(RecoveryExpr)); 4789 return new (Mem) RecoveryExpr(EmptyShell(), NumSubExprs); 4790 } 4791 4792 void OMPArrayShapingExpr::setDimensions(ArrayRef<Expr *> Dims) { 4793 assert( 4794 NumDims == Dims.size() && 4795 "Preallocated number of dimensions is different from the provided one."); 4796 llvm::copy(Dims, getTrailingObjects<Expr *>()); 4797 } 4798 4799 void OMPArrayShapingExpr::setBracketsRanges(ArrayRef<SourceRange> BR) { 4800 assert( 4801 NumDims == BR.size() && 4802 "Preallocated number of dimensions is different from the provided one."); 4803 llvm::copy(BR, getTrailingObjects<SourceRange>()); 4804 } 4805 4806 OMPArrayShapingExpr::OMPArrayShapingExpr(QualType ExprTy, Expr *Op, 4807 SourceLocation L, SourceLocation R, 4808 ArrayRef<Expr *> Dims) 4809 : Expr(OMPArrayShapingExprClass, ExprTy, VK_LValue, OK_Ordinary), LPLoc(L), 4810 RPLoc(R), NumDims(Dims.size()) { 4811 setBase(Op); 4812 setDimensions(Dims); 4813 setDependence(computeDependence(this)); 4814 } 4815 4816 OMPArrayShapingExpr * 4817 OMPArrayShapingExpr::Create(const ASTContext &Context, QualType T, Expr *Op, 4818 SourceLocation L, SourceLocation R, 4819 ArrayRef<Expr *> Dims, 4820 ArrayRef<SourceRange> BracketRanges) { 4821 assert(Dims.size() == BracketRanges.size() && 4822 "Different number of dimensions and brackets ranges."); 4823 void *Mem = Context.Allocate( 4824 totalSizeToAlloc<Expr *, SourceRange>(Dims.size() + 1, Dims.size()), 4825 alignof(OMPArrayShapingExpr)); 4826 auto *E = new (Mem) OMPArrayShapingExpr(T, Op, L, R, Dims); 4827 E->setBracketsRanges(BracketRanges); 4828 return E; 4829 } 4830 4831 OMPArrayShapingExpr *OMPArrayShapingExpr::CreateEmpty(const ASTContext &Context, 4832 unsigned NumDims) { 4833 void *Mem = Context.Allocate( 4834 totalSizeToAlloc<Expr *, SourceRange>(NumDims + 1, NumDims), 4835 alignof(OMPArrayShapingExpr)); 4836 return new (Mem) OMPArrayShapingExpr(EmptyShell(), NumDims); 4837 } 4838 4839 void OMPIteratorExpr::setIteratorDeclaration(unsigned I, Decl *D) { 4840 assert(I < NumIterators && 4841 "Idx is greater or equal the number of iterators definitions."); 4842 getTrailingObjects<Decl *>()[I] = D; 4843 } 4844 4845 void OMPIteratorExpr::setAssignmentLoc(unsigned I, SourceLocation Loc) { 4846 assert(I < NumIterators && 4847 "Idx is greater or equal the number of iterators definitions."); 4848 getTrailingObjects< 4849 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) + 4850 static_cast<int>(RangeLocOffset::AssignLoc)] = Loc; 4851 } 4852 4853 void OMPIteratorExpr::setIteratorRange(unsigned I, Expr *Begin, 4854 SourceLocation ColonLoc, Expr *End, 4855 SourceLocation SecondColonLoc, 4856 Expr *Step) { 4857 assert(I < NumIterators && 4858 "Idx is greater or equal the number of iterators definitions."); 4859 getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) + 4860 static_cast<int>(RangeExprOffset::Begin)] = 4861 Begin; 4862 getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) + 4863 static_cast<int>(RangeExprOffset::End)] = End; 4864 getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) + 4865 static_cast<int>(RangeExprOffset::Step)] = Step; 4866 getTrailingObjects< 4867 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) + 4868 static_cast<int>(RangeLocOffset::FirstColonLoc)] = 4869 ColonLoc; 4870 getTrailingObjects< 4871 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) + 4872 static_cast<int>(RangeLocOffset::SecondColonLoc)] = 4873 SecondColonLoc; 4874 } 4875 4876 Decl *OMPIteratorExpr::getIteratorDecl(unsigned I) { 4877 return getTrailingObjects<Decl *>()[I]; 4878 } 4879 4880 OMPIteratorExpr::IteratorRange OMPIteratorExpr::getIteratorRange(unsigned I) { 4881 IteratorRange Res; 4882 Res.Begin = 4883 getTrailingObjects<Expr *>()[I * static_cast<int>( 4884 RangeExprOffset::Total) + 4885 static_cast<int>(RangeExprOffset::Begin)]; 4886 Res.End = 4887 getTrailingObjects<Expr *>()[I * static_cast<int>( 4888 RangeExprOffset::Total) + 4889 static_cast<int>(RangeExprOffset::End)]; 4890 Res.Step = 4891 getTrailingObjects<Expr *>()[I * static_cast<int>( 4892 RangeExprOffset::Total) + 4893 static_cast<int>(RangeExprOffset::Step)]; 4894 return Res; 4895 } 4896 4897 SourceLocation OMPIteratorExpr::getAssignLoc(unsigned I) const { 4898 return getTrailingObjects< 4899 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) + 4900 static_cast<int>(RangeLocOffset::AssignLoc)]; 4901 } 4902 4903 SourceLocation OMPIteratorExpr::getColonLoc(unsigned I) const { 4904 return getTrailingObjects< 4905 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) + 4906 static_cast<int>(RangeLocOffset::FirstColonLoc)]; 4907 } 4908 4909 SourceLocation OMPIteratorExpr::getSecondColonLoc(unsigned I) const { 4910 return getTrailingObjects< 4911 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) + 4912 static_cast<int>(RangeLocOffset::SecondColonLoc)]; 4913 } 4914 4915 void OMPIteratorExpr::setHelper(unsigned I, const OMPIteratorHelperData &D) { 4916 getTrailingObjects<OMPIteratorHelperData>()[I] = D; 4917 } 4918 4919 OMPIteratorHelperData &OMPIteratorExpr::getHelper(unsigned I) { 4920 return getTrailingObjects<OMPIteratorHelperData>()[I]; 4921 } 4922 4923 const OMPIteratorHelperData &OMPIteratorExpr::getHelper(unsigned I) const { 4924 return getTrailingObjects<OMPIteratorHelperData>()[I]; 4925 } 4926 4927 OMPIteratorExpr::OMPIteratorExpr( 4928 QualType ExprTy, SourceLocation IteratorKwLoc, SourceLocation L, 4929 SourceLocation R, ArrayRef<OMPIteratorExpr::IteratorDefinition> Data, 4930 ArrayRef<OMPIteratorHelperData> Helpers) 4931 : Expr(OMPIteratorExprClass, ExprTy, VK_LValue, OK_Ordinary), 4932 IteratorKwLoc(IteratorKwLoc), LPLoc(L), RPLoc(R), 4933 NumIterators(Data.size()) { 4934 for (unsigned I = 0, E = Data.size(); I < E; ++I) { 4935 const IteratorDefinition &D = Data[I]; 4936 setIteratorDeclaration(I, D.IteratorDecl); 4937 setAssignmentLoc(I, D.AssignmentLoc); 4938 setIteratorRange(I, D.Range.Begin, D.ColonLoc, D.Range.End, 4939 D.SecondColonLoc, D.Range.Step); 4940 setHelper(I, Helpers[I]); 4941 } 4942 setDependence(computeDependence(this)); 4943 } 4944 4945 OMPIteratorExpr * 4946 OMPIteratorExpr::Create(const ASTContext &Context, QualType T, 4947 SourceLocation IteratorKwLoc, SourceLocation L, 4948 SourceLocation R, 4949 ArrayRef<OMPIteratorExpr::IteratorDefinition> Data, 4950 ArrayRef<OMPIteratorHelperData> Helpers) { 4951 assert(Data.size() == Helpers.size() && 4952 "Data and helpers must have the same size."); 4953 void *Mem = Context.Allocate( 4954 totalSizeToAlloc<Decl *, Expr *, SourceLocation, OMPIteratorHelperData>( 4955 Data.size(), Data.size() * static_cast<int>(RangeExprOffset::Total), 4956 Data.size() * static_cast<int>(RangeLocOffset::Total), 4957 Helpers.size()), 4958 alignof(OMPIteratorExpr)); 4959 return new (Mem) OMPIteratorExpr(T, IteratorKwLoc, L, R, Data, Helpers); 4960 } 4961 4962 OMPIteratorExpr *OMPIteratorExpr::CreateEmpty(const ASTContext &Context, 4963 unsigned NumIterators) { 4964 void *Mem = Context.Allocate( 4965 totalSizeToAlloc<Decl *, Expr *, SourceLocation, OMPIteratorHelperData>( 4966 NumIterators, NumIterators * static_cast<int>(RangeExprOffset::Total), 4967 NumIterators * static_cast<int>(RangeLocOffset::Total), NumIterators), 4968 alignof(OMPIteratorExpr)); 4969 return new (Mem) OMPIteratorExpr(EmptyShell(), NumIterators); 4970 } 4971