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