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