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