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