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