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