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