1 //===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 /// 10 /// \file 11 /// \brief Implements semantic analysis for C++ expressions. 12 /// 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/Sema/SemaInternal.h" 16 #include "TreeTransform.h" 17 #include "TypeLocBuilder.h" 18 #include "clang/AST/ASTContext.h" 19 #include "clang/AST/ASTLambda.h" 20 #include "clang/AST/CXXInheritance.h" 21 #include "clang/AST/CharUnits.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/ExprCXX.h" 24 #include "clang/AST/ExprObjC.h" 25 #include "clang/AST/RecursiveASTVisitor.h" 26 #include "clang/AST/TypeLoc.h" 27 #include "clang/Basic/PartialDiagnostic.h" 28 #include "clang/Basic/TargetInfo.h" 29 #include "clang/Lex/Preprocessor.h" 30 #include "clang/Sema/DeclSpec.h" 31 #include "clang/Sema/Initialization.h" 32 #include "clang/Sema/Lookup.h" 33 #include "clang/Sema/ParsedTemplate.h" 34 #include "clang/Sema/Scope.h" 35 #include "clang/Sema/ScopeInfo.h" 36 #include "clang/Sema/SemaLambda.h" 37 #include "clang/Sema/TemplateDeduction.h" 38 #include "llvm/ADT/APInt.h" 39 #include "llvm/ADT/STLExtras.h" 40 #include "llvm/Support/ErrorHandling.h" 41 using namespace clang; 42 using namespace sema; 43 44 /// \brief Handle the result of the special case name lookup for inheriting 45 /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as 46 /// constructor names in member using declarations, even if 'X' is not the 47 /// name of the corresponding type. 48 ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS, 49 SourceLocation NameLoc, 50 IdentifierInfo &Name) { 51 NestedNameSpecifier *NNS = SS.getScopeRep(); 52 53 // Convert the nested-name-specifier into a type. 54 QualType Type; 55 switch (NNS->getKind()) { 56 case NestedNameSpecifier::TypeSpec: 57 case NestedNameSpecifier::TypeSpecWithTemplate: 58 Type = QualType(NNS->getAsType(), 0); 59 break; 60 61 case NestedNameSpecifier::Identifier: 62 // Strip off the last layer of the nested-name-specifier and build a 63 // typename type for it. 64 assert(NNS->getAsIdentifier() == &Name && "not a constructor name"); 65 Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(), 66 NNS->getAsIdentifier()); 67 break; 68 69 case NestedNameSpecifier::Global: 70 case NestedNameSpecifier::Super: 71 case NestedNameSpecifier::Namespace: 72 case NestedNameSpecifier::NamespaceAlias: 73 llvm_unreachable("Nested name specifier is not a type for inheriting ctor"); 74 } 75 76 // This reference to the type is located entirely at the location of the 77 // final identifier in the qualified-id. 78 return CreateParsedType(Type, 79 Context.getTrivialTypeSourceInfo(Type, NameLoc)); 80 } 81 82 ParsedType Sema::getDestructorName(SourceLocation TildeLoc, 83 IdentifierInfo &II, 84 SourceLocation NameLoc, 85 Scope *S, CXXScopeSpec &SS, 86 ParsedType ObjectTypePtr, 87 bool EnteringContext) { 88 // Determine where to perform name lookup. 89 90 // FIXME: This area of the standard is very messy, and the current 91 // wording is rather unclear about which scopes we search for the 92 // destructor name; see core issues 399 and 555. Issue 399 in 93 // particular shows where the current description of destructor name 94 // lookup is completely out of line with existing practice, e.g., 95 // this appears to be ill-formed: 96 // 97 // namespace N { 98 // template <typename T> struct S { 99 // ~S(); 100 // }; 101 // } 102 // 103 // void f(N::S<int>* s) { 104 // s->N::S<int>::~S(); 105 // } 106 // 107 // See also PR6358 and PR6359. 108 // For this reason, we're currently only doing the C++03 version of this 109 // code; the C++0x version has to wait until we get a proper spec. 110 QualType SearchType; 111 DeclContext *LookupCtx = nullptr; 112 bool isDependent = false; 113 bool LookInScope = false; 114 115 if (SS.isInvalid()) 116 return nullptr; 117 118 // If we have an object type, it's because we are in a 119 // pseudo-destructor-expression or a member access expression, and 120 // we know what type we're looking for. 121 if (ObjectTypePtr) 122 SearchType = GetTypeFromParser(ObjectTypePtr); 123 124 if (SS.isSet()) { 125 NestedNameSpecifier *NNS = SS.getScopeRep(); 126 127 bool AlreadySearched = false; 128 bool LookAtPrefix = true; 129 // C++11 [basic.lookup.qual]p6: 130 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier, 131 // the type-names are looked up as types in the scope designated by the 132 // nested-name-specifier. Similarly, in a qualified-id of the form: 133 // 134 // nested-name-specifier[opt] class-name :: ~ class-name 135 // 136 // the second class-name is looked up in the same scope as the first. 137 // 138 // Here, we determine whether the code below is permitted to look at the 139 // prefix of the nested-name-specifier. 140 DeclContext *DC = computeDeclContext(SS, EnteringContext); 141 if (DC && DC->isFileContext()) { 142 AlreadySearched = true; 143 LookupCtx = DC; 144 isDependent = false; 145 } else if (DC && isa<CXXRecordDecl>(DC)) { 146 LookAtPrefix = false; 147 LookInScope = true; 148 } 149 150 // The second case from the C++03 rules quoted further above. 151 NestedNameSpecifier *Prefix = nullptr; 152 if (AlreadySearched) { 153 // Nothing left to do. 154 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) { 155 CXXScopeSpec PrefixSS; 156 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data())); 157 LookupCtx = computeDeclContext(PrefixSS, EnteringContext); 158 isDependent = isDependentScopeSpecifier(PrefixSS); 159 } else if (ObjectTypePtr) { 160 LookupCtx = computeDeclContext(SearchType); 161 isDependent = SearchType->isDependentType(); 162 } else { 163 LookupCtx = computeDeclContext(SS, EnteringContext); 164 isDependent = LookupCtx && LookupCtx->isDependentContext(); 165 } 166 } else if (ObjectTypePtr) { 167 // C++ [basic.lookup.classref]p3: 168 // If the unqualified-id is ~type-name, the type-name is looked up 169 // in the context of the entire postfix-expression. If the type T 170 // of the object expression is of a class type C, the type-name is 171 // also looked up in the scope of class C. At least one of the 172 // lookups shall find a name that refers to (possibly 173 // cv-qualified) T. 174 LookupCtx = computeDeclContext(SearchType); 175 isDependent = SearchType->isDependentType(); 176 assert((isDependent || !SearchType->isIncompleteType()) && 177 "Caller should have completed object type"); 178 179 LookInScope = true; 180 } else { 181 // Perform lookup into the current scope (only). 182 LookInScope = true; 183 } 184 185 TypeDecl *NonMatchingTypeDecl = nullptr; 186 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName); 187 for (unsigned Step = 0; Step != 2; ++Step) { 188 // Look for the name first in the computed lookup context (if we 189 // have one) and, if that fails to find a match, in the scope (if 190 // we're allowed to look there). 191 Found.clear(); 192 if (Step == 0 && LookupCtx) 193 LookupQualifiedName(Found, LookupCtx); 194 else if (Step == 1 && LookInScope && S) 195 LookupName(Found, S); 196 else 197 continue; 198 199 // FIXME: Should we be suppressing ambiguities here? 200 if (Found.isAmbiguous()) 201 return nullptr; 202 203 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) { 204 QualType T = Context.getTypeDeclType(Type); 205 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 206 207 if (SearchType.isNull() || SearchType->isDependentType() || 208 Context.hasSameUnqualifiedType(T, SearchType)) { 209 // We found our type! 210 211 return CreateParsedType(T, 212 Context.getTrivialTypeSourceInfo(T, NameLoc)); 213 } 214 215 if (!SearchType.isNull()) 216 NonMatchingTypeDecl = Type; 217 } 218 219 // If the name that we found is a class template name, and it is 220 // the same name as the template name in the last part of the 221 // nested-name-specifier (if present) or the object type, then 222 // this is the destructor for that class. 223 // FIXME: This is a workaround until we get real drafting for core 224 // issue 399, for which there isn't even an obvious direction. 225 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) { 226 QualType MemberOfType; 227 if (SS.isSet()) { 228 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) { 229 // Figure out the type of the context, if it has one. 230 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) 231 MemberOfType = Context.getTypeDeclType(Record); 232 } 233 } 234 if (MemberOfType.isNull()) 235 MemberOfType = SearchType; 236 237 if (MemberOfType.isNull()) 238 continue; 239 240 // We're referring into a class template specialization. If the 241 // class template we found is the same as the template being 242 // specialized, we found what we are looking for. 243 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) { 244 if (ClassTemplateSpecializationDecl *Spec 245 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { 246 if (Spec->getSpecializedTemplate()->getCanonicalDecl() == 247 Template->getCanonicalDecl()) 248 return CreateParsedType( 249 MemberOfType, 250 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc)); 251 } 252 253 continue; 254 } 255 256 // We're referring to an unresolved class template 257 // specialization. Determine whether we class template we found 258 // is the same as the template being specialized or, if we don't 259 // know which template is being specialized, that it at least 260 // has the same name. 261 if (const TemplateSpecializationType *SpecType 262 = MemberOfType->getAs<TemplateSpecializationType>()) { 263 TemplateName SpecName = SpecType->getTemplateName(); 264 265 // The class template we found is the same template being 266 // specialized. 267 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) { 268 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl()) 269 return CreateParsedType( 270 MemberOfType, 271 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc)); 272 273 continue; 274 } 275 276 // The class template we found has the same name as the 277 // (dependent) template name being specialized. 278 if (DependentTemplateName *DepTemplate 279 = SpecName.getAsDependentTemplateName()) { 280 if (DepTemplate->isIdentifier() && 281 DepTemplate->getIdentifier() == Template->getIdentifier()) 282 return CreateParsedType( 283 MemberOfType, 284 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc)); 285 286 continue; 287 } 288 } 289 } 290 } 291 292 if (isDependent) { 293 // We didn't find our type, but that's okay: it's dependent 294 // anyway. 295 296 // FIXME: What if we have no nested-name-specifier? 297 QualType T = CheckTypenameType(ETK_None, SourceLocation(), 298 SS.getWithLocInContext(Context), 299 II, NameLoc); 300 return ParsedType::make(T); 301 } 302 303 if (NonMatchingTypeDecl) { 304 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl); 305 Diag(NameLoc, diag::err_destructor_expr_type_mismatch) 306 << T << SearchType; 307 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here) 308 << T; 309 } else if (ObjectTypePtr) 310 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type) 311 << &II; 312 else { 313 SemaDiagnosticBuilder DtorDiag = Diag(NameLoc, 314 diag::err_destructor_class_name); 315 if (S) { 316 const DeclContext *Ctx = S->getEntity(); 317 if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx)) 318 DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc), 319 Class->getNameAsString()); 320 } 321 } 322 323 return nullptr; 324 } 325 326 ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) { 327 if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType) 328 return nullptr; 329 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype 330 && "only get destructor types from declspecs"); 331 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 332 QualType SearchType = GetTypeFromParser(ObjectType); 333 if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(SearchType, T)) { 334 return ParsedType::make(T); 335 } 336 337 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch) 338 << T << SearchType; 339 return nullptr; 340 } 341 342 bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS, 343 const UnqualifiedId &Name) { 344 assert(Name.getKind() == UnqualifiedId::IK_LiteralOperatorId); 345 346 if (!SS.isValid()) 347 return false; 348 349 switch (SS.getScopeRep()->getKind()) { 350 case NestedNameSpecifier::Identifier: 351 case NestedNameSpecifier::TypeSpec: 352 case NestedNameSpecifier::TypeSpecWithTemplate: 353 // Per C++11 [over.literal]p2, literal operators can only be declared at 354 // namespace scope. Therefore, this unqualified-id cannot name anything. 355 // Reject it early, because we have no AST representation for this in the 356 // case where the scope is dependent. 357 Diag(Name.getLocStart(), diag::err_literal_operator_id_outside_namespace) 358 << SS.getScopeRep(); 359 return true; 360 361 case NestedNameSpecifier::Global: 362 case NestedNameSpecifier::Super: 363 case NestedNameSpecifier::Namespace: 364 case NestedNameSpecifier::NamespaceAlias: 365 return false; 366 } 367 368 llvm_unreachable("unknown nested name specifier kind"); 369 } 370 371 /// \brief Build a C++ typeid expression with a type operand. 372 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, 373 SourceLocation TypeidLoc, 374 TypeSourceInfo *Operand, 375 SourceLocation RParenLoc) { 376 // C++ [expr.typeid]p4: 377 // The top-level cv-qualifiers of the lvalue expression or the type-id 378 // that is the operand of typeid are always ignored. 379 // If the type of the type-id is a class type or a reference to a class 380 // type, the class shall be completely-defined. 381 Qualifiers Quals; 382 QualType T 383 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(), 384 Quals); 385 if (T->getAs<RecordType>() && 386 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) 387 return ExprError(); 388 389 if (T->isVariablyModifiedType()) 390 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T); 391 392 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand, 393 SourceRange(TypeidLoc, RParenLoc)); 394 } 395 396 /// \brief Build a C++ typeid expression with an expression operand. 397 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, 398 SourceLocation TypeidLoc, 399 Expr *E, 400 SourceLocation RParenLoc) { 401 bool WasEvaluated = false; 402 if (E && !E->isTypeDependent()) { 403 if (E->getType()->isPlaceholderType()) { 404 ExprResult result = CheckPlaceholderExpr(E); 405 if (result.isInvalid()) return ExprError(); 406 E = result.get(); 407 } 408 409 QualType T = E->getType(); 410 if (const RecordType *RecordT = T->getAs<RecordType>()) { 411 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl()); 412 // C++ [expr.typeid]p3: 413 // [...] If the type of the expression is a class type, the class 414 // shall be completely-defined. 415 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) 416 return ExprError(); 417 418 // C++ [expr.typeid]p3: 419 // When typeid is applied to an expression other than an glvalue of a 420 // polymorphic class type [...] [the] expression is an unevaluated 421 // operand. [...] 422 if (RecordD->isPolymorphic() && E->isGLValue()) { 423 // The subexpression is potentially evaluated; switch the context 424 // and recheck the subexpression. 425 ExprResult Result = TransformToPotentiallyEvaluated(E); 426 if (Result.isInvalid()) return ExprError(); 427 E = Result.get(); 428 429 // We require a vtable to query the type at run time. 430 MarkVTableUsed(TypeidLoc, RecordD); 431 WasEvaluated = true; 432 } 433 } 434 435 // C++ [expr.typeid]p4: 436 // [...] If the type of the type-id is a reference to a possibly 437 // cv-qualified type, the result of the typeid expression refers to a 438 // std::type_info object representing the cv-unqualified referenced 439 // type. 440 Qualifiers Quals; 441 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals); 442 if (!Context.hasSameType(T, UnqualT)) { 443 T = UnqualT; 444 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get(); 445 } 446 } 447 448 if (E->getType()->isVariablyModifiedType()) 449 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) 450 << E->getType()); 451 else if (ActiveTemplateInstantiations.empty() && 452 E->HasSideEffects(Context, WasEvaluated)) { 453 // The expression operand for typeid is in an unevaluated expression 454 // context, so side effects could result in unintended consequences. 455 Diag(E->getExprLoc(), WasEvaluated 456 ? diag::warn_side_effects_typeid 457 : diag::warn_side_effects_unevaluated_context); 458 } 459 460 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E, 461 SourceRange(TypeidLoc, RParenLoc)); 462 } 463 464 /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression); 465 ExprResult 466 Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, 467 bool isType, void *TyOrExpr, SourceLocation RParenLoc) { 468 // Find the std::type_info type. 469 if (!getStdNamespace()) 470 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); 471 472 if (!CXXTypeInfoDecl) { 473 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info"); 474 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName); 475 LookupQualifiedName(R, getStdNamespace()); 476 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>(); 477 // Microsoft's typeinfo doesn't have type_info in std but in the global 478 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153. 479 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) { 480 LookupQualifiedName(R, Context.getTranslationUnitDecl()); 481 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>(); 482 } 483 if (!CXXTypeInfoDecl) 484 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); 485 } 486 487 if (!getLangOpts().RTTI) { 488 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti)); 489 } 490 491 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl); 492 493 if (isType) { 494 // The operand is a type; handle it as such. 495 TypeSourceInfo *TInfo = nullptr; 496 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr), 497 &TInfo); 498 if (T.isNull()) 499 return ExprError(); 500 501 if (!TInfo) 502 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); 503 504 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc); 505 } 506 507 // The operand is an expression. 508 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc); 509 } 510 511 /// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to 512 /// a single GUID. 513 static void 514 getUuidAttrOfType(Sema &SemaRef, QualType QT, 515 llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) { 516 // Optionally remove one level of pointer, reference or array indirection. 517 const Type *Ty = QT.getTypePtr(); 518 if (QT->isPointerType() || QT->isReferenceType()) 519 Ty = QT->getPointeeType().getTypePtr(); 520 else if (QT->isArrayType()) 521 Ty = Ty->getBaseElementTypeUnsafe(); 522 523 const auto *RD = Ty->getAsCXXRecordDecl(); 524 if (!RD) 525 return; 526 527 if (const auto *Uuid = RD->getMostRecentDecl()->getAttr<UuidAttr>()) { 528 UuidAttrs.insert(Uuid); 529 return; 530 } 531 532 // __uuidof can grab UUIDs from template arguments. 533 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(RD)) { 534 const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); 535 for (const TemplateArgument &TA : TAL.asArray()) { 536 const UuidAttr *UuidForTA = nullptr; 537 if (TA.getKind() == TemplateArgument::Type) 538 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs); 539 else if (TA.getKind() == TemplateArgument::Declaration) 540 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs); 541 542 if (UuidForTA) 543 UuidAttrs.insert(UuidForTA); 544 } 545 } 546 } 547 548 /// \brief Build a Microsoft __uuidof expression with a type operand. 549 ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType, 550 SourceLocation TypeidLoc, 551 TypeSourceInfo *Operand, 552 SourceLocation RParenLoc) { 553 StringRef UuidStr; 554 if (!Operand->getType()->isDependentType()) { 555 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs; 556 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs); 557 if (UuidAttrs.empty()) 558 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid)); 559 if (UuidAttrs.size() > 1) 560 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids)); 561 UuidStr = UuidAttrs.back()->getGuid(); 562 } 563 564 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr, 565 SourceRange(TypeidLoc, RParenLoc)); 566 } 567 568 /// \brief Build a Microsoft __uuidof expression with an expression operand. 569 ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType, 570 SourceLocation TypeidLoc, 571 Expr *E, 572 SourceLocation RParenLoc) { 573 StringRef UuidStr; 574 if (!E->getType()->isDependentType()) { 575 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 576 UuidStr = "00000000-0000-0000-0000-000000000000"; 577 } else { 578 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs; 579 getUuidAttrOfType(*this, E->getType(), UuidAttrs); 580 if (UuidAttrs.empty()) 581 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid)); 582 if (UuidAttrs.size() > 1) 583 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids)); 584 UuidStr = UuidAttrs.back()->getGuid(); 585 } 586 } 587 588 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr, 589 SourceRange(TypeidLoc, RParenLoc)); 590 } 591 592 /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression); 593 ExprResult 594 Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, 595 bool isType, void *TyOrExpr, SourceLocation RParenLoc) { 596 // If MSVCGuidDecl has not been cached, do the lookup. 597 if (!MSVCGuidDecl) { 598 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID"); 599 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName); 600 LookupQualifiedName(R, Context.getTranslationUnitDecl()); 601 MSVCGuidDecl = R.getAsSingle<RecordDecl>(); 602 if (!MSVCGuidDecl) 603 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof)); 604 } 605 606 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl); 607 608 if (isType) { 609 // The operand is a type; handle it as such. 610 TypeSourceInfo *TInfo = nullptr; 611 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr), 612 &TInfo); 613 if (T.isNull()) 614 return ExprError(); 615 616 if (!TInfo) 617 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); 618 619 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc); 620 } 621 622 // The operand is an expression. 623 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc); 624 } 625 626 /// ActOnCXXBoolLiteral - Parse {true,false} literals. 627 ExprResult 628 Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 629 assert((Kind == tok::kw_true || Kind == tok::kw_false) && 630 "Unknown C++ Boolean value!"); 631 return new (Context) 632 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc); 633 } 634 635 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. 636 ExprResult 637 Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) { 638 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc); 639 } 640 641 /// ActOnCXXThrow - Parse throw expressions. 642 ExprResult 643 Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) { 644 bool IsThrownVarInScope = false; 645 if (Ex) { 646 // C++0x [class.copymove]p31: 647 // When certain criteria are met, an implementation is allowed to omit the 648 // copy/move construction of a class object [...] 649 // 650 // - in a throw-expression, when the operand is the name of a 651 // non-volatile automatic object (other than a function or catch- 652 // clause parameter) whose scope does not extend beyond the end of the 653 // innermost enclosing try-block (if there is one), the copy/move 654 // operation from the operand to the exception object (15.1) can be 655 // omitted by constructing the automatic object directly into the 656 // exception object 657 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens())) 658 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 659 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) { 660 for( ; S; S = S->getParent()) { 661 if (S->isDeclScope(Var)) { 662 IsThrownVarInScope = true; 663 break; 664 } 665 666 if (S->getFlags() & 667 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope | 668 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope | 669 Scope::TryScope)) 670 break; 671 } 672 } 673 } 674 } 675 676 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope); 677 } 678 679 ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, 680 bool IsThrownVarInScope) { 681 // Don't report an error if 'throw' is used in system headers. 682 if (!getLangOpts().CXXExceptions && 683 !getSourceManager().isInSystemHeader(OpLoc)) 684 Diag(OpLoc, diag::err_exceptions_disabled) << "throw"; 685 686 // Exceptions aren't allowed in CUDA device code. 687 if (getLangOpts().CUDA) 688 CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions) 689 << "throw" << CurrentCUDATarget(); 690 691 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope()) 692 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw"; 693 694 if (Ex && !Ex->isTypeDependent()) { 695 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType()); 696 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex)) 697 return ExprError(); 698 699 // Initialize the exception result. This implicitly weeds out 700 // abstract types or types with inaccessible copy constructors. 701 702 // C++0x [class.copymove]p31: 703 // When certain criteria are met, an implementation is allowed to omit the 704 // copy/move construction of a class object [...] 705 // 706 // - in a throw-expression, when the operand is the name of a 707 // non-volatile automatic object (other than a function or 708 // catch-clause 709 // parameter) whose scope does not extend beyond the end of the 710 // innermost enclosing try-block (if there is one), the copy/move 711 // operation from the operand to the exception object (15.1) can be 712 // omitted by constructing the automatic object directly into the 713 // exception object 714 const VarDecl *NRVOVariable = nullptr; 715 if (IsThrownVarInScope) 716 NRVOVariable = getCopyElisionCandidate(QualType(), Ex, false); 717 718 InitializedEntity Entity = InitializedEntity::InitializeException( 719 OpLoc, ExceptionObjectTy, 720 /*NRVO=*/NRVOVariable != nullptr); 721 ExprResult Res = PerformMoveOrCopyInitialization( 722 Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope); 723 if (Res.isInvalid()) 724 return ExprError(); 725 Ex = Res.get(); 726 } 727 728 return new (Context) 729 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope); 730 } 731 732 static void 733 collectPublicBases(CXXRecordDecl *RD, 734 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen, 735 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases, 736 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen, 737 bool ParentIsPublic) { 738 for (const CXXBaseSpecifier &BS : RD->bases()) { 739 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 740 bool NewSubobject; 741 // Virtual bases constitute the same subobject. Non-virtual bases are 742 // always distinct subobjects. 743 if (BS.isVirtual()) 744 NewSubobject = VBases.insert(BaseDecl).second; 745 else 746 NewSubobject = true; 747 748 if (NewSubobject) 749 ++SubobjectsSeen[BaseDecl]; 750 751 // Only add subobjects which have public access throughout the entire chain. 752 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public; 753 if (PublicPath) 754 PublicSubobjectsSeen.insert(BaseDecl); 755 756 // Recurse on to each base subobject. 757 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen, 758 PublicPath); 759 } 760 } 761 762 static void getUnambiguousPublicSubobjects( 763 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) { 764 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen; 765 llvm::SmallSet<CXXRecordDecl *, 2> VBases; 766 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen; 767 SubobjectsSeen[RD] = 1; 768 PublicSubobjectsSeen.insert(RD); 769 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen, 770 /*ParentIsPublic=*/true); 771 772 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) { 773 // Skip ambiguous objects. 774 if (SubobjectsSeen[PublicSubobject] > 1) 775 continue; 776 777 Objects.push_back(PublicSubobject); 778 } 779 } 780 781 /// CheckCXXThrowOperand - Validate the operand of a throw. 782 bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, 783 QualType ExceptionObjectTy, Expr *E) { 784 // If the type of the exception would be an incomplete type or a pointer 785 // to an incomplete type other than (cv) void the program is ill-formed. 786 QualType Ty = ExceptionObjectTy; 787 bool isPointer = false; 788 if (const PointerType* Ptr = Ty->getAs<PointerType>()) { 789 Ty = Ptr->getPointeeType(); 790 isPointer = true; 791 } 792 if (!isPointer || !Ty->isVoidType()) { 793 if (RequireCompleteType(ThrowLoc, Ty, 794 isPointer ? diag::err_throw_incomplete_ptr 795 : diag::err_throw_incomplete, 796 E->getSourceRange())) 797 return true; 798 799 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy, 800 diag::err_throw_abstract_type, E)) 801 return true; 802 } 803 804 // If the exception has class type, we need additional handling. 805 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 806 if (!RD) 807 return false; 808 809 // If we are throwing a polymorphic class type or pointer thereof, 810 // exception handling will make use of the vtable. 811 MarkVTableUsed(ThrowLoc, RD); 812 813 // If a pointer is thrown, the referenced object will not be destroyed. 814 if (isPointer) 815 return false; 816 817 // If the class has a destructor, we must be able to call it. 818 if (!RD->hasIrrelevantDestructor()) { 819 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 820 MarkFunctionReferenced(E->getExprLoc(), Destructor); 821 CheckDestructorAccess(E->getExprLoc(), Destructor, 822 PDiag(diag::err_access_dtor_exception) << Ty); 823 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc())) 824 return true; 825 } 826 } 827 828 // The MSVC ABI creates a list of all types which can catch the exception 829 // object. This list also references the appropriate copy constructor to call 830 // if the object is caught by value and has a non-trivial copy constructor. 831 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 832 // We are only interested in the public, unambiguous bases contained within 833 // the exception object. Bases which are ambiguous or otherwise 834 // inaccessible are not catchable types. 835 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects; 836 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects); 837 838 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) { 839 // Attempt to lookup the copy constructor. Various pieces of machinery 840 // will spring into action, like template instantiation, which means this 841 // cannot be a simple walk of the class's decls. Instead, we must perform 842 // lookup and overload resolution. 843 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0); 844 if (!CD) 845 continue; 846 847 // Mark the constructor referenced as it is used by this throw expression. 848 MarkFunctionReferenced(E->getExprLoc(), CD); 849 850 // Skip this copy constructor if it is trivial, we don't need to record it 851 // in the catchable type data. 852 if (CD->isTrivial()) 853 continue; 854 855 // The copy constructor is non-trivial, create a mapping from this class 856 // type to this constructor. 857 // N.B. The selection of copy constructor is not sensitive to this 858 // particular throw-site. Lookup will be performed at the catch-site to 859 // ensure that the copy constructor is, in fact, accessible (via 860 // friendship or any other means). 861 Context.addCopyConstructorForExceptionObject(Subobject, CD); 862 863 // We don't keep the instantiated default argument expressions around so 864 // we must rebuild them here. 865 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) { 866 // Skip any default arguments that we've already instantiated. 867 if (Context.getDefaultArgExprForConstructor(CD, I)) 868 continue; 869 870 Expr *DefaultArg = 871 BuildCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)).get(); 872 Context.addDefaultArgExprForConstructor(CD, I, DefaultArg); 873 } 874 } 875 } 876 877 return false; 878 } 879 880 static QualType adjustCVQualifiersForCXXThisWithinLambda( 881 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy, 882 DeclContext *CurSemaContext, ASTContext &ASTCtx) { 883 884 QualType ClassType = ThisTy->getPointeeType(); 885 LambdaScopeInfo *CurLSI = nullptr; 886 DeclContext *CurDC = CurSemaContext; 887 888 // Iterate through the stack of lambdas starting from the innermost lambda to 889 // the outermost lambda, checking if '*this' is ever captured by copy - since 890 // that could change the cv-qualifiers of the '*this' object. 891 // The object referred to by '*this' starts out with the cv-qualifiers of its 892 // member function. We then start with the innermost lambda and iterate 893 // outward checking to see if any lambda performs a by-copy capture of '*this' 894 // - and if so, any nested lambda must respect the 'constness' of that 895 // capturing lamdbda's call operator. 896 // 897 898 // The issue is that we cannot rely entirely on the FunctionScopeInfo stack 899 // since ScopeInfos are pushed on during parsing and treetransforming. But 900 // since a generic lambda's call operator can be instantiated anywhere (even 901 // end of the TU) we need to be able to examine its enclosing lambdas and so 902 // we use the DeclContext to get a hold of the closure-class and query it for 903 // capture information. The reason we don't just resort to always using the 904 // DeclContext chain is that it is only mature for lambda expressions 905 // enclosing generic lambda's call operators that are being instantiated. 906 907 for (int I = FunctionScopes.size(); 908 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]); 909 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) { 910 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]); 911 912 if (!CurLSI->isCXXThisCaptured()) 913 continue; 914 915 auto C = CurLSI->getCXXThisCapture(); 916 917 if (C.isCopyCapture()) { 918 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask); 919 if (CurLSI->CallOperator->isConst()) 920 ClassType.addConst(); 921 return ASTCtx.getPointerType(ClassType); 922 } 923 } 924 // We've run out of ScopeInfos but check if CurDC is a lambda (which can 925 // happen during instantiation of generic lambdas) 926 if (isLambdaCallOperator(CurDC)) { 927 assert(CurLSI); 928 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator)); 929 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator)); 930 931 auto IsThisCaptured = 932 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) { 933 IsConst = false; 934 IsByCopy = false; 935 for (auto &&C : Closure->captures()) { 936 if (C.capturesThis()) { 937 if (C.getCaptureKind() == LCK_StarThis) 938 IsByCopy = true; 939 if (Closure->getLambdaCallOperator()->isConst()) 940 IsConst = true; 941 return true; 942 } 943 } 944 return false; 945 }; 946 947 bool IsByCopyCapture = false; 948 bool IsConstCapture = false; 949 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent()); 950 while (Closure && 951 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) { 952 if (IsByCopyCapture) { 953 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask); 954 if (IsConstCapture) 955 ClassType.addConst(); 956 return ASTCtx.getPointerType(ClassType); 957 } 958 Closure = isLambdaCallOperator(Closure->getParent()) 959 ? cast<CXXRecordDecl>(Closure->getParent()->getParent()) 960 : nullptr; 961 } 962 } 963 return ASTCtx.getPointerType(ClassType); 964 } 965 966 QualType Sema::getCurrentThisType() { 967 DeclContext *DC = getFunctionLevelDeclContext(); 968 QualType ThisTy = CXXThisTypeOverride; 969 970 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) { 971 if (method && method->isInstance()) 972 ThisTy = method->getThisType(Context); 973 } 974 975 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) && 976 !ActiveTemplateInstantiations.empty()) { 977 978 assert(isa<CXXRecordDecl>(DC) && 979 "Trying to get 'this' type from static method?"); 980 981 // This is a lambda call operator that is being instantiated as a default 982 // initializer. DC must point to the enclosing class type, so we can recover 983 // the 'this' type from it. 984 985 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC)); 986 // There are no cv-qualifiers for 'this' within default initializers, 987 // per [expr.prim.general]p4. 988 ThisTy = Context.getPointerType(ClassTy); 989 } 990 991 // If we are within a lambda's call operator, the cv-qualifiers of 'this' 992 // might need to be adjusted if the lambda or any of its enclosing lambda's 993 // captures '*this' by copy. 994 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext)) 995 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy, 996 CurContext, Context); 997 return ThisTy; 998 } 999 1000 Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S, 1001 Decl *ContextDecl, 1002 unsigned CXXThisTypeQuals, 1003 bool Enabled) 1004 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false) 1005 { 1006 if (!Enabled || !ContextDecl) 1007 return; 1008 1009 CXXRecordDecl *Record = nullptr; 1010 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl)) 1011 Record = Template->getTemplatedDecl(); 1012 else 1013 Record = cast<CXXRecordDecl>(ContextDecl); 1014 1015 // We care only for CVR qualifiers here, so cut everything else. 1016 CXXThisTypeQuals &= Qualifiers::FastMask; 1017 S.CXXThisTypeOverride 1018 = S.Context.getPointerType( 1019 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals)); 1020 1021 this->Enabled = true; 1022 } 1023 1024 1025 Sema::CXXThisScopeRAII::~CXXThisScopeRAII() { 1026 if (Enabled) { 1027 S.CXXThisTypeOverride = OldCXXThisTypeOverride; 1028 } 1029 } 1030 1031 static Expr *captureThis(Sema &S, ASTContext &Context, RecordDecl *RD, 1032 QualType ThisTy, SourceLocation Loc, 1033 const bool ByCopy) { 1034 1035 QualType AdjustedThisTy = ThisTy; 1036 // The type of the corresponding data member (not a 'this' pointer if 'by 1037 // copy'). 1038 QualType CaptureThisFieldTy = ThisTy; 1039 if (ByCopy) { 1040 // If we are capturing the object referred to by '*this' by copy, ignore any 1041 // cv qualifiers inherited from the type of the member function for the type 1042 // of the closure-type's corresponding data member and any use of 'this'. 1043 CaptureThisFieldTy = ThisTy->getPointeeType(); 1044 CaptureThisFieldTy.removeLocalCVRQualifiers(Qualifiers::CVRMask); 1045 AdjustedThisTy = Context.getPointerType(CaptureThisFieldTy); 1046 } 1047 1048 FieldDecl *Field = FieldDecl::Create( 1049 Context, RD, Loc, Loc, nullptr, CaptureThisFieldTy, 1050 Context.getTrivialTypeSourceInfo(CaptureThisFieldTy, Loc), nullptr, false, 1051 ICIS_NoInit); 1052 1053 Field->setImplicit(true); 1054 Field->setAccess(AS_private); 1055 RD->addDecl(Field); 1056 Expr *This = 1057 new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/ true); 1058 if (ByCopy) { 1059 Expr *StarThis = S.CreateBuiltinUnaryOp(Loc, 1060 UO_Deref, 1061 This).get(); 1062 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture( 1063 nullptr, CaptureThisFieldTy, Loc); 1064 InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc); 1065 InitializationSequence Init(S, Entity, InitKind, StarThis); 1066 ExprResult ER = Init.Perform(S, Entity, InitKind, StarThis); 1067 if (ER.isInvalid()) return nullptr; 1068 return ER.get(); 1069 } 1070 return This; 1071 } 1072 1073 bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit, 1074 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt, 1075 const bool ByCopy) { 1076 // We don't need to capture this in an unevaluated context. 1077 if (isUnevaluatedContext() && !Explicit) 1078 return true; 1079 1080 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value"); 1081 1082 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt ? 1083 *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 1084 1085 // Check that we can capture the *enclosing object* (referred to by '*this') 1086 // by the capturing-entity/closure (lambda/block/etc) at 1087 // MaxFunctionScopesIndex-deep on the FunctionScopes stack. 1088 1089 // Note: The *enclosing object* can only be captured by-value by a 1090 // closure that is a lambda, using the explicit notation: 1091 // [*this] { ... }. 1092 // Every other capture of the *enclosing object* results in its by-reference 1093 // capture. 1094 1095 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes 1096 // stack), we can capture the *enclosing object* only if: 1097 // - 'L' has an explicit byref or byval capture of the *enclosing object* 1098 // - or, 'L' has an implicit capture. 1099 // AND 1100 // -- there is no enclosing closure 1101 // -- or, there is some enclosing closure 'E' that has already captured the 1102 // *enclosing object*, and every intervening closure (if any) between 'E' 1103 // and 'L' can implicitly capture the *enclosing object*. 1104 // -- or, every enclosing closure can implicitly capture the 1105 // *enclosing object* 1106 1107 1108 unsigned NumCapturingClosures = 0; 1109 for (unsigned idx = MaxFunctionScopesIndex; idx != 0; idx--) { 1110 if (CapturingScopeInfo *CSI = 1111 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) { 1112 if (CSI->CXXThisCaptureIndex != 0) { 1113 // 'this' is already being captured; there isn't anything more to do. 1114 break; 1115 } 1116 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI); 1117 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) { 1118 // This context can't implicitly capture 'this'; fail out. 1119 if (BuildAndDiagnose) 1120 Diag(Loc, diag::err_this_capture) 1121 << (Explicit && idx == MaxFunctionScopesIndex); 1122 return true; 1123 } 1124 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref || 1125 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval || 1126 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block || 1127 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion || 1128 (Explicit && idx == MaxFunctionScopesIndex)) { 1129 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first 1130 // iteration through can be an explicit capture, all enclosing closures, 1131 // if any, must perform implicit captures. 1132 1133 // This closure can capture 'this'; continue looking upwards. 1134 NumCapturingClosures++; 1135 continue; 1136 } 1137 // This context can't implicitly capture 'this'; fail out. 1138 if (BuildAndDiagnose) 1139 Diag(Loc, diag::err_this_capture) 1140 << (Explicit && idx == MaxFunctionScopesIndex); 1141 return true; 1142 } 1143 break; 1144 } 1145 if (!BuildAndDiagnose) return false; 1146 1147 // If we got here, then the closure at MaxFunctionScopesIndex on the 1148 // FunctionScopes stack, can capture the *enclosing object*, so capture it 1149 // (including implicit by-reference captures in any enclosing closures). 1150 1151 // In the loop below, respect the ByCopy flag only for the closure requesting 1152 // the capture (i.e. first iteration through the loop below). Ignore it for 1153 // all enclosing closure's upto NumCapturingClosures (since they must be 1154 // implicitly capturing the *enclosing object* by reference (see loop 1155 // above)). 1156 assert((!ByCopy || 1157 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && 1158 "Only a lambda can capture the enclosing object (referred to by " 1159 "*this) by copy"); 1160 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated 1161 // contexts. 1162 QualType ThisTy = getCurrentThisType(); 1163 for (unsigned idx = MaxFunctionScopesIndex; NumCapturingClosures; 1164 --idx, --NumCapturingClosures) { 1165 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]); 1166 Expr *ThisExpr = nullptr; 1167 1168 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 1169 // For lambda expressions, build a field and an initializing expression, 1170 // and capture the *enclosing object* by copy only if this is the first 1171 // iteration. 1172 ThisExpr = captureThis(*this, Context, LSI->Lambda, ThisTy, Loc, 1173 ByCopy && idx == MaxFunctionScopesIndex); 1174 1175 } else if (CapturedRegionScopeInfo *RSI 1176 = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx])) 1177 ThisExpr = 1178 captureThis(*this, Context, RSI->TheRecordDecl, ThisTy, Loc, 1179 false/*ByCopy*/); 1180 1181 bool isNested = NumCapturingClosures > 1; 1182 CSI->addThisCapture(isNested, Loc, ThisExpr, ByCopy); 1183 } 1184 return false; 1185 } 1186 1187 ExprResult Sema::ActOnCXXThis(SourceLocation Loc) { 1188 /// C++ 9.3.2: In the body of a non-static member function, the keyword this 1189 /// is a non-lvalue expression whose value is the address of the object for 1190 /// which the function is called. 1191 1192 QualType ThisTy = getCurrentThisType(); 1193 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use); 1194 1195 CheckCXXThisCapture(Loc); 1196 return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false); 1197 } 1198 1199 bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) { 1200 // If we're outside the body of a member function, then we'll have a specified 1201 // type for 'this'. 1202 if (CXXThisTypeOverride.isNull()) 1203 return false; 1204 1205 // Determine whether we're looking into a class that's currently being 1206 // defined. 1207 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl(); 1208 return Class && Class->isBeingDefined(); 1209 } 1210 1211 ExprResult 1212 Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep, 1213 SourceLocation LParenLoc, 1214 MultiExprArg exprs, 1215 SourceLocation RParenLoc) { 1216 if (!TypeRep) 1217 return ExprError(); 1218 1219 TypeSourceInfo *TInfo; 1220 QualType Ty = GetTypeFromParser(TypeRep, &TInfo); 1221 if (!TInfo) 1222 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation()); 1223 1224 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc); 1225 // Avoid creating a non-type-dependent expression that contains typos. 1226 // Non-type-dependent expressions are liable to be discarded without 1227 // checking for embedded typos. 1228 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() && 1229 !Result.get()->isTypeDependent()) 1230 Result = CorrectDelayedTyposInExpr(Result.get()); 1231 return Result; 1232 } 1233 1234 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. 1235 /// Can be interpreted either as function-style casting ("int(x)") 1236 /// or class type construction ("ClassType(x,y,z)") 1237 /// or creation of a value-initialized type ("int()"). 1238 ExprResult 1239 Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo, 1240 SourceLocation LParenLoc, 1241 MultiExprArg Exprs, 1242 SourceLocation RParenLoc) { 1243 QualType Ty = TInfo->getType(); 1244 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc(); 1245 1246 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) { 1247 return CXXUnresolvedConstructExpr::Create(Context, TInfo, LParenLoc, Exprs, 1248 RParenLoc); 1249 } 1250 1251 bool ListInitialization = LParenLoc.isInvalid(); 1252 assert((!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) 1253 && "List initialization must have initializer list as expression."); 1254 SourceRange FullRange = SourceRange(TyBeginLoc, 1255 ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc); 1256 1257 // C++ [expr.type.conv]p1: 1258 // If the expression list is a single expression, the type conversion 1259 // expression is equivalent (in definedness, and if defined in meaning) to the 1260 // corresponding cast expression. 1261 if (Exprs.size() == 1 && !ListInitialization) { 1262 Expr *Arg = Exprs[0]; 1263 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc); 1264 } 1265 1266 // C++14 [expr.type.conv]p2: The expression T(), where T is a 1267 // simple-type-specifier or typename-specifier for a non-array complete 1268 // object type or the (possibly cv-qualified) void type, creates a prvalue 1269 // of the specified type, whose value is that produced by value-initializing 1270 // an object of type T. 1271 QualType ElemTy = Ty; 1272 if (Ty->isArrayType()) { 1273 if (!ListInitialization) 1274 return ExprError(Diag(TyBeginLoc, 1275 diag::err_value_init_for_array_type) << FullRange); 1276 ElemTy = Context.getBaseElementType(Ty); 1277 } 1278 1279 if (!ListInitialization && Ty->isFunctionType()) 1280 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_function_type) 1281 << FullRange); 1282 1283 if (!Ty->isVoidType() && 1284 RequireCompleteType(TyBeginLoc, ElemTy, 1285 diag::err_invalid_incomplete_type_use, FullRange)) 1286 return ExprError(); 1287 1288 if (RequireNonAbstractType(TyBeginLoc, Ty, 1289 diag::err_allocation_of_abstract_type)) 1290 return ExprError(); 1291 1292 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo); 1293 InitializationKind Kind = 1294 Exprs.size() ? ListInitialization 1295 ? InitializationKind::CreateDirectList(TyBeginLoc) 1296 : InitializationKind::CreateDirect(TyBeginLoc, LParenLoc, RParenLoc) 1297 : InitializationKind::CreateValue(TyBeginLoc, LParenLoc, RParenLoc); 1298 InitializationSequence InitSeq(*this, Entity, Kind, Exprs); 1299 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs); 1300 1301 if (Result.isInvalid() || !ListInitialization) 1302 return Result; 1303 1304 Expr *Inner = Result.get(); 1305 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner)) 1306 Inner = BTE->getSubExpr(); 1307 if (!isa<CXXTemporaryObjectExpr>(Inner)) { 1308 // If we created a CXXTemporaryObjectExpr, that node also represents the 1309 // functional cast. Otherwise, create an explicit cast to represent 1310 // the syntactic form of a functional-style cast that was used here. 1311 // 1312 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr 1313 // would give a more consistent AST representation than using a 1314 // CXXTemporaryObjectExpr. It's also weird that the functional cast 1315 // is sometimes handled by initialization and sometimes not. 1316 QualType ResultType = Result.get()->getType(); 1317 Result = CXXFunctionalCastExpr::Create( 1318 Context, ResultType, Expr::getValueKindForType(TInfo->getType()), TInfo, 1319 CK_NoOp, Result.get(), /*Path=*/nullptr, LParenLoc, RParenLoc); 1320 } 1321 1322 return Result; 1323 } 1324 1325 /// \brief Determine whether the given function is a non-placement 1326 /// deallocation function. 1327 static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) { 1328 if (FD->isInvalidDecl()) 1329 return false; 1330 1331 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD)) 1332 return Method->isUsualDeallocationFunction(); 1333 1334 if (FD->getOverloadedOperator() != OO_Delete && 1335 FD->getOverloadedOperator() != OO_Array_Delete) 1336 return false; 1337 1338 unsigned UsualParams = 1; 1339 1340 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() && 1341 S.Context.hasSameUnqualifiedType( 1342 FD->getParamDecl(UsualParams)->getType(), 1343 S.Context.getSizeType())) 1344 ++UsualParams; 1345 1346 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() && 1347 S.Context.hasSameUnqualifiedType( 1348 FD->getParamDecl(UsualParams)->getType(), 1349 S.Context.getTypeDeclType(S.getStdAlignValT()))) 1350 ++UsualParams; 1351 1352 return UsualParams == FD->getNumParams(); 1353 } 1354 1355 namespace { 1356 struct UsualDeallocFnInfo { 1357 UsualDeallocFnInfo() : Found(), FD(nullptr) {} 1358 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found) 1359 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())), 1360 HasSizeT(false), HasAlignValT(false), CUDAPref(Sema::CFP_Native) { 1361 // A function template declaration is never a usual deallocation function. 1362 if (!FD) 1363 return; 1364 if (FD->getNumParams() == 3) 1365 HasAlignValT = HasSizeT = true; 1366 else if (FD->getNumParams() == 2) { 1367 HasSizeT = FD->getParamDecl(1)->getType()->isIntegerType(); 1368 HasAlignValT = !HasSizeT; 1369 } 1370 1371 // In CUDA, determine how much we'd like / dislike to call this. 1372 if (S.getLangOpts().CUDA) 1373 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 1374 CUDAPref = S.IdentifyCUDAPreference(Caller, FD); 1375 } 1376 1377 operator bool() const { return FD; } 1378 1379 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize, 1380 bool WantAlign) const { 1381 // C++17 [expr.delete]p10: 1382 // If the type has new-extended alignment, a function with a parameter 1383 // of type std::align_val_t is preferred; otherwise a function without 1384 // such a parameter is preferred 1385 if (HasAlignValT != Other.HasAlignValT) 1386 return HasAlignValT == WantAlign; 1387 1388 if (HasSizeT != Other.HasSizeT) 1389 return HasSizeT == WantSize; 1390 1391 // Use CUDA call preference as a tiebreaker. 1392 return CUDAPref > Other.CUDAPref; 1393 } 1394 1395 DeclAccessPair Found; 1396 FunctionDecl *FD; 1397 bool HasSizeT, HasAlignValT; 1398 Sema::CUDAFunctionPreference CUDAPref; 1399 }; 1400 } 1401 1402 /// Determine whether a type has new-extended alignment. This may be called when 1403 /// the type is incomplete (for a delete-expression with an incomplete pointee 1404 /// type), in which case it will conservatively return false if the alignment is 1405 /// not known. 1406 static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) { 1407 return S.getLangOpts().AlignedAllocation && 1408 S.getASTContext().getTypeAlignIfKnown(AllocType) > 1409 S.getASTContext().getTargetInfo().getNewAlign(); 1410 } 1411 1412 /// Select the correct "usual" deallocation function to use from a selection of 1413 /// deallocation functions (either global or class-scope). 1414 static UsualDeallocFnInfo resolveDeallocationOverload( 1415 Sema &S, LookupResult &R, bool WantSize, bool WantAlign, 1416 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) { 1417 UsualDeallocFnInfo Best; 1418 1419 for (auto I = R.begin(), E = R.end(); I != E; ++I) { 1420 UsualDeallocFnInfo Info(S, I.getPair()); 1421 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) || 1422 Info.CUDAPref == Sema::CFP_Never) 1423 continue; 1424 1425 if (!Best) { 1426 Best = Info; 1427 if (BestFns) 1428 BestFns->push_back(Info); 1429 continue; 1430 } 1431 1432 if (Best.isBetterThan(Info, WantSize, WantAlign)) 1433 continue; 1434 1435 // If more than one preferred function is found, all non-preferred 1436 // functions are eliminated from further consideration. 1437 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign)) 1438 BestFns->clear(); 1439 1440 Best = Info; 1441 if (BestFns) 1442 BestFns->push_back(Info); 1443 } 1444 1445 return Best; 1446 } 1447 1448 /// Determine whether a given type is a class for which 'delete[]' would call 1449 /// a member 'operator delete[]' with a 'size_t' parameter. This implies that 1450 /// we need to store the array size (even if the type is 1451 /// trivially-destructible). 1452 static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc, 1453 QualType allocType) { 1454 const RecordType *record = 1455 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>(); 1456 if (!record) return false; 1457 1458 // Try to find an operator delete[] in class scope. 1459 1460 DeclarationName deleteName = 1461 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete); 1462 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName); 1463 S.LookupQualifiedName(ops, record->getDecl()); 1464 1465 // We're just doing this for information. 1466 ops.suppressDiagnostics(); 1467 1468 // Very likely: there's no operator delete[]. 1469 if (ops.empty()) return false; 1470 1471 // If it's ambiguous, it should be illegal to call operator delete[] 1472 // on this thing, so it doesn't matter if we allocate extra space or not. 1473 if (ops.isAmbiguous()) return false; 1474 1475 // C++17 [expr.delete]p10: 1476 // If the deallocation functions have class scope, the one without a 1477 // parameter of type std::size_t is selected. 1478 auto Best = resolveDeallocationOverload( 1479 S, ops, /*WantSize*/false, 1480 /*WantAlign*/hasNewExtendedAlignment(S, allocType)); 1481 return Best && Best.HasSizeT; 1482 } 1483 1484 /// \brief Parsed a C++ 'new' expression (C++ 5.3.4). 1485 /// 1486 /// E.g.: 1487 /// @code new (memory) int[size][4] @endcode 1488 /// or 1489 /// @code ::new Foo(23, "hello") @endcode 1490 /// 1491 /// \param StartLoc The first location of the expression. 1492 /// \param UseGlobal True if 'new' was prefixed with '::'. 1493 /// \param PlacementLParen Opening paren of the placement arguments. 1494 /// \param PlacementArgs Placement new arguments. 1495 /// \param PlacementRParen Closing paren of the placement arguments. 1496 /// \param TypeIdParens If the type is in parens, the source range. 1497 /// \param D The type to be allocated, as well as array dimensions. 1498 /// \param Initializer The initializing expression or initializer-list, or null 1499 /// if there is none. 1500 ExprResult 1501 Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 1502 SourceLocation PlacementLParen, MultiExprArg PlacementArgs, 1503 SourceLocation PlacementRParen, SourceRange TypeIdParens, 1504 Declarator &D, Expr *Initializer) { 1505 bool TypeContainsAuto = D.getDeclSpec().containsPlaceholderType(); 1506 1507 Expr *ArraySize = nullptr; 1508 // If the specified type is an array, unwrap it and save the expression. 1509 if (D.getNumTypeObjects() > 0 && 1510 D.getTypeObject(0).Kind == DeclaratorChunk::Array) { 1511 DeclaratorChunk &Chunk = D.getTypeObject(0); 1512 if (TypeContainsAuto) 1513 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto) 1514 << D.getSourceRange()); 1515 if (Chunk.Arr.hasStatic) 1516 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new) 1517 << D.getSourceRange()); 1518 if (!Chunk.Arr.NumElts) 1519 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size) 1520 << D.getSourceRange()); 1521 1522 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts); 1523 D.DropFirstTypeObject(); 1524 } 1525 1526 // Every dimension shall be of constant size. 1527 if (ArraySize) { 1528 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) { 1529 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array) 1530 break; 1531 1532 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr; 1533 if (Expr *NumElts = (Expr *)Array.NumElts) { 1534 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) { 1535 if (getLangOpts().CPlusPlus14) { 1536 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator 1537 // shall be a converted constant expression (5.19) of type std::size_t 1538 // and shall evaluate to a strictly positive value. 1539 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 1540 assert(IntWidth && "Builtin type of size 0?"); 1541 llvm::APSInt Value(IntWidth); 1542 Array.NumElts 1543 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value, 1544 CCEK_NewExpr) 1545 .get(); 1546 } else { 1547 Array.NumElts 1548 = VerifyIntegerConstantExpression(NumElts, nullptr, 1549 diag::err_new_array_nonconst) 1550 .get(); 1551 } 1552 if (!Array.NumElts) 1553 return ExprError(); 1554 } 1555 } 1556 } 1557 } 1558 1559 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr); 1560 QualType AllocType = TInfo->getType(); 1561 if (D.isInvalidType()) 1562 return ExprError(); 1563 1564 SourceRange DirectInitRange; 1565 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) 1566 DirectInitRange = List->getSourceRange(); 1567 1568 return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal, 1569 PlacementLParen, 1570 PlacementArgs, 1571 PlacementRParen, 1572 TypeIdParens, 1573 AllocType, 1574 TInfo, 1575 ArraySize, 1576 DirectInitRange, 1577 Initializer, 1578 TypeContainsAuto); 1579 } 1580 1581 static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style, 1582 Expr *Init) { 1583 if (!Init) 1584 return true; 1585 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) 1586 return PLE->getNumExprs() == 0; 1587 if (isa<ImplicitValueInitExpr>(Init)) 1588 return true; 1589 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) 1590 return !CCE->isListInitialization() && 1591 CCE->getConstructor()->isDefaultConstructor(); 1592 else if (Style == CXXNewExpr::ListInit) { 1593 assert(isa<InitListExpr>(Init) && 1594 "Shouldn't create list CXXConstructExprs for arrays."); 1595 return true; 1596 } 1597 return false; 1598 } 1599 1600 ExprResult 1601 Sema::BuildCXXNew(SourceRange Range, bool UseGlobal, 1602 SourceLocation PlacementLParen, 1603 MultiExprArg PlacementArgs, 1604 SourceLocation PlacementRParen, 1605 SourceRange TypeIdParens, 1606 QualType AllocType, 1607 TypeSourceInfo *AllocTypeInfo, 1608 Expr *ArraySize, 1609 SourceRange DirectInitRange, 1610 Expr *Initializer, 1611 bool TypeMayContainAuto) { 1612 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange(); 1613 SourceLocation StartLoc = Range.getBegin(); 1614 1615 CXXNewExpr::InitializationStyle initStyle; 1616 if (DirectInitRange.isValid()) { 1617 assert(Initializer && "Have parens but no initializer."); 1618 initStyle = CXXNewExpr::CallInit; 1619 } else if (Initializer && isa<InitListExpr>(Initializer)) 1620 initStyle = CXXNewExpr::ListInit; 1621 else { 1622 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) || 1623 isa<CXXConstructExpr>(Initializer)) && 1624 "Initializer expression that cannot have been implicitly created."); 1625 initStyle = CXXNewExpr::NoInit; 1626 } 1627 1628 Expr **Inits = &Initializer; 1629 unsigned NumInits = Initializer ? 1 : 0; 1630 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) { 1631 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init"); 1632 Inits = List->getExprs(); 1633 NumInits = List->getNumExprs(); 1634 } 1635 1636 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for. 1637 if (TypeMayContainAuto && AllocType->isUndeducedType()) { 1638 if (initStyle == CXXNewExpr::NoInit || NumInits == 0) 1639 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg) 1640 << AllocType << TypeRange); 1641 if (initStyle == CXXNewExpr::ListInit || 1642 (NumInits == 1 && isa<InitListExpr>(Inits[0]))) 1643 return ExprError(Diag(Inits[0]->getLocStart(), 1644 diag::err_auto_new_list_init) 1645 << AllocType << TypeRange); 1646 if (NumInits > 1) { 1647 Expr *FirstBad = Inits[1]; 1648 return ExprError(Diag(FirstBad->getLocStart(), 1649 diag::err_auto_new_ctor_multiple_expressions) 1650 << AllocType << TypeRange); 1651 } 1652 Expr *Deduce = Inits[0]; 1653 QualType DeducedType; 1654 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed) 1655 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure) 1656 << AllocType << Deduce->getType() 1657 << TypeRange << Deduce->getSourceRange()); 1658 if (DeducedType.isNull()) 1659 return ExprError(); 1660 AllocType = DeducedType; 1661 } 1662 1663 // Per C++0x [expr.new]p5, the type being constructed may be a 1664 // typedef of an array type. 1665 if (!ArraySize) { 1666 if (const ConstantArrayType *Array 1667 = Context.getAsConstantArrayType(AllocType)) { 1668 ArraySize = IntegerLiteral::Create(Context, Array->getSize(), 1669 Context.getSizeType(), 1670 TypeRange.getEnd()); 1671 AllocType = Array->getElementType(); 1672 } 1673 } 1674 1675 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange)) 1676 return ExprError(); 1677 1678 if (initStyle == CXXNewExpr::ListInit && 1679 isStdInitializerList(AllocType, nullptr)) { 1680 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(), 1681 diag::warn_dangling_std_initializer_list) 1682 << /*at end of FE*/0 << Inits[0]->getSourceRange(); 1683 } 1684 1685 // In ARC, infer 'retaining' for the allocated 1686 if (getLangOpts().ObjCAutoRefCount && 1687 AllocType.getObjCLifetime() == Qualifiers::OCL_None && 1688 AllocType->isObjCLifetimeType()) { 1689 AllocType = Context.getLifetimeQualifiedType(AllocType, 1690 AllocType->getObjCARCImplicitLifetime()); 1691 } 1692 1693 QualType ResultType = Context.getPointerType(AllocType); 1694 1695 if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) { 1696 ExprResult result = CheckPlaceholderExpr(ArraySize); 1697 if (result.isInvalid()) return ExprError(); 1698 ArraySize = result.get(); 1699 } 1700 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have 1701 // integral or enumeration type with a non-negative value." 1702 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped 1703 // enumeration type, or a class type for which a single non-explicit 1704 // conversion function to integral or unscoped enumeration type exists. 1705 // C++1y [expr.new]p6: The expression [...] is implicitly converted to 1706 // std::size_t. 1707 llvm::Optional<uint64_t> KnownArraySize; 1708 if (ArraySize && !ArraySize->isTypeDependent()) { 1709 ExprResult ConvertedSize; 1710 if (getLangOpts().CPlusPlus14) { 1711 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?"); 1712 1713 ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(), 1714 AA_Converting); 1715 1716 if (!ConvertedSize.isInvalid() && 1717 ArraySize->getType()->getAs<RecordType>()) 1718 // Diagnose the compatibility of this conversion. 1719 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion) 1720 << ArraySize->getType() << 0 << "'size_t'"; 1721 } else { 1722 class SizeConvertDiagnoser : public ICEConvertDiagnoser { 1723 protected: 1724 Expr *ArraySize; 1725 1726 public: 1727 SizeConvertDiagnoser(Expr *ArraySize) 1728 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false), 1729 ArraySize(ArraySize) {} 1730 1731 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 1732 QualType T) override { 1733 return S.Diag(Loc, diag::err_array_size_not_integral) 1734 << S.getLangOpts().CPlusPlus11 << T; 1735 } 1736 1737 SemaDiagnosticBuilder diagnoseIncomplete( 1738 Sema &S, SourceLocation Loc, QualType T) override { 1739 return S.Diag(Loc, diag::err_array_size_incomplete_type) 1740 << T << ArraySize->getSourceRange(); 1741 } 1742 1743 SemaDiagnosticBuilder diagnoseExplicitConv( 1744 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 1745 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy; 1746 } 1747 1748 SemaDiagnosticBuilder noteExplicitConv( 1749 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 1750 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion) 1751 << ConvTy->isEnumeralType() << ConvTy; 1752 } 1753 1754 SemaDiagnosticBuilder diagnoseAmbiguous( 1755 Sema &S, SourceLocation Loc, QualType T) override { 1756 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T; 1757 } 1758 1759 SemaDiagnosticBuilder noteAmbiguous( 1760 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 1761 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion) 1762 << ConvTy->isEnumeralType() << ConvTy; 1763 } 1764 1765 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, 1766 QualType T, 1767 QualType ConvTy) override { 1768 return S.Diag(Loc, 1769 S.getLangOpts().CPlusPlus11 1770 ? diag::warn_cxx98_compat_array_size_conversion 1771 : diag::ext_array_size_conversion) 1772 << T << ConvTy->isEnumeralType() << ConvTy; 1773 } 1774 } SizeDiagnoser(ArraySize); 1775 1776 ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize, 1777 SizeDiagnoser); 1778 } 1779 if (ConvertedSize.isInvalid()) 1780 return ExprError(); 1781 1782 ArraySize = ConvertedSize.get(); 1783 QualType SizeType = ArraySize->getType(); 1784 1785 if (!SizeType->isIntegralOrUnscopedEnumerationType()) 1786 return ExprError(); 1787 1788 // C++98 [expr.new]p7: 1789 // The expression in a direct-new-declarator shall have integral type 1790 // with a non-negative value. 1791 // 1792 // Let's see if this is a constant < 0. If so, we reject it out of hand, 1793 // per CWG1464. Otherwise, if it's not a constant, we must have an 1794 // unparenthesized array type. 1795 if (!ArraySize->isValueDependent()) { 1796 llvm::APSInt Value; 1797 // We've already performed any required implicit conversion to integer or 1798 // unscoped enumeration type. 1799 // FIXME: Per CWG1464, we are required to check the value prior to 1800 // converting to size_t. This will never find a negative array size in 1801 // C++14 onwards, because Value is always unsigned here! 1802 if (ArraySize->isIntegerConstantExpr(Value, Context)) { 1803 if (Value.isSigned() && Value.isNegative()) { 1804 return ExprError(Diag(ArraySize->getLocStart(), 1805 diag::err_typecheck_negative_array_size) 1806 << ArraySize->getSourceRange()); 1807 } 1808 1809 if (!AllocType->isDependentType()) { 1810 unsigned ActiveSizeBits = 1811 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value); 1812 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) 1813 return ExprError(Diag(ArraySize->getLocStart(), 1814 diag::err_array_too_large) 1815 << Value.toString(10) 1816 << ArraySize->getSourceRange()); 1817 } 1818 1819 KnownArraySize = Value.getZExtValue(); 1820 } else if (TypeIdParens.isValid()) { 1821 // Can't have dynamic array size when the type-id is in parentheses. 1822 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst) 1823 << ArraySize->getSourceRange() 1824 << FixItHint::CreateRemoval(TypeIdParens.getBegin()) 1825 << FixItHint::CreateRemoval(TypeIdParens.getEnd()); 1826 1827 TypeIdParens = SourceRange(); 1828 } 1829 } 1830 1831 // Note that we do *not* convert the argument in any way. It can 1832 // be signed, larger than size_t, whatever. 1833 } 1834 1835 FunctionDecl *OperatorNew = nullptr; 1836 FunctionDecl *OperatorDelete = nullptr; 1837 unsigned Alignment = 1838 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType); 1839 unsigned NewAlignment = Context.getTargetInfo().getNewAlign(); 1840 bool PassAlignment = getLangOpts().AlignedAllocation && 1841 Alignment > NewAlignment; 1842 1843 if (!AllocType->isDependentType() && 1844 !Expr::hasAnyTypeDependentArguments(PlacementArgs) && 1845 FindAllocationFunctions(StartLoc, 1846 SourceRange(PlacementLParen, PlacementRParen), 1847 UseGlobal, AllocType, ArraySize, PassAlignment, 1848 PlacementArgs, OperatorNew, OperatorDelete)) 1849 return ExprError(); 1850 1851 // If this is an array allocation, compute whether the usual array 1852 // deallocation function for the type has a size_t parameter. 1853 bool UsualArrayDeleteWantsSize = false; 1854 if (ArraySize && !AllocType->isDependentType()) 1855 UsualArrayDeleteWantsSize = 1856 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType); 1857 1858 SmallVector<Expr *, 8> AllPlaceArgs; 1859 if (OperatorNew) { 1860 const FunctionProtoType *Proto = 1861 OperatorNew->getType()->getAs<FunctionProtoType>(); 1862 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction 1863 : VariadicDoesNotApply; 1864 1865 // We've already converted the placement args, just fill in any default 1866 // arguments. Skip the first parameter because we don't have a corresponding 1867 // argument. Skip the second parameter too if we're passing in the 1868 // alignment; we've already filled it in. 1869 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto, 1870 PassAlignment ? 2 : 1, PlacementArgs, 1871 AllPlaceArgs, CallType)) 1872 return ExprError(); 1873 1874 if (!AllPlaceArgs.empty()) 1875 PlacementArgs = AllPlaceArgs; 1876 1877 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument. 1878 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs); 1879 1880 // FIXME: Missing call to CheckFunctionCall or equivalent 1881 1882 // Warn if the type is over-aligned and is being allocated by (unaligned) 1883 // global operator new. 1884 if (PlacementArgs.empty() && !PassAlignment && 1885 (OperatorNew->isImplicit() || 1886 (OperatorNew->getLocStart().isValid() && 1887 getSourceManager().isInSystemHeader(OperatorNew->getLocStart())))) { 1888 if (Alignment > NewAlignment) 1889 Diag(StartLoc, diag::warn_overaligned_type) 1890 << AllocType 1891 << unsigned(Alignment / Context.getCharWidth()) 1892 << unsigned(NewAlignment / Context.getCharWidth()); 1893 } 1894 } 1895 1896 // Array 'new' can't have any initializers except empty parentheses. 1897 // Initializer lists are also allowed, in C++11. Rely on the parser for the 1898 // dialect distinction. 1899 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) { 1900 SourceRange InitRange(Inits[0]->getLocStart(), 1901 Inits[NumInits - 1]->getLocEnd()); 1902 Diag(StartLoc, diag::err_new_array_init_args) << InitRange; 1903 return ExprError(); 1904 } 1905 1906 // If we can perform the initialization, and we've not already done so, 1907 // do it now. 1908 if (!AllocType->isDependentType() && 1909 !Expr::hasAnyTypeDependentArguments( 1910 llvm::makeArrayRef(Inits, NumInits))) { 1911 // The type we initialize is the complete type, including the array bound. 1912 QualType InitType; 1913 if (KnownArraySize) 1914 InitType = Context.getConstantArrayType( 1915 AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()), 1916 *KnownArraySize), 1917 ArrayType::Normal, 0); 1918 else if (ArraySize) 1919 InitType = 1920 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0); 1921 else 1922 InitType = AllocType; 1923 1924 // C++11 [expr.new]p15: 1925 // A new-expression that creates an object of type T initializes that 1926 // object as follows: 1927 InitializationKind Kind 1928 // - If the new-initializer is omitted, the object is default- 1929 // initialized (8.5); if no initialization is performed, 1930 // the object has indeterminate value 1931 = initStyle == CXXNewExpr::NoInit 1932 ? InitializationKind::CreateDefault(TypeRange.getBegin()) 1933 // - Otherwise, the new-initializer is interpreted according to the 1934 // initialization rules of 8.5 for direct-initialization. 1935 : initStyle == CXXNewExpr::ListInit 1936 ? InitializationKind::CreateDirectList(TypeRange.getBegin()) 1937 : InitializationKind::CreateDirect(TypeRange.getBegin(), 1938 DirectInitRange.getBegin(), 1939 DirectInitRange.getEnd()); 1940 1941 InitializedEntity Entity 1942 = InitializedEntity::InitializeNew(StartLoc, InitType); 1943 InitializationSequence InitSeq(*this, Entity, Kind, 1944 MultiExprArg(Inits, NumInits)); 1945 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, 1946 MultiExprArg(Inits, NumInits)); 1947 if (FullInit.isInvalid()) 1948 return ExprError(); 1949 1950 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because 1951 // we don't want the initialized object to be destructed. 1952 // FIXME: We should not create these in the first place. 1953 if (CXXBindTemporaryExpr *Binder = 1954 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get())) 1955 FullInit = Binder->getSubExpr(); 1956 1957 Initializer = FullInit.get(); 1958 } 1959 1960 // Mark the new and delete operators as referenced. 1961 if (OperatorNew) { 1962 if (DiagnoseUseOfDecl(OperatorNew, StartLoc)) 1963 return ExprError(); 1964 MarkFunctionReferenced(StartLoc, OperatorNew); 1965 } 1966 if (OperatorDelete) { 1967 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc)) 1968 return ExprError(); 1969 MarkFunctionReferenced(StartLoc, OperatorDelete); 1970 } 1971 1972 // C++0x [expr.new]p17: 1973 // If the new expression creates an array of objects of class type, 1974 // access and ambiguity control are done for the destructor. 1975 QualType BaseAllocType = Context.getBaseElementType(AllocType); 1976 if (ArraySize && !BaseAllocType->isDependentType()) { 1977 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) { 1978 if (CXXDestructorDecl *dtor = LookupDestructor( 1979 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) { 1980 MarkFunctionReferenced(StartLoc, dtor); 1981 CheckDestructorAccess(StartLoc, dtor, 1982 PDiag(diag::err_access_dtor) 1983 << BaseAllocType); 1984 if (DiagnoseUseOfDecl(dtor, StartLoc)) 1985 return ExprError(); 1986 } 1987 } 1988 } 1989 1990 return new (Context) 1991 CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete, PassAlignment, 1992 UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens, 1993 ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo, 1994 Range, DirectInitRange); 1995 } 1996 1997 /// \brief Checks that a type is suitable as the allocated type 1998 /// in a new-expression. 1999 bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc, 2000 SourceRange R) { 2001 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an 2002 // abstract class type or array thereof. 2003 if (AllocType->isFunctionType()) 2004 return Diag(Loc, diag::err_bad_new_type) 2005 << AllocType << 0 << R; 2006 else if (AllocType->isReferenceType()) 2007 return Diag(Loc, diag::err_bad_new_type) 2008 << AllocType << 1 << R; 2009 else if (!AllocType->isDependentType() && 2010 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R)) 2011 return true; 2012 else if (RequireNonAbstractType(Loc, AllocType, 2013 diag::err_allocation_of_abstract_type)) 2014 return true; 2015 else if (AllocType->isVariablyModifiedType()) 2016 return Diag(Loc, diag::err_variably_modified_new_type) 2017 << AllocType; 2018 else if (unsigned AddressSpace = AllocType.getAddressSpace()) 2019 return Diag(Loc, diag::err_address_space_qualified_new) 2020 << AllocType.getUnqualifiedType() << AddressSpace; 2021 else if (getLangOpts().ObjCAutoRefCount) { 2022 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) { 2023 QualType BaseAllocType = Context.getBaseElementType(AT); 2024 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None && 2025 BaseAllocType->isObjCLifetimeType()) 2026 return Diag(Loc, diag::err_arc_new_array_without_ownership) 2027 << BaseAllocType; 2028 } 2029 } 2030 2031 return false; 2032 } 2033 2034 static bool 2035 resolveAllocationOverload(Sema &S, LookupResult &R, SourceRange Range, 2036 SmallVectorImpl<Expr *> &Args, bool &PassAlignment, 2037 FunctionDecl *&Operator, 2038 OverloadCandidateSet *AlignedCandidates = nullptr, 2039 Expr *AlignArg = nullptr) { 2040 OverloadCandidateSet Candidates(R.getNameLoc(), 2041 OverloadCandidateSet::CSK_Normal); 2042 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end(); 2043 Alloc != AllocEnd; ++Alloc) { 2044 // Even member operator new/delete are implicitly treated as 2045 // static, so don't use AddMemberCandidate. 2046 NamedDecl *D = (*Alloc)->getUnderlyingDecl(); 2047 2048 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) { 2049 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(), 2050 /*ExplicitTemplateArgs=*/nullptr, Args, 2051 Candidates, 2052 /*SuppressUserConversions=*/false); 2053 continue; 2054 } 2055 2056 FunctionDecl *Fn = cast<FunctionDecl>(D); 2057 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates, 2058 /*SuppressUserConversions=*/false); 2059 } 2060 2061 // Do the resolution. 2062 OverloadCandidateSet::iterator Best; 2063 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) { 2064 case OR_Success: { 2065 // Got one! 2066 FunctionDecl *FnDecl = Best->Function; 2067 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(), 2068 Best->FoundDecl) == Sema::AR_inaccessible) 2069 return true; 2070 2071 Operator = FnDecl; 2072 return false; 2073 } 2074 2075 case OR_No_Viable_Function: 2076 // C++17 [expr.new]p13: 2077 // If no matching function is found and the allocated object type has 2078 // new-extended alignment, the alignment argument is removed from the 2079 // argument list, and overload resolution is performed again. 2080 if (PassAlignment) { 2081 PassAlignment = false; 2082 AlignArg = Args[1]; 2083 Args.erase(Args.begin() + 1); 2084 return resolveAllocationOverload(S, R, Range, Args, PassAlignment, 2085 Operator, &Candidates, AlignArg); 2086 } 2087 2088 // MSVC will fall back on trying to find a matching global operator new 2089 // if operator new[] cannot be found. Also, MSVC will leak by not 2090 // generating a call to operator delete or operator delete[], but we 2091 // will not replicate that bug. 2092 // FIXME: Find out how this interacts with the std::align_val_t fallback 2093 // once MSVC implements it. 2094 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New && 2095 S.Context.getLangOpts().MSVCCompat) { 2096 R.clear(); 2097 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New)); 2098 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl()); 2099 // FIXME: This will give bad diagnostics pointing at the wrong functions. 2100 return resolveAllocationOverload(S, R, Range, Args, PassAlignment, 2101 Operator, nullptr); 2102 } 2103 2104 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call) 2105 << R.getLookupName() << Range; 2106 2107 // If we have aligned candidates, only note the align_val_t candidates 2108 // from AlignedCandidates and the non-align_val_t candidates from 2109 // Candidates. 2110 if (AlignedCandidates) { 2111 auto IsAligned = [](OverloadCandidate &C) { 2112 return C.Function->getNumParams() > 1 && 2113 C.Function->getParamDecl(1)->getType()->isAlignValT(); 2114 }; 2115 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); }; 2116 2117 // This was an overaligned allocation, so list the aligned candidates 2118 // first. 2119 Args.insert(Args.begin() + 1, AlignArg); 2120 AlignedCandidates->NoteCandidates(S, OCD_AllCandidates, Args, "", 2121 R.getNameLoc(), IsAligned); 2122 Args.erase(Args.begin() + 1); 2123 Candidates.NoteCandidates(S, OCD_AllCandidates, Args, "", R.getNameLoc(), 2124 IsUnaligned); 2125 } else { 2126 Candidates.NoteCandidates(S, OCD_AllCandidates, Args); 2127 } 2128 return true; 2129 2130 case OR_Ambiguous: 2131 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) 2132 << R.getLookupName() << Range; 2133 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args); 2134 return true; 2135 2136 case OR_Deleted: { 2137 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call) 2138 << Best->Function->isDeleted() 2139 << R.getLookupName() 2140 << S.getDeletedOrUnavailableSuffix(Best->Function) 2141 << Range; 2142 Candidates.NoteCandidates(S, OCD_AllCandidates, Args); 2143 return true; 2144 } 2145 } 2146 llvm_unreachable("Unreachable, bad result from BestViableFunction"); 2147 } 2148 2149 2150 /// FindAllocationFunctions - Finds the overloads of operator new and delete 2151 /// that are appropriate for the allocation. 2152 bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 2153 bool UseGlobal, QualType AllocType, 2154 bool IsArray, bool &PassAlignment, 2155 MultiExprArg PlaceArgs, 2156 FunctionDecl *&OperatorNew, 2157 FunctionDecl *&OperatorDelete) { 2158 // --- Choosing an allocation function --- 2159 // C++ 5.3.4p8 - 14 & 18 2160 // 1) If UseGlobal is true, only look in the global scope. Else, also look 2161 // in the scope of the allocated class. 2162 // 2) If an array size is given, look for operator new[], else look for 2163 // operator new. 2164 // 3) The first argument is always size_t. Append the arguments from the 2165 // placement form. 2166 2167 SmallVector<Expr*, 8> AllocArgs; 2168 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size()); 2169 2170 // We don't care about the actual value of these arguments. 2171 // FIXME: Should the Sema create the expression and embed it in the syntax 2172 // tree? Or should the consumer just recalculate the value? 2173 // FIXME: Using a dummy value will interact poorly with attribute enable_if. 2174 IntegerLiteral Size(Context, llvm::APInt::getNullValue( 2175 Context.getTargetInfo().getPointerWidth(0)), 2176 Context.getSizeType(), 2177 SourceLocation()); 2178 AllocArgs.push_back(&Size); 2179 2180 QualType AlignValT = Context.VoidTy; 2181 if (PassAlignment) { 2182 DeclareGlobalNewDelete(); 2183 AlignValT = Context.getTypeDeclType(getStdAlignValT()); 2184 } 2185 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation()); 2186 if (PassAlignment) 2187 AllocArgs.push_back(&Align); 2188 2189 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end()); 2190 2191 // C++ [expr.new]p8: 2192 // If the allocated type is a non-array type, the allocation 2193 // function's name is operator new and the deallocation function's 2194 // name is operator delete. If the allocated type is an array 2195 // type, the allocation function's name is operator new[] and the 2196 // deallocation function's name is operator delete[]. 2197 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName( 2198 IsArray ? OO_Array_New : OO_New); 2199 2200 QualType AllocElemType = Context.getBaseElementType(AllocType); 2201 2202 // Find the allocation function. 2203 { 2204 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName); 2205 2206 // C++1z [expr.new]p9: 2207 // If the new-expression begins with a unary :: operator, the allocation 2208 // function's name is looked up in the global scope. Otherwise, if the 2209 // allocated type is a class type T or array thereof, the allocation 2210 // function's name is looked up in the scope of T. 2211 if (AllocElemType->isRecordType() && !UseGlobal) 2212 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl()); 2213 2214 // We can see ambiguity here if the allocation function is found in 2215 // multiple base classes. 2216 if (R.isAmbiguous()) 2217 return true; 2218 2219 // If this lookup fails to find the name, or if the allocated type is not 2220 // a class type, the allocation function's name is looked up in the 2221 // global scope. 2222 if (R.empty()) 2223 LookupQualifiedName(R, Context.getTranslationUnitDecl()); 2224 2225 assert(!R.empty() && "implicitly declared allocation functions not found"); 2226 assert(!R.isAmbiguous() && "global allocation functions are ambiguous"); 2227 2228 // We do our own custom access checks below. 2229 R.suppressDiagnostics(); 2230 2231 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment, 2232 OperatorNew)) 2233 return true; 2234 } 2235 2236 // We don't need an operator delete if we're running under -fno-exceptions. 2237 if (!getLangOpts().Exceptions) { 2238 OperatorDelete = nullptr; 2239 return false; 2240 } 2241 2242 // Note, the name of OperatorNew might have been changed from array to 2243 // non-array by resolveAllocationOverload. 2244 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( 2245 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New 2246 ? OO_Array_Delete 2247 : OO_Delete); 2248 2249 // C++ [expr.new]p19: 2250 // 2251 // If the new-expression begins with a unary :: operator, the 2252 // deallocation function's name is looked up in the global 2253 // scope. Otherwise, if the allocated type is a class type T or an 2254 // array thereof, the deallocation function's name is looked up in 2255 // the scope of T. If this lookup fails to find the name, or if 2256 // the allocated type is not a class type or array thereof, the 2257 // deallocation function's name is looked up in the global scope. 2258 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName); 2259 if (AllocElemType->isRecordType() && !UseGlobal) { 2260 CXXRecordDecl *RD 2261 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl()); 2262 LookupQualifiedName(FoundDelete, RD); 2263 } 2264 if (FoundDelete.isAmbiguous()) 2265 return true; // FIXME: clean up expressions? 2266 2267 bool FoundGlobalDelete = FoundDelete.empty(); 2268 if (FoundDelete.empty()) { 2269 DeclareGlobalNewDelete(); 2270 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl()); 2271 } 2272 2273 FoundDelete.suppressDiagnostics(); 2274 2275 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches; 2276 2277 // Whether we're looking for a placement operator delete is dictated 2278 // by whether we selected a placement operator new, not by whether 2279 // we had explicit placement arguments. This matters for things like 2280 // struct A { void *operator new(size_t, int = 0); ... }; 2281 // A *a = new A() 2282 // 2283 // We don't have any definition for what a "placement allocation function" 2284 // is, but we assume it's any allocation function whose 2285 // parameter-declaration-clause is anything other than (size_t). 2286 // 2287 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement? 2288 // This affects whether an exception from the constructor of an overaligned 2289 // type uses the sized or non-sized form of aligned operator delete. 2290 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 || 2291 OperatorNew->isVariadic(); 2292 2293 if (isPlacementNew) { 2294 // C++ [expr.new]p20: 2295 // A declaration of a placement deallocation function matches the 2296 // declaration of a placement allocation function if it has the 2297 // same number of parameters and, after parameter transformations 2298 // (8.3.5), all parameter types except the first are 2299 // identical. [...] 2300 // 2301 // To perform this comparison, we compute the function type that 2302 // the deallocation function should have, and use that type both 2303 // for template argument deduction and for comparison purposes. 2304 // 2305 // FIXME: this comparison should ignore CC and the like. 2306 QualType ExpectedFunctionType; 2307 { 2308 const FunctionProtoType *Proto 2309 = OperatorNew->getType()->getAs<FunctionProtoType>(); 2310 2311 SmallVector<QualType, 4> ArgTypes; 2312 ArgTypes.push_back(Context.VoidPtrTy); 2313 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I) 2314 ArgTypes.push_back(Proto->getParamType(I)); 2315 2316 FunctionProtoType::ExtProtoInfo EPI; 2317 // FIXME: This is not part of the standard's rule. 2318 EPI.Variadic = Proto->isVariadic(); 2319 EPI.ExceptionSpec.Type = EST_BasicNoexcept; 2320 2321 ExpectedFunctionType 2322 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI); 2323 } 2324 2325 for (LookupResult::iterator D = FoundDelete.begin(), 2326 DEnd = FoundDelete.end(); 2327 D != DEnd; ++D) { 2328 FunctionDecl *Fn = nullptr; 2329 if (FunctionTemplateDecl *FnTmpl 2330 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) { 2331 // Perform template argument deduction to try to match the 2332 // expected function type. 2333 TemplateDeductionInfo Info(StartLoc); 2334 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn, 2335 Info)) 2336 continue; 2337 } else 2338 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl()); 2339 2340 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType)) 2341 Matches.push_back(std::make_pair(D.getPair(), Fn)); 2342 } 2343 2344 if (getLangOpts().CUDA) 2345 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches); 2346 } else { 2347 // C++1y [expr.new]p22: 2348 // For a non-placement allocation function, the normal deallocation 2349 // function lookup is used 2350 // 2351 // Per [expr.delete]p10, this lookup prefers a member operator delete 2352 // without a size_t argument, but prefers a non-member operator delete 2353 // with a size_t where possible (which it always is in this case). 2354 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns; 2355 UsualDeallocFnInfo Selected = resolveDeallocationOverload( 2356 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete, 2357 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType), 2358 &BestDeallocFns); 2359 if (Selected) 2360 Matches.push_back(std::make_pair(Selected.Found, Selected.FD)); 2361 else { 2362 // If we failed to select an operator, all remaining functions are viable 2363 // but ambiguous. 2364 for (auto Fn : BestDeallocFns) 2365 Matches.push_back(std::make_pair(Fn.Found, Fn.FD)); 2366 } 2367 } 2368 2369 // C++ [expr.new]p20: 2370 // [...] If the lookup finds a single matching deallocation 2371 // function, that function will be called; otherwise, no 2372 // deallocation function will be called. 2373 if (Matches.size() == 1) { 2374 OperatorDelete = Matches[0].second; 2375 2376 // C++1z [expr.new]p23: 2377 // If the lookup finds a usual deallocation function (3.7.4.2) 2378 // with a parameter of type std::size_t and that function, considered 2379 // as a placement deallocation function, would have been 2380 // selected as a match for the allocation function, the program 2381 // is ill-formed. 2382 if (getLangOpts().CPlusPlus11 && isPlacementNew && 2383 isNonPlacementDeallocationFunction(*this, OperatorDelete)) { 2384 UsualDeallocFnInfo Info(*this, 2385 DeclAccessPair::make(OperatorDelete, AS_public)); 2386 // Core issue, per mail to core reflector, 2016-10-09: 2387 // If this is a member operator delete, and there is a corresponding 2388 // non-sized member operator delete, this isn't /really/ a sized 2389 // deallocation function, it just happens to have a size_t parameter. 2390 bool IsSizedDelete = Info.HasSizeT; 2391 if (IsSizedDelete && !FoundGlobalDelete) { 2392 auto NonSizedDelete = 2393 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false, 2394 /*WantAlign*/Info.HasAlignValT); 2395 if (NonSizedDelete && !NonSizedDelete.HasSizeT && 2396 NonSizedDelete.HasAlignValT == Info.HasAlignValT) 2397 IsSizedDelete = false; 2398 } 2399 2400 if (IsSizedDelete) { 2401 SourceRange R = PlaceArgs.empty() 2402 ? SourceRange() 2403 : SourceRange(PlaceArgs.front()->getLocStart(), 2404 PlaceArgs.back()->getLocEnd()); 2405 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R; 2406 if (!OperatorDelete->isImplicit()) 2407 Diag(OperatorDelete->getLocation(), diag::note_previous_decl) 2408 << DeleteName; 2409 } 2410 } 2411 2412 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(), 2413 Matches[0].first); 2414 } else if (!Matches.empty()) { 2415 // We found multiple suitable operators. Per [expr.new]p20, that means we 2416 // call no 'operator delete' function, but we should at least warn the user. 2417 // FIXME: Suppress this warning if the construction cannot throw. 2418 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found) 2419 << DeleteName << AllocElemType; 2420 2421 for (auto &Match : Matches) 2422 Diag(Match.second->getLocation(), 2423 diag::note_member_declared_here) << DeleteName; 2424 } 2425 2426 return false; 2427 } 2428 2429 /// DeclareGlobalNewDelete - Declare the global forms of operator new and 2430 /// delete. These are: 2431 /// @code 2432 /// // C++03: 2433 /// void* operator new(std::size_t) throw(std::bad_alloc); 2434 /// void* operator new[](std::size_t) throw(std::bad_alloc); 2435 /// void operator delete(void *) throw(); 2436 /// void operator delete[](void *) throw(); 2437 /// // C++11: 2438 /// void* operator new(std::size_t); 2439 /// void* operator new[](std::size_t); 2440 /// void operator delete(void *) noexcept; 2441 /// void operator delete[](void *) noexcept; 2442 /// // C++1y: 2443 /// void* operator new(std::size_t); 2444 /// void* operator new[](std::size_t); 2445 /// void operator delete(void *) noexcept; 2446 /// void operator delete[](void *) noexcept; 2447 /// void operator delete(void *, std::size_t) noexcept; 2448 /// void operator delete[](void *, std::size_t) noexcept; 2449 /// @endcode 2450 /// Note that the placement and nothrow forms of new are *not* implicitly 2451 /// declared. Their use requires including \<new\>. 2452 void Sema::DeclareGlobalNewDelete() { 2453 if (GlobalNewDeleteDeclared) 2454 return; 2455 2456 // C++ [basic.std.dynamic]p2: 2457 // [...] The following allocation and deallocation functions (18.4) are 2458 // implicitly declared in global scope in each translation unit of a 2459 // program 2460 // 2461 // C++03: 2462 // void* operator new(std::size_t) throw(std::bad_alloc); 2463 // void* operator new[](std::size_t) throw(std::bad_alloc); 2464 // void operator delete(void*) throw(); 2465 // void operator delete[](void*) throw(); 2466 // C++11: 2467 // void* operator new(std::size_t); 2468 // void* operator new[](std::size_t); 2469 // void operator delete(void*) noexcept; 2470 // void operator delete[](void*) noexcept; 2471 // C++1y: 2472 // void* operator new(std::size_t); 2473 // void* operator new[](std::size_t); 2474 // void operator delete(void*) noexcept; 2475 // void operator delete[](void*) noexcept; 2476 // void operator delete(void*, std::size_t) noexcept; 2477 // void operator delete[](void*, std::size_t) noexcept; 2478 // 2479 // These implicit declarations introduce only the function names operator 2480 // new, operator new[], operator delete, operator delete[]. 2481 // 2482 // Here, we need to refer to std::bad_alloc, so we will implicitly declare 2483 // "std" or "bad_alloc" as necessary to form the exception specification. 2484 // However, we do not make these implicit declarations visible to name 2485 // lookup. 2486 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) { 2487 // The "std::bad_alloc" class has not yet been declared, so build it 2488 // implicitly. 2489 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class, 2490 getOrCreateStdNamespace(), 2491 SourceLocation(), SourceLocation(), 2492 &PP.getIdentifierTable().get("bad_alloc"), 2493 nullptr); 2494 getStdBadAlloc()->setImplicit(true); 2495 } 2496 if (!StdAlignValT && getLangOpts().AlignedAllocation) { 2497 // The "std::align_val_t" enum class has not yet been declared, so build it 2498 // implicitly. 2499 auto *AlignValT = EnumDecl::Create( 2500 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(), 2501 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true); 2502 AlignValT->setIntegerType(Context.getSizeType()); 2503 AlignValT->setPromotionType(Context.getSizeType()); 2504 AlignValT->setImplicit(true); 2505 StdAlignValT = AlignValT; 2506 } 2507 2508 GlobalNewDeleteDeclared = true; 2509 2510 QualType VoidPtr = Context.getPointerType(Context.VoidTy); 2511 QualType SizeT = Context.getSizeType(); 2512 2513 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind, 2514 QualType Return, QualType Param) { 2515 llvm::SmallVector<QualType, 3> Params; 2516 Params.push_back(Param); 2517 2518 // Create up to four variants of the function (sized/aligned). 2519 bool HasSizedVariant = getLangOpts().SizedDeallocation && 2520 (Kind == OO_Delete || Kind == OO_Array_Delete); 2521 bool HasAlignedVariant = getLangOpts().AlignedAllocation; 2522 2523 int NumSizeVariants = (HasSizedVariant ? 2 : 1); 2524 int NumAlignVariants = (HasAlignedVariant ? 2 : 1); 2525 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) { 2526 if (Sized) 2527 Params.push_back(SizeT); 2528 2529 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) { 2530 if (Aligned) 2531 Params.push_back(Context.getTypeDeclType(getStdAlignValT())); 2532 2533 DeclareGlobalAllocationFunction( 2534 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params); 2535 2536 if (Aligned) 2537 Params.pop_back(); 2538 } 2539 } 2540 }; 2541 2542 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT); 2543 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT); 2544 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr); 2545 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr); 2546 } 2547 2548 /// DeclareGlobalAllocationFunction - Declares a single implicit global 2549 /// allocation function if it doesn't already exist. 2550 void Sema::DeclareGlobalAllocationFunction(DeclarationName Name, 2551 QualType Return, 2552 ArrayRef<QualType> Params) { 2553 DeclContext *GlobalCtx = Context.getTranslationUnitDecl(); 2554 2555 // Check if this function is already declared. 2556 DeclContext::lookup_result R = GlobalCtx->lookup(Name); 2557 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end(); 2558 Alloc != AllocEnd; ++Alloc) { 2559 // Only look at non-template functions, as it is the predefined, 2560 // non-templated allocation function we are trying to declare here. 2561 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) { 2562 if (Func->getNumParams() == Params.size()) { 2563 llvm::SmallVector<QualType, 3> FuncParams; 2564 for (auto *P : Func->parameters()) 2565 FuncParams.push_back( 2566 Context.getCanonicalType(P->getType().getUnqualifiedType())); 2567 if (llvm::makeArrayRef(FuncParams) == Params) { 2568 // Make the function visible to name lookup, even if we found it in 2569 // an unimported module. It either is an implicitly-declared global 2570 // allocation function, or is suppressing that function. 2571 Func->setHidden(false); 2572 return; 2573 } 2574 } 2575 } 2576 } 2577 2578 FunctionProtoType::ExtProtoInfo EPI; 2579 2580 QualType BadAllocType; 2581 bool HasBadAllocExceptionSpec 2582 = (Name.getCXXOverloadedOperator() == OO_New || 2583 Name.getCXXOverloadedOperator() == OO_Array_New); 2584 if (HasBadAllocExceptionSpec) { 2585 if (!getLangOpts().CPlusPlus11) { 2586 BadAllocType = Context.getTypeDeclType(getStdBadAlloc()); 2587 assert(StdBadAlloc && "Must have std::bad_alloc declared"); 2588 EPI.ExceptionSpec.Type = EST_Dynamic; 2589 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType); 2590 } 2591 } else { 2592 EPI.ExceptionSpec = 2593 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone; 2594 } 2595 2596 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) { 2597 QualType FnType = Context.getFunctionType(Return, Params, EPI); 2598 FunctionDecl *Alloc = FunctionDecl::Create( 2599 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name, 2600 FnType, /*TInfo=*/nullptr, SC_None, false, true); 2601 Alloc->setImplicit(); 2602 2603 // Implicit sized deallocation functions always have default visibility. 2604 Alloc->addAttr( 2605 VisibilityAttr::CreateImplicit(Context, VisibilityAttr::Default)); 2606 2607 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls; 2608 for (QualType T : Params) { 2609 ParamDecls.push_back(ParmVarDecl::Create( 2610 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T, 2611 /*TInfo=*/nullptr, SC_None, nullptr)); 2612 ParamDecls.back()->setImplicit(); 2613 } 2614 Alloc->setParams(ParamDecls); 2615 if (ExtraAttr) 2616 Alloc->addAttr(ExtraAttr); 2617 Context.getTranslationUnitDecl()->addDecl(Alloc); 2618 IdResolver.tryAddTopLevelDecl(Alloc, Name); 2619 }; 2620 2621 if (!LangOpts.CUDA) 2622 CreateAllocationFunctionDecl(nullptr); 2623 else { 2624 // Host and device get their own declaration so each can be 2625 // defined or re-declared independently. 2626 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context)); 2627 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context)); 2628 } 2629 } 2630 2631 FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc, 2632 bool CanProvideSize, 2633 bool Overaligned, 2634 DeclarationName Name) { 2635 DeclareGlobalNewDelete(); 2636 2637 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName); 2638 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl()); 2639 2640 // FIXME: It's possible for this to result in ambiguity, through a 2641 // user-declared variadic operator delete or the enable_if attribute. We 2642 // should probably not consider those cases to be usual deallocation 2643 // functions. But for now we just make an arbitrary choice in that case. 2644 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize, 2645 Overaligned); 2646 assert(Result.FD && "operator delete missing from global scope?"); 2647 return Result.FD; 2648 } 2649 2650 FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc, 2651 CXXRecordDecl *RD) { 2652 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete); 2653 2654 FunctionDecl *OperatorDelete = nullptr; 2655 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 2656 return nullptr; 2657 if (OperatorDelete) 2658 return OperatorDelete; 2659 2660 // If there's no class-specific operator delete, look up the global 2661 // non-array delete. 2662 return FindUsualDeallocationFunction( 2663 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)), 2664 Name); 2665 } 2666 2667 bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, 2668 DeclarationName Name, 2669 FunctionDecl *&Operator, bool Diagnose) { 2670 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName); 2671 // Try to find operator delete/operator delete[] in class scope. 2672 LookupQualifiedName(Found, RD); 2673 2674 if (Found.isAmbiguous()) 2675 return true; 2676 2677 Found.suppressDiagnostics(); 2678 2679 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD)); 2680 2681 // C++17 [expr.delete]p10: 2682 // If the deallocation functions have class scope, the one without a 2683 // parameter of type std::size_t is selected. 2684 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches; 2685 resolveDeallocationOverload(*this, Found, /*WantSize*/ false, 2686 /*WantAlign*/ Overaligned, &Matches); 2687 2688 // If we could find an overload, use it. 2689 if (Matches.size() == 1) { 2690 Operator = cast<CXXMethodDecl>(Matches[0].FD); 2691 2692 // FIXME: DiagnoseUseOfDecl? 2693 if (Operator->isDeleted()) { 2694 if (Diagnose) { 2695 Diag(StartLoc, diag::err_deleted_function_use); 2696 NoteDeletedFunction(Operator); 2697 } 2698 return true; 2699 } 2700 2701 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(), 2702 Matches[0].Found, Diagnose) == AR_inaccessible) 2703 return true; 2704 2705 return false; 2706 } 2707 2708 // We found multiple suitable operators; complain about the ambiguity. 2709 // FIXME: The standard doesn't say to do this; it appears that the intent 2710 // is that this should never happen. 2711 if (!Matches.empty()) { 2712 if (Diagnose) { 2713 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found) 2714 << Name << RD; 2715 for (auto &Match : Matches) 2716 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name; 2717 } 2718 return true; 2719 } 2720 2721 // We did find operator delete/operator delete[] declarations, but 2722 // none of them were suitable. 2723 if (!Found.empty()) { 2724 if (Diagnose) { 2725 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found) 2726 << Name << RD; 2727 2728 for (NamedDecl *D : Found) 2729 Diag(D->getUnderlyingDecl()->getLocation(), 2730 diag::note_member_declared_here) << Name; 2731 } 2732 return true; 2733 } 2734 2735 Operator = nullptr; 2736 return false; 2737 } 2738 2739 namespace { 2740 /// \brief Checks whether delete-expression, and new-expression used for 2741 /// initializing deletee have the same array form. 2742 class MismatchingNewDeleteDetector { 2743 public: 2744 enum MismatchResult { 2745 /// Indicates that there is no mismatch or a mismatch cannot be proven. 2746 NoMismatch, 2747 /// Indicates that variable is initialized with mismatching form of \a new. 2748 VarInitMismatches, 2749 /// Indicates that member is initialized with mismatching form of \a new. 2750 MemberInitMismatches, 2751 /// Indicates that 1 or more constructors' definitions could not been 2752 /// analyzed, and they will be checked again at the end of translation unit. 2753 AnalyzeLater 2754 }; 2755 2756 /// \param EndOfTU True, if this is the final analysis at the end of 2757 /// translation unit. False, if this is the initial analysis at the point 2758 /// delete-expression was encountered. 2759 explicit MismatchingNewDeleteDetector(bool EndOfTU) 2760 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU), 2761 HasUndefinedConstructors(false) {} 2762 2763 /// \brief Checks whether pointee of a delete-expression is initialized with 2764 /// matching form of new-expression. 2765 /// 2766 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the 2767 /// point where delete-expression is encountered, then a warning will be 2768 /// issued immediately. If return value is \c AnalyzeLater at the point where 2769 /// delete-expression is seen, then member will be analyzed at the end of 2770 /// translation unit. \c AnalyzeLater is returned iff at least one constructor 2771 /// couldn't be analyzed. If at least one constructor initializes the member 2772 /// with matching type of new, the return value is \c NoMismatch. 2773 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE); 2774 /// \brief Analyzes a class member. 2775 /// \param Field Class member to analyze. 2776 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used 2777 /// for deleting the \p Field. 2778 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm); 2779 FieldDecl *Field; 2780 /// List of mismatching new-expressions used for initialization of the pointee 2781 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs; 2782 /// Indicates whether delete-expression was in array form. 2783 bool IsArrayForm; 2784 2785 private: 2786 const bool EndOfTU; 2787 /// \brief Indicates that there is at least one constructor without body. 2788 bool HasUndefinedConstructors; 2789 /// \brief Returns \c CXXNewExpr from given initialization expression. 2790 /// \param E Expression used for initializing pointee in delete-expression. 2791 /// E can be a single-element \c InitListExpr consisting of new-expression. 2792 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E); 2793 /// \brief Returns whether member is initialized with mismatching form of 2794 /// \c new either by the member initializer or in-class initialization. 2795 /// 2796 /// If bodies of all constructors are not visible at the end of translation 2797 /// unit or at least one constructor initializes member with the matching 2798 /// form of \c new, mismatch cannot be proven, and this function will return 2799 /// \c NoMismatch. 2800 MismatchResult analyzeMemberExpr(const MemberExpr *ME); 2801 /// \brief Returns whether variable is initialized with mismatching form of 2802 /// \c new. 2803 /// 2804 /// If variable is initialized with matching form of \c new or variable is not 2805 /// initialized with a \c new expression, this function will return true. 2806 /// If variable is initialized with mismatching form of \c new, returns false. 2807 /// \param D Variable to analyze. 2808 bool hasMatchingVarInit(const DeclRefExpr *D); 2809 /// \brief Checks whether the constructor initializes pointee with mismatching 2810 /// form of \c new. 2811 /// 2812 /// Returns true, if member is initialized with matching form of \c new in 2813 /// member initializer list. Returns false, if member is initialized with the 2814 /// matching form of \c new in this constructor's initializer or given 2815 /// constructor isn't defined at the point where delete-expression is seen, or 2816 /// member isn't initialized by the constructor. 2817 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD); 2818 /// \brief Checks whether member is initialized with matching form of 2819 /// \c new in member initializer list. 2820 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI); 2821 /// Checks whether member is initialized with mismatching form of \c new by 2822 /// in-class initializer. 2823 MismatchResult analyzeInClassInitializer(); 2824 }; 2825 } 2826 2827 MismatchingNewDeleteDetector::MismatchResult 2828 MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) { 2829 NewExprs.clear(); 2830 assert(DE && "Expected delete-expression"); 2831 IsArrayForm = DE->isArrayForm(); 2832 const Expr *E = DE->getArgument()->IgnoreParenImpCasts(); 2833 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) { 2834 return analyzeMemberExpr(ME); 2835 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) { 2836 if (!hasMatchingVarInit(D)) 2837 return VarInitMismatches; 2838 } 2839 return NoMismatch; 2840 } 2841 2842 const CXXNewExpr * 2843 MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) { 2844 assert(E != nullptr && "Expected a valid initializer expression"); 2845 E = E->IgnoreParenImpCasts(); 2846 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) { 2847 if (ILE->getNumInits() == 1) 2848 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts()); 2849 } 2850 2851 return dyn_cast_or_null<const CXXNewExpr>(E); 2852 } 2853 2854 bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit( 2855 const CXXCtorInitializer *CI) { 2856 const CXXNewExpr *NE = nullptr; 2857 if (Field == CI->getMember() && 2858 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) { 2859 if (NE->isArray() == IsArrayForm) 2860 return true; 2861 else 2862 NewExprs.push_back(NE); 2863 } 2864 return false; 2865 } 2866 2867 bool MismatchingNewDeleteDetector::hasMatchingNewInCtor( 2868 const CXXConstructorDecl *CD) { 2869 if (CD->isImplicit()) 2870 return false; 2871 const FunctionDecl *Definition = CD; 2872 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) { 2873 HasUndefinedConstructors = true; 2874 return EndOfTU; 2875 } 2876 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) { 2877 if (hasMatchingNewInCtorInit(CI)) 2878 return true; 2879 } 2880 return false; 2881 } 2882 2883 MismatchingNewDeleteDetector::MismatchResult 2884 MismatchingNewDeleteDetector::analyzeInClassInitializer() { 2885 assert(Field != nullptr && "This should be called only for members"); 2886 const Expr *InitExpr = Field->getInClassInitializer(); 2887 if (!InitExpr) 2888 return EndOfTU ? NoMismatch : AnalyzeLater; 2889 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) { 2890 if (NE->isArray() != IsArrayForm) { 2891 NewExprs.push_back(NE); 2892 return MemberInitMismatches; 2893 } 2894 } 2895 return NoMismatch; 2896 } 2897 2898 MismatchingNewDeleteDetector::MismatchResult 2899 MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field, 2900 bool DeleteWasArrayForm) { 2901 assert(Field != nullptr && "Analysis requires a valid class member."); 2902 this->Field = Field; 2903 IsArrayForm = DeleteWasArrayForm; 2904 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent()); 2905 for (const auto *CD : RD->ctors()) { 2906 if (hasMatchingNewInCtor(CD)) 2907 return NoMismatch; 2908 } 2909 if (HasUndefinedConstructors) 2910 return EndOfTU ? NoMismatch : AnalyzeLater; 2911 if (!NewExprs.empty()) 2912 return MemberInitMismatches; 2913 return Field->hasInClassInitializer() ? analyzeInClassInitializer() 2914 : NoMismatch; 2915 } 2916 2917 MismatchingNewDeleteDetector::MismatchResult 2918 MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) { 2919 assert(ME != nullptr && "Expected a member expression"); 2920 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2921 return analyzeField(F, IsArrayForm); 2922 return NoMismatch; 2923 } 2924 2925 bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) { 2926 const CXXNewExpr *NE = nullptr; 2927 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) { 2928 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) && 2929 NE->isArray() != IsArrayForm) { 2930 NewExprs.push_back(NE); 2931 } 2932 } 2933 return NewExprs.empty(); 2934 } 2935 2936 static void 2937 DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc, 2938 const MismatchingNewDeleteDetector &Detector) { 2939 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc); 2940 FixItHint H; 2941 if (!Detector.IsArrayForm) 2942 H = FixItHint::CreateInsertion(EndOfDelete, "[]"); 2943 else { 2944 SourceLocation RSquare = Lexer::findLocationAfterToken( 2945 DeleteLoc, tok::l_square, SemaRef.getSourceManager(), 2946 SemaRef.getLangOpts(), true); 2947 if (RSquare.isValid()) 2948 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare)); 2949 } 2950 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new) 2951 << Detector.IsArrayForm << H; 2952 2953 for (const auto *NE : Detector.NewExprs) 2954 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here) 2955 << Detector.IsArrayForm; 2956 } 2957 2958 void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) { 2959 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) 2960 return; 2961 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false); 2962 switch (Detector.analyzeDeleteExpr(DE)) { 2963 case MismatchingNewDeleteDetector::VarInitMismatches: 2964 case MismatchingNewDeleteDetector::MemberInitMismatches: { 2965 DiagnoseMismatchedNewDelete(*this, DE->getLocStart(), Detector); 2966 break; 2967 } 2968 case MismatchingNewDeleteDetector::AnalyzeLater: { 2969 DeleteExprs[Detector.Field].push_back( 2970 std::make_pair(DE->getLocStart(), DE->isArrayForm())); 2971 break; 2972 } 2973 case MismatchingNewDeleteDetector::NoMismatch: 2974 break; 2975 } 2976 } 2977 2978 void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, 2979 bool DeleteWasArrayForm) { 2980 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true); 2981 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) { 2982 case MismatchingNewDeleteDetector::VarInitMismatches: 2983 llvm_unreachable("This analysis should have been done for class members."); 2984 case MismatchingNewDeleteDetector::AnalyzeLater: 2985 llvm_unreachable("Analysis cannot be postponed any point beyond end of " 2986 "translation unit."); 2987 case MismatchingNewDeleteDetector::MemberInitMismatches: 2988 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector); 2989 break; 2990 case MismatchingNewDeleteDetector::NoMismatch: 2991 break; 2992 } 2993 } 2994 2995 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in: 2996 /// @code ::delete ptr; @endcode 2997 /// or 2998 /// @code delete [] ptr; @endcode 2999 ExprResult 3000 Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, 3001 bool ArrayForm, Expr *ExE) { 3002 // C++ [expr.delete]p1: 3003 // The operand shall have a pointer type, or a class type having a single 3004 // non-explicit conversion function to a pointer type. The result has type 3005 // void. 3006 // 3007 // DR599 amends "pointer type" to "pointer to object type" in both cases. 3008 3009 ExprResult Ex = ExE; 3010 FunctionDecl *OperatorDelete = nullptr; 3011 bool ArrayFormAsWritten = ArrayForm; 3012 bool UsualArrayDeleteWantsSize = false; 3013 3014 if (!Ex.get()->isTypeDependent()) { 3015 // Perform lvalue-to-rvalue cast, if needed. 3016 Ex = DefaultLvalueConversion(Ex.get()); 3017 if (Ex.isInvalid()) 3018 return ExprError(); 3019 3020 QualType Type = Ex.get()->getType(); 3021 3022 class DeleteConverter : public ContextualImplicitConverter { 3023 public: 3024 DeleteConverter() : ContextualImplicitConverter(false, true) {} 3025 3026 bool match(QualType ConvType) override { 3027 // FIXME: If we have an operator T* and an operator void*, we must pick 3028 // the operator T*. 3029 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 3030 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType()) 3031 return true; 3032 return false; 3033 } 3034 3035 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, 3036 QualType T) override { 3037 return S.Diag(Loc, diag::err_delete_operand) << T; 3038 } 3039 3040 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 3041 QualType T) override { 3042 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T; 3043 } 3044 3045 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 3046 QualType T, 3047 QualType ConvTy) override { 3048 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy; 3049 } 3050 3051 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 3052 QualType ConvTy) override { 3053 return S.Diag(Conv->getLocation(), diag::note_delete_conversion) 3054 << ConvTy; 3055 } 3056 3057 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 3058 QualType T) override { 3059 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T; 3060 } 3061 3062 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 3063 QualType ConvTy) override { 3064 return S.Diag(Conv->getLocation(), diag::note_delete_conversion) 3065 << ConvTy; 3066 } 3067 3068 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, 3069 QualType T, 3070 QualType ConvTy) override { 3071 llvm_unreachable("conversion functions are permitted"); 3072 } 3073 } Converter; 3074 3075 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter); 3076 if (Ex.isInvalid()) 3077 return ExprError(); 3078 Type = Ex.get()->getType(); 3079 if (!Converter.match(Type)) 3080 // FIXME: PerformContextualImplicitConversion should return ExprError 3081 // itself in this case. 3082 return ExprError(); 3083 3084 QualType Pointee = Type->getAs<PointerType>()->getPointeeType(); 3085 QualType PointeeElem = Context.getBaseElementType(Pointee); 3086 3087 if (unsigned AddressSpace = Pointee.getAddressSpace()) 3088 return Diag(Ex.get()->getLocStart(), 3089 diag::err_address_space_qualified_delete) 3090 << Pointee.getUnqualifiedType() << AddressSpace; 3091 3092 CXXRecordDecl *PointeeRD = nullptr; 3093 if (Pointee->isVoidType() && !isSFINAEContext()) { 3094 // The C++ standard bans deleting a pointer to a non-object type, which 3095 // effectively bans deletion of "void*". However, most compilers support 3096 // this, so we treat it as a warning unless we're in a SFINAE context. 3097 Diag(StartLoc, diag::ext_delete_void_ptr_operand) 3098 << Type << Ex.get()->getSourceRange(); 3099 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) { 3100 return ExprError(Diag(StartLoc, diag::err_delete_operand) 3101 << Type << Ex.get()->getSourceRange()); 3102 } else if (!Pointee->isDependentType()) { 3103 // FIXME: This can result in errors if the definition was imported from a 3104 // module but is hidden. 3105 if (!RequireCompleteType(StartLoc, Pointee, 3106 diag::warn_delete_incomplete, Ex.get())) { 3107 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) 3108 PointeeRD = cast<CXXRecordDecl>(RT->getDecl()); 3109 } 3110 } 3111 3112 if (Pointee->isArrayType() && !ArrayForm) { 3113 Diag(StartLoc, diag::warn_delete_array_type) 3114 << Type << Ex.get()->getSourceRange() 3115 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]"); 3116 ArrayForm = true; 3117 } 3118 3119 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( 3120 ArrayForm ? OO_Array_Delete : OO_Delete); 3121 3122 if (PointeeRD) { 3123 if (!UseGlobal && 3124 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName, 3125 OperatorDelete)) 3126 return ExprError(); 3127 3128 // If we're allocating an array of records, check whether the 3129 // usual operator delete[] has a size_t parameter. 3130 if (ArrayForm) { 3131 // If the user specifically asked to use the global allocator, 3132 // we'll need to do the lookup into the class. 3133 if (UseGlobal) 3134 UsualArrayDeleteWantsSize = 3135 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem); 3136 3137 // Otherwise, the usual operator delete[] should be the 3138 // function we just found. 3139 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete)) 3140 UsualArrayDeleteWantsSize = 3141 UsualDeallocFnInfo(*this, 3142 DeclAccessPair::make(OperatorDelete, AS_public)) 3143 .HasSizeT; 3144 } 3145 3146 if (!PointeeRD->hasIrrelevantDestructor()) 3147 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) { 3148 MarkFunctionReferenced(StartLoc, 3149 const_cast<CXXDestructorDecl*>(Dtor)); 3150 if (DiagnoseUseOfDecl(Dtor, StartLoc)) 3151 return ExprError(); 3152 } 3153 3154 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc, 3155 /*IsDelete=*/true, /*CallCanBeVirtual=*/true, 3156 /*WarnOnNonAbstractTypes=*/!ArrayForm, 3157 SourceLocation()); 3158 } 3159 3160 if (!OperatorDelete) { 3161 bool IsComplete = isCompleteType(StartLoc, Pointee); 3162 bool CanProvideSize = 3163 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize || 3164 Pointee.isDestructedType()); 3165 bool Overaligned = hasNewExtendedAlignment(*this, Pointee); 3166 3167 // Look for a global declaration. 3168 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize, 3169 Overaligned, DeleteName); 3170 } 3171 3172 MarkFunctionReferenced(StartLoc, OperatorDelete); 3173 3174 // Check access and ambiguity of operator delete and destructor. 3175 if (PointeeRD) { 3176 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) { 3177 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor, 3178 PDiag(diag::err_access_dtor) << PointeeElem); 3179 } 3180 } 3181 } 3182 3183 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr( 3184 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten, 3185 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc); 3186 AnalyzeDeleteExprMismatch(Result); 3187 return Result; 3188 } 3189 3190 void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, 3191 bool IsDelete, bool CallCanBeVirtual, 3192 bool WarnOnNonAbstractTypes, 3193 SourceLocation DtorLoc) { 3194 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual) 3195 return; 3196 3197 // C++ [expr.delete]p3: 3198 // In the first alternative (delete object), if the static type of the 3199 // object to be deleted is different from its dynamic type, the static 3200 // type shall be a base class of the dynamic type of the object to be 3201 // deleted and the static type shall have a virtual destructor or the 3202 // behavior is undefined. 3203 // 3204 const CXXRecordDecl *PointeeRD = dtor->getParent(); 3205 // Note: a final class cannot be derived from, no issue there 3206 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>()) 3207 return; 3208 3209 QualType ClassType = dtor->getThisType(Context)->getPointeeType(); 3210 if (PointeeRD->isAbstract()) { 3211 // If the class is abstract, we warn by default, because we're 3212 // sure the code has undefined behavior. 3213 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1) 3214 << ClassType; 3215 } else if (WarnOnNonAbstractTypes) { 3216 // Otherwise, if this is not an array delete, it's a bit suspect, 3217 // but not necessarily wrong. 3218 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1) 3219 << ClassType; 3220 } 3221 if (!IsDelete) { 3222 std::string TypeStr; 3223 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy()); 3224 Diag(DtorLoc, diag::note_delete_non_virtual) 3225 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::"); 3226 } 3227 } 3228 3229 Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar, 3230 SourceLocation StmtLoc, 3231 ConditionKind CK) { 3232 ExprResult E = 3233 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK); 3234 if (E.isInvalid()) 3235 return ConditionError(); 3236 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc), 3237 CK == ConditionKind::ConstexprIf); 3238 } 3239 3240 /// \brief Check the use of the given variable as a C++ condition in an if, 3241 /// while, do-while, or switch statement. 3242 ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar, 3243 SourceLocation StmtLoc, 3244 ConditionKind CK) { 3245 if (ConditionVar->isInvalidDecl()) 3246 return ExprError(); 3247 3248 QualType T = ConditionVar->getType(); 3249 3250 // C++ [stmt.select]p2: 3251 // The declarator shall not specify a function or an array. 3252 if (T->isFunctionType()) 3253 return ExprError(Diag(ConditionVar->getLocation(), 3254 diag::err_invalid_use_of_function_type) 3255 << ConditionVar->getSourceRange()); 3256 else if (T->isArrayType()) 3257 return ExprError(Diag(ConditionVar->getLocation(), 3258 diag::err_invalid_use_of_array_type) 3259 << ConditionVar->getSourceRange()); 3260 3261 ExprResult Condition = DeclRefExpr::Create( 3262 Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar, 3263 /*enclosing*/ false, ConditionVar->getLocation(), 3264 ConditionVar->getType().getNonReferenceType(), VK_LValue); 3265 3266 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get())); 3267 3268 switch (CK) { 3269 case ConditionKind::Boolean: 3270 return CheckBooleanCondition(StmtLoc, Condition.get()); 3271 3272 case ConditionKind::ConstexprIf: 3273 return CheckBooleanCondition(StmtLoc, Condition.get(), true); 3274 3275 case ConditionKind::Switch: 3276 return CheckSwitchCondition(StmtLoc, Condition.get()); 3277 } 3278 3279 llvm_unreachable("unexpected condition kind"); 3280 } 3281 3282 /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid. 3283 ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) { 3284 // C++ 6.4p4: 3285 // The value of a condition that is an initialized declaration in a statement 3286 // other than a switch statement is the value of the declared variable 3287 // implicitly converted to type bool. If that conversion is ill-formed, the 3288 // program is ill-formed. 3289 // The value of a condition that is an expression is the value of the 3290 // expression, implicitly converted to bool. 3291 // 3292 // FIXME: Return this value to the caller so they don't need to recompute it. 3293 llvm::APSInt Value(/*BitWidth*/1); 3294 return (IsConstexpr && !CondExpr->isValueDependent()) 3295 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value, 3296 CCEK_ConstexprIf) 3297 : PerformContextuallyConvertToBool(CondExpr); 3298 } 3299 3300 /// Helper function to determine whether this is the (deprecated) C++ 3301 /// conversion from a string literal to a pointer to non-const char or 3302 /// non-const wchar_t (for narrow and wide string literals, 3303 /// respectively). 3304 bool 3305 Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) { 3306 // Look inside the implicit cast, if it exists. 3307 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From)) 3308 From = Cast->getSubExpr(); 3309 3310 // A string literal (2.13.4) that is not a wide string literal can 3311 // be converted to an rvalue of type "pointer to char"; a wide 3312 // string literal can be converted to an rvalue of type "pointer 3313 // to wchar_t" (C++ 4.2p2). 3314 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens())) 3315 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) 3316 if (const BuiltinType *ToPointeeType 3317 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) { 3318 // This conversion is considered only when there is an 3319 // explicit appropriate pointer target type (C++ 4.2p2). 3320 if (!ToPtrType->getPointeeType().hasQualifiers()) { 3321 switch (StrLit->getKind()) { 3322 case StringLiteral::UTF8: 3323 case StringLiteral::UTF16: 3324 case StringLiteral::UTF32: 3325 // We don't allow UTF literals to be implicitly converted 3326 break; 3327 case StringLiteral::Ascii: 3328 return (ToPointeeType->getKind() == BuiltinType::Char_U || 3329 ToPointeeType->getKind() == BuiltinType::Char_S); 3330 case StringLiteral::Wide: 3331 return Context.typesAreCompatible(Context.getWideCharType(), 3332 QualType(ToPointeeType, 0)); 3333 } 3334 } 3335 } 3336 3337 return false; 3338 } 3339 3340 static ExprResult BuildCXXCastArgument(Sema &S, 3341 SourceLocation CastLoc, 3342 QualType Ty, 3343 CastKind Kind, 3344 CXXMethodDecl *Method, 3345 DeclAccessPair FoundDecl, 3346 bool HadMultipleCandidates, 3347 Expr *From) { 3348 switch (Kind) { 3349 default: llvm_unreachable("Unhandled cast kind!"); 3350 case CK_ConstructorConversion: { 3351 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method); 3352 SmallVector<Expr*, 8> ConstructorArgs; 3353 3354 if (S.RequireNonAbstractType(CastLoc, Ty, 3355 diag::err_allocation_of_abstract_type)) 3356 return ExprError(); 3357 3358 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs)) 3359 return ExprError(); 3360 3361 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl, 3362 InitializedEntity::InitializeTemporary(Ty)); 3363 if (S.DiagnoseUseOfDecl(Method, CastLoc)) 3364 return ExprError(); 3365 3366 ExprResult Result = S.BuildCXXConstructExpr( 3367 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method), 3368 ConstructorArgs, HadMultipleCandidates, 3369 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, 3370 CXXConstructExpr::CK_Complete, SourceRange()); 3371 if (Result.isInvalid()) 3372 return ExprError(); 3373 3374 return S.MaybeBindToTemporary(Result.getAs<Expr>()); 3375 } 3376 3377 case CK_UserDefinedConversion: { 3378 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!"); 3379 3380 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl); 3381 if (S.DiagnoseUseOfDecl(Method, CastLoc)) 3382 return ExprError(); 3383 3384 // Create an implicit call expr that calls it. 3385 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method); 3386 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv, 3387 HadMultipleCandidates); 3388 if (Result.isInvalid()) 3389 return ExprError(); 3390 // Record usage of conversion in an implicit cast. 3391 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(), 3392 CK_UserDefinedConversion, Result.get(), 3393 nullptr, Result.get()->getValueKind()); 3394 3395 return S.MaybeBindToTemporary(Result.get()); 3396 } 3397 } 3398 } 3399 3400 /// PerformImplicitConversion - Perform an implicit conversion of the 3401 /// expression From to the type ToType using the pre-computed implicit 3402 /// conversion sequence ICS. Returns the converted 3403 /// expression. Action is the kind of conversion we're performing, 3404 /// used in the error message. 3405 ExprResult 3406 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 3407 const ImplicitConversionSequence &ICS, 3408 AssignmentAction Action, 3409 CheckedConversionKind CCK) { 3410 switch (ICS.getKind()) { 3411 case ImplicitConversionSequence::StandardConversion: { 3412 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard, 3413 Action, CCK); 3414 if (Res.isInvalid()) 3415 return ExprError(); 3416 From = Res.get(); 3417 break; 3418 } 3419 3420 case ImplicitConversionSequence::UserDefinedConversion: { 3421 3422 FunctionDecl *FD = ICS.UserDefined.ConversionFunction; 3423 CastKind CastKind; 3424 QualType BeforeToType; 3425 assert(FD && "no conversion function for user-defined conversion seq"); 3426 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) { 3427 CastKind = CK_UserDefinedConversion; 3428 3429 // If the user-defined conversion is specified by a conversion function, 3430 // the initial standard conversion sequence converts the source type to 3431 // the implicit object parameter of the conversion function. 3432 BeforeToType = Context.getTagDeclType(Conv->getParent()); 3433 } else { 3434 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD); 3435 CastKind = CK_ConstructorConversion; 3436 // Do no conversion if dealing with ... for the first conversion. 3437 if (!ICS.UserDefined.EllipsisConversion) { 3438 // If the user-defined conversion is specified by a constructor, the 3439 // initial standard conversion sequence converts the source type to 3440 // the type required by the argument of the constructor 3441 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType(); 3442 } 3443 } 3444 // Watch out for ellipsis conversion. 3445 if (!ICS.UserDefined.EllipsisConversion) { 3446 ExprResult Res = 3447 PerformImplicitConversion(From, BeforeToType, 3448 ICS.UserDefined.Before, AA_Converting, 3449 CCK); 3450 if (Res.isInvalid()) 3451 return ExprError(); 3452 From = Res.get(); 3453 } 3454 3455 ExprResult CastArg 3456 = BuildCXXCastArgument(*this, 3457 From->getLocStart(), 3458 ToType.getNonReferenceType(), 3459 CastKind, cast<CXXMethodDecl>(FD), 3460 ICS.UserDefined.FoundConversionFunction, 3461 ICS.UserDefined.HadMultipleCandidates, 3462 From); 3463 3464 if (CastArg.isInvalid()) 3465 return ExprError(); 3466 3467 From = CastArg.get(); 3468 3469 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After, 3470 AA_Converting, CCK); 3471 } 3472 3473 case ImplicitConversionSequence::AmbiguousConversion: 3474 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(), 3475 PDiag(diag::err_typecheck_ambiguous_condition) 3476 << From->getSourceRange()); 3477 return ExprError(); 3478 3479 case ImplicitConversionSequence::EllipsisConversion: 3480 llvm_unreachable("Cannot perform an ellipsis conversion"); 3481 3482 case ImplicitConversionSequence::BadConversion: 3483 bool Diagnosed = 3484 DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType, 3485 From->getType(), From, Action); 3486 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed; 3487 return ExprError(); 3488 } 3489 3490 // Everything went well. 3491 return From; 3492 } 3493 3494 /// PerformImplicitConversion - Perform an implicit conversion of the 3495 /// expression From to the type ToType by following the standard 3496 /// conversion sequence SCS. Returns the converted 3497 /// expression. Flavor is the context in which we're performing this 3498 /// conversion, for use in error messages. 3499 ExprResult 3500 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 3501 const StandardConversionSequence& SCS, 3502 AssignmentAction Action, 3503 CheckedConversionKind CCK) { 3504 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast); 3505 3506 // Overall FIXME: we are recomputing too many types here and doing far too 3507 // much extra work. What this means is that we need to keep track of more 3508 // information that is computed when we try the implicit conversion initially, 3509 // so that we don't need to recompute anything here. 3510 QualType FromType = From->getType(); 3511 3512 if (SCS.CopyConstructor) { 3513 // FIXME: When can ToType be a reference type? 3514 assert(!ToType->isReferenceType()); 3515 if (SCS.Second == ICK_Derived_To_Base) { 3516 SmallVector<Expr*, 8> ConstructorArgs; 3517 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor), 3518 From, /*FIXME:ConstructLoc*/SourceLocation(), 3519 ConstructorArgs)) 3520 return ExprError(); 3521 return BuildCXXConstructExpr( 3522 /*FIXME:ConstructLoc*/ SourceLocation(), ToType, 3523 SCS.FoundCopyConstructor, SCS.CopyConstructor, 3524 ConstructorArgs, /*HadMultipleCandidates*/ false, 3525 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, 3526 CXXConstructExpr::CK_Complete, SourceRange()); 3527 } 3528 return BuildCXXConstructExpr( 3529 /*FIXME:ConstructLoc*/ SourceLocation(), ToType, 3530 SCS.FoundCopyConstructor, SCS.CopyConstructor, 3531 From, /*HadMultipleCandidates*/ false, 3532 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, 3533 CXXConstructExpr::CK_Complete, SourceRange()); 3534 } 3535 3536 // Resolve overloaded function references. 3537 if (Context.hasSameType(FromType, Context.OverloadTy)) { 3538 DeclAccessPair Found; 3539 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, 3540 true, Found); 3541 if (!Fn) 3542 return ExprError(); 3543 3544 if (DiagnoseUseOfDecl(Fn, From->getLocStart())) 3545 return ExprError(); 3546 3547 From = FixOverloadedFunctionReference(From, Found, Fn); 3548 FromType = From->getType(); 3549 } 3550 3551 // If we're converting to an atomic type, first convert to the corresponding 3552 // non-atomic type. 3553 QualType ToAtomicType; 3554 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) { 3555 ToAtomicType = ToType; 3556 ToType = ToAtomic->getValueType(); 3557 } 3558 3559 QualType InitialFromType = FromType; 3560 // Perform the first implicit conversion. 3561 switch (SCS.First) { 3562 case ICK_Identity: 3563 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) { 3564 FromType = FromAtomic->getValueType().getUnqualifiedType(); 3565 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic, 3566 From, /*BasePath=*/nullptr, VK_RValue); 3567 } 3568 break; 3569 3570 case ICK_Lvalue_To_Rvalue: { 3571 assert(From->getObjectKind() != OK_ObjCProperty); 3572 ExprResult FromRes = DefaultLvalueConversion(From); 3573 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!"); 3574 From = FromRes.get(); 3575 FromType = From->getType(); 3576 break; 3577 } 3578 3579 case ICK_Array_To_Pointer: 3580 FromType = Context.getArrayDecayedType(FromType); 3581 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, 3582 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 3583 break; 3584 3585 case ICK_Function_To_Pointer: 3586 FromType = Context.getPointerType(FromType); 3587 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay, 3588 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 3589 break; 3590 3591 default: 3592 llvm_unreachable("Improper first standard conversion"); 3593 } 3594 3595 // Perform the second implicit conversion 3596 switch (SCS.Second) { 3597 case ICK_Identity: 3598 // C++ [except.spec]p5: 3599 // [For] assignment to and initialization of pointers to functions, 3600 // pointers to member functions, and references to functions: the 3601 // target entity shall allow at least the exceptions allowed by the 3602 // source value in the assignment or initialization. 3603 switch (Action) { 3604 case AA_Assigning: 3605 case AA_Initializing: 3606 // Note, function argument passing and returning are initialization. 3607 case AA_Passing: 3608 case AA_Returning: 3609 case AA_Sending: 3610 case AA_Passing_CFAudited: 3611 if (CheckExceptionSpecCompatibility(From, ToType)) 3612 return ExprError(); 3613 break; 3614 3615 case AA_Casting: 3616 case AA_Converting: 3617 // Casts and implicit conversions are not initialization, so are not 3618 // checked for exception specification mismatches. 3619 break; 3620 } 3621 // Nothing else to do. 3622 break; 3623 3624 case ICK_Integral_Promotion: 3625 case ICK_Integral_Conversion: 3626 if (ToType->isBooleanType()) { 3627 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() && 3628 SCS.Second == ICK_Integral_Promotion && 3629 "only enums with fixed underlying type can promote to bool"); 3630 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean, 3631 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 3632 } else { 3633 From = ImpCastExprToType(From, ToType, CK_IntegralCast, 3634 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 3635 } 3636 break; 3637 3638 case ICK_Floating_Promotion: 3639 case ICK_Floating_Conversion: 3640 From = ImpCastExprToType(From, ToType, CK_FloatingCast, 3641 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 3642 break; 3643 3644 case ICK_Complex_Promotion: 3645 case ICK_Complex_Conversion: { 3646 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType(); 3647 QualType ToEl = ToType->getAs<ComplexType>()->getElementType(); 3648 CastKind CK; 3649 if (FromEl->isRealFloatingType()) { 3650 if (ToEl->isRealFloatingType()) 3651 CK = CK_FloatingComplexCast; 3652 else 3653 CK = CK_FloatingComplexToIntegralComplex; 3654 } else if (ToEl->isRealFloatingType()) { 3655 CK = CK_IntegralComplexToFloatingComplex; 3656 } else { 3657 CK = CK_IntegralComplexCast; 3658 } 3659 From = ImpCastExprToType(From, ToType, CK, 3660 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 3661 break; 3662 } 3663 3664 case ICK_Floating_Integral: 3665 if (ToType->isRealFloatingType()) 3666 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating, 3667 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 3668 else 3669 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral, 3670 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 3671 break; 3672 3673 case ICK_Compatible_Conversion: 3674 From = ImpCastExprToType(From, ToType, CK_NoOp, 3675 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 3676 break; 3677 3678 case ICK_Writeback_Conversion: 3679 case ICK_Pointer_Conversion: { 3680 if (SCS.IncompatibleObjC && Action != AA_Casting) { 3681 // Diagnose incompatible Objective-C conversions 3682 if (Action == AA_Initializing || Action == AA_Assigning) 3683 Diag(From->getLocStart(), 3684 diag::ext_typecheck_convert_incompatible_pointer) 3685 << ToType << From->getType() << Action 3686 << From->getSourceRange() << 0; 3687 else 3688 Diag(From->getLocStart(), 3689 diag::ext_typecheck_convert_incompatible_pointer) 3690 << From->getType() << ToType << Action 3691 << From->getSourceRange() << 0; 3692 3693 if (From->getType()->isObjCObjectPointerType() && 3694 ToType->isObjCObjectPointerType()) 3695 EmitRelatedResultTypeNote(From); 3696 } 3697 else if (getLangOpts().ObjCAutoRefCount && 3698 !CheckObjCARCUnavailableWeakConversion(ToType, 3699 From->getType())) { 3700 if (Action == AA_Initializing) 3701 Diag(From->getLocStart(), 3702 diag::err_arc_weak_unavailable_assign); 3703 else 3704 Diag(From->getLocStart(), 3705 diag::err_arc_convesion_of_weak_unavailable) 3706 << (Action == AA_Casting) << From->getType() << ToType 3707 << From->getSourceRange(); 3708 } 3709 3710 CastKind Kind = CK_Invalid; 3711 CXXCastPath BasePath; 3712 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle)) 3713 return ExprError(); 3714 3715 // Make sure we extend blocks if necessary. 3716 // FIXME: doing this here is really ugly. 3717 if (Kind == CK_BlockPointerToObjCPointerCast) { 3718 ExprResult E = From; 3719 (void) PrepareCastToObjCObjectPointer(E); 3720 From = E.get(); 3721 } 3722 if (getLangOpts().ObjCAutoRefCount) 3723 CheckObjCARCConversion(SourceRange(), ToType, From, CCK); 3724 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK) 3725 .get(); 3726 break; 3727 } 3728 3729 case ICK_Pointer_Member: { 3730 CastKind Kind = CK_Invalid; 3731 CXXCastPath BasePath; 3732 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle)) 3733 return ExprError(); 3734 if (CheckExceptionSpecCompatibility(From, ToType)) 3735 return ExprError(); 3736 3737 // We may not have been able to figure out what this member pointer resolved 3738 // to up until this exact point. Attempt to lock-in it's inheritance model. 3739 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 3740 (void)isCompleteType(From->getExprLoc(), From->getType()); 3741 (void)isCompleteType(From->getExprLoc(), ToType); 3742 } 3743 3744 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK) 3745 .get(); 3746 break; 3747 } 3748 3749 case ICK_Boolean_Conversion: 3750 // Perform half-to-boolean conversion via float. 3751 if (From->getType()->isHalfType()) { 3752 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get(); 3753 FromType = Context.FloatTy; 3754 } 3755 3756 From = ImpCastExprToType(From, Context.BoolTy, 3757 ScalarTypeToBooleanCastKind(FromType), 3758 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 3759 break; 3760 3761 case ICK_Derived_To_Base: { 3762 CXXCastPath BasePath; 3763 if (CheckDerivedToBaseConversion(From->getType(), 3764 ToType.getNonReferenceType(), 3765 From->getLocStart(), 3766 From->getSourceRange(), 3767 &BasePath, 3768 CStyle)) 3769 return ExprError(); 3770 3771 From = ImpCastExprToType(From, ToType.getNonReferenceType(), 3772 CK_DerivedToBase, From->getValueKind(), 3773 &BasePath, CCK).get(); 3774 break; 3775 } 3776 3777 case ICK_Vector_Conversion: 3778 From = ImpCastExprToType(From, ToType, CK_BitCast, 3779 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 3780 break; 3781 3782 case ICK_Vector_Splat: { 3783 // Vector splat from any arithmetic type to a vector. 3784 Expr *Elem = prepareVectorSplat(ToType, From).get(); 3785 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue, 3786 /*BasePath=*/nullptr, CCK).get(); 3787 break; 3788 } 3789 3790 case ICK_Complex_Real: 3791 // Case 1. x -> _Complex y 3792 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) { 3793 QualType ElType = ToComplex->getElementType(); 3794 bool isFloatingComplex = ElType->isRealFloatingType(); 3795 3796 // x -> y 3797 if (Context.hasSameUnqualifiedType(ElType, From->getType())) { 3798 // do nothing 3799 } else if (From->getType()->isRealFloatingType()) { 3800 From = ImpCastExprToType(From, ElType, 3801 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get(); 3802 } else { 3803 assert(From->getType()->isIntegerType()); 3804 From = ImpCastExprToType(From, ElType, 3805 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get(); 3806 } 3807 // y -> _Complex y 3808 From = ImpCastExprToType(From, ToType, 3809 isFloatingComplex ? CK_FloatingRealToComplex 3810 : CK_IntegralRealToComplex).get(); 3811 3812 // Case 2. _Complex x -> y 3813 } else { 3814 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>(); 3815 assert(FromComplex); 3816 3817 QualType ElType = FromComplex->getElementType(); 3818 bool isFloatingComplex = ElType->isRealFloatingType(); 3819 3820 // _Complex x -> x 3821 From = ImpCastExprToType(From, ElType, 3822 isFloatingComplex ? CK_FloatingComplexToReal 3823 : CK_IntegralComplexToReal, 3824 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 3825 3826 // x -> y 3827 if (Context.hasSameUnqualifiedType(ElType, ToType)) { 3828 // do nothing 3829 } else if (ToType->isRealFloatingType()) { 3830 From = ImpCastExprToType(From, ToType, 3831 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating, 3832 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 3833 } else { 3834 assert(ToType->isIntegerType()); 3835 From = ImpCastExprToType(From, ToType, 3836 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast, 3837 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 3838 } 3839 } 3840 break; 3841 3842 case ICK_Block_Pointer_Conversion: { 3843 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast, 3844 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 3845 break; 3846 } 3847 3848 case ICK_TransparentUnionConversion: { 3849 ExprResult FromRes = From; 3850 Sema::AssignConvertType ConvTy = 3851 CheckTransparentUnionArgumentConstraints(ToType, FromRes); 3852 if (FromRes.isInvalid()) 3853 return ExprError(); 3854 From = FromRes.get(); 3855 assert ((ConvTy == Sema::Compatible) && 3856 "Improper transparent union conversion"); 3857 (void)ConvTy; 3858 break; 3859 } 3860 3861 case ICK_Zero_Event_Conversion: 3862 From = ImpCastExprToType(From, ToType, 3863 CK_ZeroToOCLEvent, 3864 From->getValueKind()).get(); 3865 break; 3866 3867 case ICK_Lvalue_To_Rvalue: 3868 case ICK_Array_To_Pointer: 3869 case ICK_Function_To_Pointer: 3870 case ICK_Function_Conversion: 3871 case ICK_Qualification: 3872 case ICK_Num_Conversion_Kinds: 3873 case ICK_C_Only_Conversion: 3874 case ICK_Incompatible_Pointer_Conversion: 3875 llvm_unreachable("Improper second standard conversion"); 3876 } 3877 3878 switch (SCS.Third) { 3879 case ICK_Identity: 3880 // Nothing to do. 3881 break; 3882 3883 case ICK_Function_Conversion: 3884 // If both sides are functions (or pointers/references to them), there could 3885 // be incompatible exception declarations. 3886 if (CheckExceptionSpecCompatibility(From, ToType)) 3887 return ExprError(); 3888 3889 From = ImpCastExprToType(From, ToType, CK_NoOp, 3890 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 3891 break; 3892 3893 case ICK_Qualification: { 3894 // The qualification keeps the category of the inner expression, unless the 3895 // target type isn't a reference. 3896 ExprValueKind VK = ToType->isReferenceType() ? 3897 From->getValueKind() : VK_RValue; 3898 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), 3899 CK_NoOp, VK, /*BasePath=*/nullptr, CCK).get(); 3900 3901 if (SCS.DeprecatedStringLiteralToCharPtr && 3902 !getLangOpts().WritableStrings) { 3903 Diag(From->getLocStart(), getLangOpts().CPlusPlus11 3904 ? diag::ext_deprecated_string_literal_conversion 3905 : diag::warn_deprecated_string_literal_conversion) 3906 << ToType.getNonReferenceType(); 3907 } 3908 3909 break; 3910 } 3911 3912 default: 3913 llvm_unreachable("Improper third standard conversion"); 3914 } 3915 3916 // If this conversion sequence involved a scalar -> atomic conversion, perform 3917 // that conversion now. 3918 if (!ToAtomicType.isNull()) { 3919 assert(Context.hasSameType( 3920 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType())); 3921 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic, 3922 VK_RValue, nullptr, CCK).get(); 3923 } 3924 3925 // If this conversion sequence succeeded and involved implicitly converting a 3926 // _Nullable type to a _Nonnull one, complain. 3927 if (CCK == CCK_ImplicitConversion) 3928 diagnoseNullableToNonnullConversion(ToType, InitialFromType, 3929 From->getLocStart()); 3930 3931 return From; 3932 } 3933 3934 /// \brief Check the completeness of a type in a unary type trait. 3935 /// 3936 /// If the particular type trait requires a complete type, tries to complete 3937 /// it. If completing the type fails, a diagnostic is emitted and false 3938 /// returned. If completing the type succeeds or no completion was required, 3939 /// returns true. 3940 static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT, 3941 SourceLocation Loc, 3942 QualType ArgTy) { 3943 // C++0x [meta.unary.prop]p3: 3944 // For all of the class templates X declared in this Clause, instantiating 3945 // that template with a template argument that is a class template 3946 // specialization may result in the implicit instantiation of the template 3947 // argument if and only if the semantics of X require that the argument 3948 // must be a complete type. 3949 // We apply this rule to all the type trait expressions used to implement 3950 // these class templates. We also try to follow any GCC documented behavior 3951 // in these expressions to ensure portability of standard libraries. 3952 switch (UTT) { 3953 default: llvm_unreachable("not a UTT"); 3954 // is_complete_type somewhat obviously cannot require a complete type. 3955 case UTT_IsCompleteType: 3956 // Fall-through 3957 3958 // These traits are modeled on the type predicates in C++0x 3959 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as 3960 // requiring a complete type, as whether or not they return true cannot be 3961 // impacted by the completeness of the type. 3962 case UTT_IsVoid: 3963 case UTT_IsIntegral: 3964 case UTT_IsFloatingPoint: 3965 case UTT_IsArray: 3966 case UTT_IsPointer: 3967 case UTT_IsLvalueReference: 3968 case UTT_IsRvalueReference: 3969 case UTT_IsMemberFunctionPointer: 3970 case UTT_IsMemberObjectPointer: 3971 case UTT_IsEnum: 3972 case UTT_IsUnion: 3973 case UTT_IsClass: 3974 case UTT_IsFunction: 3975 case UTT_IsReference: 3976 case UTT_IsArithmetic: 3977 case UTT_IsFundamental: 3978 case UTT_IsObject: 3979 case UTT_IsScalar: 3980 case UTT_IsCompound: 3981 case UTT_IsMemberPointer: 3982 // Fall-through 3983 3984 // These traits are modeled on type predicates in C++0x [meta.unary.prop] 3985 // which requires some of its traits to have the complete type. However, 3986 // the completeness of the type cannot impact these traits' semantics, and 3987 // so they don't require it. This matches the comments on these traits in 3988 // Table 49. 3989 case UTT_IsConst: 3990 case UTT_IsVolatile: 3991 case UTT_IsSigned: 3992 case UTT_IsUnsigned: 3993 3994 // This type trait always returns false, checking the type is moot. 3995 case UTT_IsInterfaceClass: 3996 return true; 3997 3998 // C++14 [meta.unary.prop]: 3999 // If T is a non-union class type, T shall be a complete type. 4000 case UTT_IsEmpty: 4001 case UTT_IsPolymorphic: 4002 case UTT_IsAbstract: 4003 if (const auto *RD = ArgTy->getAsCXXRecordDecl()) 4004 if (!RD->isUnion()) 4005 return !S.RequireCompleteType( 4006 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); 4007 return true; 4008 4009 // C++14 [meta.unary.prop]: 4010 // If T is a class type, T shall be a complete type. 4011 case UTT_IsFinal: 4012 case UTT_IsSealed: 4013 if (ArgTy->getAsCXXRecordDecl()) 4014 return !S.RequireCompleteType( 4015 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); 4016 return true; 4017 4018 // C++0x [meta.unary.prop] Table 49 requires the following traits to be 4019 // applied to a complete type. 4020 case UTT_IsTrivial: 4021 case UTT_IsTriviallyCopyable: 4022 case UTT_IsStandardLayout: 4023 case UTT_IsPOD: 4024 case UTT_IsLiteral: 4025 4026 case UTT_IsDestructible: 4027 case UTT_IsNothrowDestructible: 4028 // Fall-through 4029 4030 // These trait expressions are designed to help implement predicates in 4031 // [meta.unary.prop] despite not being named the same. They are specified 4032 // by both GCC and the Embarcadero C++ compiler, and require the complete 4033 // type due to the overarching C++0x type predicates being implemented 4034 // requiring the complete type. 4035 case UTT_HasNothrowAssign: 4036 case UTT_HasNothrowMoveAssign: 4037 case UTT_HasNothrowConstructor: 4038 case UTT_HasNothrowCopy: 4039 case UTT_HasTrivialAssign: 4040 case UTT_HasTrivialMoveAssign: 4041 case UTT_HasTrivialDefaultConstructor: 4042 case UTT_HasTrivialMoveConstructor: 4043 case UTT_HasTrivialCopy: 4044 case UTT_HasTrivialDestructor: 4045 case UTT_HasVirtualDestructor: 4046 // Arrays of unknown bound are expressly allowed. 4047 QualType ElTy = ArgTy; 4048 if (ArgTy->isIncompleteArrayType()) 4049 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType(); 4050 4051 // The void type is expressly allowed. 4052 if (ElTy->isVoidType()) 4053 return true; 4054 4055 return !S.RequireCompleteType( 4056 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr); 4057 } 4058 } 4059 4060 static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op, 4061 Sema &Self, SourceLocation KeyLoc, ASTContext &C, 4062 bool (CXXRecordDecl::*HasTrivial)() const, 4063 bool (CXXRecordDecl::*HasNonTrivial)() const, 4064 bool (CXXMethodDecl::*IsDesiredOp)() const) 4065 { 4066 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4067 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)()) 4068 return true; 4069 4070 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op); 4071 DeclarationNameInfo NameInfo(Name, KeyLoc); 4072 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName); 4073 if (Self.LookupQualifiedName(Res, RD)) { 4074 bool FoundOperator = false; 4075 Res.suppressDiagnostics(); 4076 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end(); 4077 Op != OpEnd; ++Op) { 4078 if (isa<FunctionTemplateDecl>(*Op)) 4079 continue; 4080 4081 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op); 4082 if((Operator->*IsDesiredOp)()) { 4083 FoundOperator = true; 4084 const FunctionProtoType *CPT = 4085 Operator->getType()->getAs<FunctionProtoType>(); 4086 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 4087 if (!CPT || !CPT->isNothrow(C)) 4088 return false; 4089 } 4090 } 4091 return FoundOperator; 4092 } 4093 return false; 4094 } 4095 4096 static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT, 4097 SourceLocation KeyLoc, QualType T) { 4098 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type"); 4099 4100 ASTContext &C = Self.Context; 4101 switch(UTT) { 4102 default: llvm_unreachable("not a UTT"); 4103 // Type trait expressions corresponding to the primary type category 4104 // predicates in C++0x [meta.unary.cat]. 4105 case UTT_IsVoid: 4106 return T->isVoidType(); 4107 case UTT_IsIntegral: 4108 return T->isIntegralType(C); 4109 case UTT_IsFloatingPoint: 4110 return T->isFloatingType(); 4111 case UTT_IsArray: 4112 return T->isArrayType(); 4113 case UTT_IsPointer: 4114 return T->isPointerType(); 4115 case UTT_IsLvalueReference: 4116 return T->isLValueReferenceType(); 4117 case UTT_IsRvalueReference: 4118 return T->isRValueReferenceType(); 4119 case UTT_IsMemberFunctionPointer: 4120 return T->isMemberFunctionPointerType(); 4121 case UTT_IsMemberObjectPointer: 4122 return T->isMemberDataPointerType(); 4123 case UTT_IsEnum: 4124 return T->isEnumeralType(); 4125 case UTT_IsUnion: 4126 return T->isUnionType(); 4127 case UTT_IsClass: 4128 return T->isClassType() || T->isStructureType() || T->isInterfaceType(); 4129 case UTT_IsFunction: 4130 return T->isFunctionType(); 4131 4132 // Type trait expressions which correspond to the convenient composition 4133 // predicates in C++0x [meta.unary.comp]. 4134 case UTT_IsReference: 4135 return T->isReferenceType(); 4136 case UTT_IsArithmetic: 4137 return T->isArithmeticType() && !T->isEnumeralType(); 4138 case UTT_IsFundamental: 4139 return T->isFundamentalType(); 4140 case UTT_IsObject: 4141 return T->isObjectType(); 4142 case UTT_IsScalar: 4143 // Note: semantic analysis depends on Objective-C lifetime types to be 4144 // considered scalar types. However, such types do not actually behave 4145 // like scalar types at run time (since they may require retain/release 4146 // operations), so we report them as non-scalar. 4147 if (T->isObjCLifetimeType()) { 4148 switch (T.getObjCLifetime()) { 4149 case Qualifiers::OCL_None: 4150 case Qualifiers::OCL_ExplicitNone: 4151 return true; 4152 4153 case Qualifiers::OCL_Strong: 4154 case Qualifiers::OCL_Weak: 4155 case Qualifiers::OCL_Autoreleasing: 4156 return false; 4157 } 4158 } 4159 4160 return T->isScalarType(); 4161 case UTT_IsCompound: 4162 return T->isCompoundType(); 4163 case UTT_IsMemberPointer: 4164 return T->isMemberPointerType(); 4165 4166 // Type trait expressions which correspond to the type property predicates 4167 // in C++0x [meta.unary.prop]. 4168 case UTT_IsConst: 4169 return T.isConstQualified(); 4170 case UTT_IsVolatile: 4171 return T.isVolatileQualified(); 4172 case UTT_IsTrivial: 4173 return T.isTrivialType(C); 4174 case UTT_IsTriviallyCopyable: 4175 return T.isTriviallyCopyableType(C); 4176 case UTT_IsStandardLayout: 4177 return T->isStandardLayoutType(); 4178 case UTT_IsPOD: 4179 return T.isPODType(C); 4180 case UTT_IsLiteral: 4181 return T->isLiteralType(C); 4182 case UTT_IsEmpty: 4183 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 4184 return !RD->isUnion() && RD->isEmpty(); 4185 return false; 4186 case UTT_IsPolymorphic: 4187 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 4188 return !RD->isUnion() && RD->isPolymorphic(); 4189 return false; 4190 case UTT_IsAbstract: 4191 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 4192 return !RD->isUnion() && RD->isAbstract(); 4193 return false; 4194 // __is_interface_class only returns true when CL is invoked in /CLR mode and 4195 // even then only when it is used with the 'interface struct ...' syntax 4196 // Clang doesn't support /CLR which makes this type trait moot. 4197 case UTT_IsInterfaceClass: 4198 return false; 4199 case UTT_IsFinal: 4200 case UTT_IsSealed: 4201 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 4202 return RD->hasAttr<FinalAttr>(); 4203 return false; 4204 case UTT_IsSigned: 4205 return T->isSignedIntegerType(); 4206 case UTT_IsUnsigned: 4207 return T->isUnsignedIntegerType(); 4208 4209 // Type trait expressions which query classes regarding their construction, 4210 // destruction, and copying. Rather than being based directly on the 4211 // related type predicates in the standard, they are specified by both 4212 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those 4213 // specifications. 4214 // 4215 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html 4216 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index 4217 // 4218 // Note that these builtins do not behave as documented in g++: if a class 4219 // has both a trivial and a non-trivial special member of a particular kind, 4220 // they return false! For now, we emulate this behavior. 4221 // FIXME: This appears to be a g++ bug: more complex cases reveal that it 4222 // does not correctly compute triviality in the presence of multiple special 4223 // members of the same kind. Revisit this once the g++ bug is fixed. 4224 case UTT_HasTrivialDefaultConstructor: 4225 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 4226 // If __is_pod (type) is true then the trait is true, else if type is 4227 // a cv class or union type (or array thereof) with a trivial default 4228 // constructor ([class.ctor]) then the trait is true, else it is false. 4229 if (T.isPODType(C)) 4230 return true; 4231 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 4232 return RD->hasTrivialDefaultConstructor() && 4233 !RD->hasNonTrivialDefaultConstructor(); 4234 return false; 4235 case UTT_HasTrivialMoveConstructor: 4236 // This trait is implemented by MSVC 2012 and needed to parse the 4237 // standard library headers. Specifically this is used as the logic 4238 // behind std::is_trivially_move_constructible (20.9.4.3). 4239 if (T.isPODType(C)) 4240 return true; 4241 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 4242 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor(); 4243 return false; 4244 case UTT_HasTrivialCopy: 4245 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 4246 // If __is_pod (type) is true or type is a reference type then 4247 // the trait is true, else if type is a cv class or union type 4248 // with a trivial copy constructor ([class.copy]) then the trait 4249 // is true, else it is false. 4250 if (T.isPODType(C) || T->isReferenceType()) 4251 return true; 4252 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 4253 return RD->hasTrivialCopyConstructor() && 4254 !RD->hasNonTrivialCopyConstructor(); 4255 return false; 4256 case UTT_HasTrivialMoveAssign: 4257 // This trait is implemented by MSVC 2012 and needed to parse the 4258 // standard library headers. Specifically it is used as the logic 4259 // behind std::is_trivially_move_assignable (20.9.4.3) 4260 if (T.isPODType(C)) 4261 return true; 4262 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 4263 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment(); 4264 return false; 4265 case UTT_HasTrivialAssign: 4266 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 4267 // If type is const qualified or is a reference type then the 4268 // trait is false. Otherwise if __is_pod (type) is true then the 4269 // trait is true, else if type is a cv class or union type with 4270 // a trivial copy assignment ([class.copy]) then the trait is 4271 // true, else it is false. 4272 // Note: the const and reference restrictions are interesting, 4273 // given that const and reference members don't prevent a class 4274 // from having a trivial copy assignment operator (but do cause 4275 // errors if the copy assignment operator is actually used, q.v. 4276 // [class.copy]p12). 4277 4278 if (T.isConstQualified()) 4279 return false; 4280 if (T.isPODType(C)) 4281 return true; 4282 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 4283 return RD->hasTrivialCopyAssignment() && 4284 !RD->hasNonTrivialCopyAssignment(); 4285 return false; 4286 case UTT_IsDestructible: 4287 case UTT_IsNothrowDestructible: 4288 // C++14 [meta.unary.prop]: 4289 // For reference types, is_destructible<T>::value is true. 4290 if (T->isReferenceType()) 4291 return true; 4292 4293 // Objective-C++ ARC: autorelease types don't require destruction. 4294 if (T->isObjCLifetimeType() && 4295 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) 4296 return true; 4297 4298 // C++14 [meta.unary.prop]: 4299 // For incomplete types and function types, is_destructible<T>::value is 4300 // false. 4301 if (T->isIncompleteType() || T->isFunctionType()) 4302 return false; 4303 4304 // C++14 [meta.unary.prop]: 4305 // For object types and given U equal to remove_all_extents_t<T>, if the 4306 // expression std::declval<U&>().~U() is well-formed when treated as an 4307 // unevaluated operand (Clause 5), then is_destructible<T>::value is true 4308 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) { 4309 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD); 4310 if (!Destructor) 4311 return false; 4312 // C++14 [dcl.fct.def.delete]p2: 4313 // A program that refers to a deleted function implicitly or 4314 // explicitly, other than to declare it, is ill-formed. 4315 if (Destructor->isDeleted()) 4316 return false; 4317 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public) 4318 return false; 4319 if (UTT == UTT_IsNothrowDestructible) { 4320 const FunctionProtoType *CPT = 4321 Destructor->getType()->getAs<FunctionProtoType>(); 4322 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 4323 if (!CPT || !CPT->isNothrow(C)) 4324 return false; 4325 } 4326 } 4327 return true; 4328 4329 case UTT_HasTrivialDestructor: 4330 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html 4331 // If __is_pod (type) is true or type is a reference type 4332 // then the trait is true, else if type is a cv class or union 4333 // type (or array thereof) with a trivial destructor 4334 // ([class.dtor]) then the trait is true, else it is 4335 // false. 4336 if (T.isPODType(C) || T->isReferenceType()) 4337 return true; 4338 4339 // Objective-C++ ARC: autorelease types don't require destruction. 4340 if (T->isObjCLifetimeType() && 4341 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) 4342 return true; 4343 4344 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 4345 return RD->hasTrivialDestructor(); 4346 return false; 4347 // TODO: Propagate nothrowness for implicitly declared special members. 4348 case UTT_HasNothrowAssign: 4349 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 4350 // If type is const qualified or is a reference type then the 4351 // trait is false. Otherwise if __has_trivial_assign (type) 4352 // is true then the trait is true, else if type is a cv class 4353 // or union type with copy assignment operators that are known 4354 // not to throw an exception then the trait is true, else it is 4355 // false. 4356 if (C.getBaseElementType(T).isConstQualified()) 4357 return false; 4358 if (T->isReferenceType()) 4359 return false; 4360 if (T.isPODType(C) || T->isObjCLifetimeType()) 4361 return true; 4362 4363 if (const RecordType *RT = T->getAs<RecordType>()) 4364 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C, 4365 &CXXRecordDecl::hasTrivialCopyAssignment, 4366 &CXXRecordDecl::hasNonTrivialCopyAssignment, 4367 &CXXMethodDecl::isCopyAssignmentOperator); 4368 return false; 4369 case UTT_HasNothrowMoveAssign: 4370 // This trait is implemented by MSVC 2012 and needed to parse the 4371 // standard library headers. Specifically this is used as the logic 4372 // behind std::is_nothrow_move_assignable (20.9.4.3). 4373 if (T.isPODType(C)) 4374 return true; 4375 4376 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) 4377 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C, 4378 &CXXRecordDecl::hasTrivialMoveAssignment, 4379 &CXXRecordDecl::hasNonTrivialMoveAssignment, 4380 &CXXMethodDecl::isMoveAssignmentOperator); 4381 return false; 4382 case UTT_HasNothrowCopy: 4383 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 4384 // If __has_trivial_copy (type) is true then the trait is true, else 4385 // if type is a cv class or union type with copy constructors that are 4386 // known not to throw an exception then the trait is true, else it is 4387 // false. 4388 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType()) 4389 return true; 4390 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 4391 if (RD->hasTrivialCopyConstructor() && 4392 !RD->hasNonTrivialCopyConstructor()) 4393 return true; 4394 4395 bool FoundConstructor = false; 4396 unsigned FoundTQs; 4397 for (const auto *ND : Self.LookupConstructors(RD)) { 4398 // A template constructor is never a copy constructor. 4399 // FIXME: However, it may actually be selected at the actual overload 4400 // resolution point. 4401 if (isa<FunctionTemplateDecl>(ND)) 4402 continue; 4403 const CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(ND); 4404 if (Constructor->isCopyConstructor(FoundTQs)) { 4405 FoundConstructor = true; 4406 const FunctionProtoType *CPT 4407 = Constructor->getType()->getAs<FunctionProtoType>(); 4408 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 4409 if (!CPT) 4410 return false; 4411 // TODO: check whether evaluating default arguments can throw. 4412 // For now, we'll be conservative and assume that they can throw. 4413 if (!CPT->isNothrow(C) || CPT->getNumParams() > 1) 4414 return false; 4415 } 4416 } 4417 4418 return FoundConstructor; 4419 } 4420 return false; 4421 case UTT_HasNothrowConstructor: 4422 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html 4423 // If __has_trivial_constructor (type) is true then the trait is 4424 // true, else if type is a cv class or union type (or array 4425 // thereof) with a default constructor that is known not to 4426 // throw an exception then the trait is true, else it is false. 4427 if (T.isPODType(C) || T->isObjCLifetimeType()) 4428 return true; 4429 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) { 4430 if (RD->hasTrivialDefaultConstructor() && 4431 !RD->hasNonTrivialDefaultConstructor()) 4432 return true; 4433 4434 bool FoundConstructor = false; 4435 for (const auto *ND : Self.LookupConstructors(RD)) { 4436 // FIXME: In C++0x, a constructor template can be a default constructor. 4437 if (isa<FunctionTemplateDecl>(ND)) 4438 continue; 4439 const CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(ND); 4440 if (Constructor->isDefaultConstructor()) { 4441 FoundConstructor = true; 4442 const FunctionProtoType *CPT 4443 = Constructor->getType()->getAs<FunctionProtoType>(); 4444 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 4445 if (!CPT) 4446 return false; 4447 // FIXME: check whether evaluating default arguments can throw. 4448 // For now, we'll be conservative and assume that they can throw. 4449 if (!CPT->isNothrow(C) || CPT->getNumParams() > 0) 4450 return false; 4451 } 4452 } 4453 return FoundConstructor; 4454 } 4455 return false; 4456 case UTT_HasVirtualDestructor: 4457 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 4458 // If type is a class type with a virtual destructor ([class.dtor]) 4459 // then the trait is true, else it is false. 4460 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 4461 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD)) 4462 return Destructor->isVirtual(); 4463 return false; 4464 4465 // These type trait expressions are modeled on the specifications for the 4466 // Embarcadero C++0x type trait functions: 4467 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index 4468 case UTT_IsCompleteType: 4469 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_): 4470 // Returns True if and only if T is a complete type at the point of the 4471 // function call. 4472 return !T->isIncompleteType(); 4473 } 4474 } 4475 4476 /// \brief Determine whether T has a non-trivial Objective-C lifetime in 4477 /// ARC mode. 4478 static bool hasNontrivialObjCLifetime(QualType T) { 4479 switch (T.getObjCLifetime()) { 4480 case Qualifiers::OCL_ExplicitNone: 4481 return false; 4482 4483 case Qualifiers::OCL_Strong: 4484 case Qualifiers::OCL_Weak: 4485 case Qualifiers::OCL_Autoreleasing: 4486 return true; 4487 4488 case Qualifiers::OCL_None: 4489 return T->isObjCLifetimeType(); 4490 } 4491 4492 llvm_unreachable("Unknown ObjC lifetime qualifier"); 4493 } 4494 4495 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT, 4496 QualType RhsT, SourceLocation KeyLoc); 4497 4498 static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc, 4499 ArrayRef<TypeSourceInfo *> Args, 4500 SourceLocation RParenLoc) { 4501 if (Kind <= UTT_Last) 4502 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType()); 4503 4504 if (Kind <= BTT_Last) 4505 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(), 4506 Args[1]->getType(), RParenLoc); 4507 4508 switch (Kind) { 4509 case clang::TT_IsConstructible: 4510 case clang::TT_IsNothrowConstructible: 4511 case clang::TT_IsTriviallyConstructible: { 4512 // C++11 [meta.unary.prop]: 4513 // is_trivially_constructible is defined as: 4514 // 4515 // is_constructible<T, Args...>::value is true and the variable 4516 // definition for is_constructible, as defined below, is known to call 4517 // no operation that is not trivial. 4518 // 4519 // The predicate condition for a template specialization 4520 // is_constructible<T, Args...> shall be satisfied if and only if the 4521 // following variable definition would be well-formed for some invented 4522 // variable t: 4523 // 4524 // T t(create<Args>()...); 4525 assert(!Args.empty()); 4526 4527 // Precondition: T and all types in the parameter pack Args shall be 4528 // complete types, (possibly cv-qualified) void, or arrays of 4529 // unknown bound. 4530 for (const auto *TSI : Args) { 4531 QualType ArgTy = TSI->getType(); 4532 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType()) 4533 continue; 4534 4535 if (S.RequireCompleteType(KWLoc, ArgTy, 4536 diag::err_incomplete_type_used_in_type_trait_expr)) 4537 return false; 4538 } 4539 4540 // Make sure the first argument is not incomplete nor a function type. 4541 QualType T = Args[0]->getType(); 4542 if (T->isIncompleteType() || T->isFunctionType()) 4543 return false; 4544 4545 // Make sure the first argument is not an abstract type. 4546 CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 4547 if (RD && RD->isAbstract()) 4548 return false; 4549 4550 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs; 4551 SmallVector<Expr *, 2> ArgExprs; 4552 ArgExprs.reserve(Args.size() - 1); 4553 for (unsigned I = 1, N = Args.size(); I != N; ++I) { 4554 QualType ArgTy = Args[I]->getType(); 4555 if (ArgTy->isObjectType() || ArgTy->isFunctionType()) 4556 ArgTy = S.Context.getRValueReferenceType(ArgTy); 4557 OpaqueArgExprs.push_back( 4558 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(), 4559 ArgTy.getNonLValueExprType(S.Context), 4560 Expr::getValueKindForType(ArgTy))); 4561 } 4562 for (Expr &E : OpaqueArgExprs) 4563 ArgExprs.push_back(&E); 4564 4565 // Perform the initialization in an unevaluated context within a SFINAE 4566 // trap at translation unit scope. 4567 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated); 4568 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true); 4569 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl()); 4570 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0])); 4571 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc, 4572 RParenLoc)); 4573 InitializationSequence Init(S, To, InitKind, ArgExprs); 4574 if (Init.Failed()) 4575 return false; 4576 4577 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs); 4578 if (Result.isInvalid() || SFINAE.hasErrorOccurred()) 4579 return false; 4580 4581 if (Kind == clang::TT_IsConstructible) 4582 return true; 4583 4584 if (Kind == clang::TT_IsNothrowConstructible) 4585 return S.canThrow(Result.get()) == CT_Cannot; 4586 4587 if (Kind == clang::TT_IsTriviallyConstructible) { 4588 // Under Objective-C ARC, if the destination has non-trivial Objective-C 4589 // lifetime, this is a non-trivial construction. 4590 if (S.getLangOpts().ObjCAutoRefCount && 4591 hasNontrivialObjCLifetime(T.getNonReferenceType())) 4592 return false; 4593 4594 // The initialization succeeded; now make sure there are no non-trivial 4595 // calls. 4596 return !Result.get()->hasNonTrivialCall(S.Context); 4597 } 4598 4599 llvm_unreachable("unhandled type trait"); 4600 return false; 4601 } 4602 default: llvm_unreachable("not a TT"); 4603 } 4604 4605 return false; 4606 } 4607 4608 ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 4609 ArrayRef<TypeSourceInfo *> Args, 4610 SourceLocation RParenLoc) { 4611 QualType ResultType = Context.getLogicalOperationType(); 4612 4613 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness( 4614 *this, Kind, KWLoc, Args[0]->getType())) 4615 return ExprError(); 4616 4617 bool Dependent = false; 4618 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 4619 if (Args[I]->getType()->isDependentType()) { 4620 Dependent = true; 4621 break; 4622 } 4623 } 4624 4625 bool Result = false; 4626 if (!Dependent) 4627 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc); 4628 4629 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args, 4630 RParenLoc, Result); 4631 } 4632 4633 ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 4634 ArrayRef<ParsedType> Args, 4635 SourceLocation RParenLoc) { 4636 SmallVector<TypeSourceInfo *, 4> ConvertedArgs; 4637 ConvertedArgs.reserve(Args.size()); 4638 4639 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 4640 TypeSourceInfo *TInfo; 4641 QualType T = GetTypeFromParser(Args[I], &TInfo); 4642 if (!TInfo) 4643 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc); 4644 4645 ConvertedArgs.push_back(TInfo); 4646 } 4647 4648 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc); 4649 } 4650 4651 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT, 4652 QualType RhsT, SourceLocation KeyLoc) { 4653 assert(!LhsT->isDependentType() && !RhsT->isDependentType() && 4654 "Cannot evaluate traits of dependent types"); 4655 4656 switch(BTT) { 4657 case BTT_IsBaseOf: { 4658 // C++0x [meta.rel]p2 4659 // Base is a base class of Derived without regard to cv-qualifiers or 4660 // Base and Derived are not unions and name the same class type without 4661 // regard to cv-qualifiers. 4662 4663 const RecordType *lhsRecord = LhsT->getAs<RecordType>(); 4664 if (!lhsRecord) return false; 4665 4666 const RecordType *rhsRecord = RhsT->getAs<RecordType>(); 4667 if (!rhsRecord) return false; 4668 4669 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT) 4670 == (lhsRecord == rhsRecord)); 4671 4672 if (lhsRecord == rhsRecord) 4673 return !lhsRecord->getDecl()->isUnion(); 4674 4675 // C++0x [meta.rel]p2: 4676 // If Base and Derived are class types and are different types 4677 // (ignoring possible cv-qualifiers) then Derived shall be a 4678 // complete type. 4679 if (Self.RequireCompleteType(KeyLoc, RhsT, 4680 diag::err_incomplete_type_used_in_type_trait_expr)) 4681 return false; 4682 4683 return cast<CXXRecordDecl>(rhsRecord->getDecl()) 4684 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl())); 4685 } 4686 case BTT_IsSame: 4687 return Self.Context.hasSameType(LhsT, RhsT); 4688 case BTT_TypeCompatible: 4689 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(), 4690 RhsT.getUnqualifiedType()); 4691 case BTT_IsConvertible: 4692 case BTT_IsConvertibleTo: { 4693 // C++0x [meta.rel]p4: 4694 // Given the following function prototype: 4695 // 4696 // template <class T> 4697 // typename add_rvalue_reference<T>::type create(); 4698 // 4699 // the predicate condition for a template specialization 4700 // is_convertible<From, To> shall be satisfied if and only if 4701 // the return expression in the following code would be 4702 // well-formed, including any implicit conversions to the return 4703 // type of the function: 4704 // 4705 // To test() { 4706 // return create<From>(); 4707 // } 4708 // 4709 // Access checking is performed as if in a context unrelated to To and 4710 // From. Only the validity of the immediate context of the expression 4711 // of the return-statement (including conversions to the return type) 4712 // is considered. 4713 // 4714 // We model the initialization as a copy-initialization of a temporary 4715 // of the appropriate type, which for this expression is identical to the 4716 // return statement (since NRVO doesn't apply). 4717 4718 // Functions aren't allowed to return function or array types. 4719 if (RhsT->isFunctionType() || RhsT->isArrayType()) 4720 return false; 4721 4722 // A return statement in a void function must have void type. 4723 if (RhsT->isVoidType()) 4724 return LhsT->isVoidType(); 4725 4726 // A function definition requires a complete, non-abstract return type. 4727 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT)) 4728 return false; 4729 4730 // Compute the result of add_rvalue_reference. 4731 if (LhsT->isObjectType() || LhsT->isFunctionType()) 4732 LhsT = Self.Context.getRValueReferenceType(LhsT); 4733 4734 // Build a fake source and destination for initialization. 4735 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT)); 4736 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context), 4737 Expr::getValueKindForType(LhsT)); 4738 Expr *FromPtr = &From; 4739 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc, 4740 SourceLocation())); 4741 4742 // Perform the initialization in an unevaluated context within a SFINAE 4743 // trap at translation unit scope. 4744 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated); 4745 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true); 4746 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl()); 4747 InitializationSequence Init(Self, To, Kind, FromPtr); 4748 if (Init.Failed()) 4749 return false; 4750 4751 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr); 4752 return !Result.isInvalid() && !SFINAE.hasErrorOccurred(); 4753 } 4754 4755 case BTT_IsAssignable: 4756 case BTT_IsNothrowAssignable: 4757 case BTT_IsTriviallyAssignable: { 4758 // C++11 [meta.unary.prop]p3: 4759 // is_trivially_assignable is defined as: 4760 // is_assignable<T, U>::value is true and the assignment, as defined by 4761 // is_assignable, is known to call no operation that is not trivial 4762 // 4763 // is_assignable is defined as: 4764 // The expression declval<T>() = declval<U>() is well-formed when 4765 // treated as an unevaluated operand (Clause 5). 4766 // 4767 // For both, T and U shall be complete types, (possibly cv-qualified) 4768 // void, or arrays of unknown bound. 4769 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() && 4770 Self.RequireCompleteType(KeyLoc, LhsT, 4771 diag::err_incomplete_type_used_in_type_trait_expr)) 4772 return false; 4773 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() && 4774 Self.RequireCompleteType(KeyLoc, RhsT, 4775 diag::err_incomplete_type_used_in_type_trait_expr)) 4776 return false; 4777 4778 // cv void is never assignable. 4779 if (LhsT->isVoidType() || RhsT->isVoidType()) 4780 return false; 4781 4782 // Build expressions that emulate the effect of declval<T>() and 4783 // declval<U>(). 4784 if (LhsT->isObjectType() || LhsT->isFunctionType()) 4785 LhsT = Self.Context.getRValueReferenceType(LhsT); 4786 if (RhsT->isObjectType() || RhsT->isFunctionType()) 4787 RhsT = Self.Context.getRValueReferenceType(RhsT); 4788 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context), 4789 Expr::getValueKindForType(LhsT)); 4790 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context), 4791 Expr::getValueKindForType(RhsT)); 4792 4793 // Attempt the assignment in an unevaluated context within a SFINAE 4794 // trap at translation unit scope. 4795 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated); 4796 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true); 4797 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl()); 4798 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs, 4799 &Rhs); 4800 if (Result.isInvalid() || SFINAE.hasErrorOccurred()) 4801 return false; 4802 4803 if (BTT == BTT_IsAssignable) 4804 return true; 4805 4806 if (BTT == BTT_IsNothrowAssignable) 4807 return Self.canThrow(Result.get()) == CT_Cannot; 4808 4809 if (BTT == BTT_IsTriviallyAssignable) { 4810 // Under Objective-C ARC, if the destination has non-trivial Objective-C 4811 // lifetime, this is a non-trivial assignment. 4812 if (Self.getLangOpts().ObjCAutoRefCount && 4813 hasNontrivialObjCLifetime(LhsT.getNonReferenceType())) 4814 return false; 4815 4816 return !Result.get()->hasNonTrivialCall(Self.Context); 4817 } 4818 4819 llvm_unreachable("unhandled type trait"); 4820 return false; 4821 } 4822 default: llvm_unreachable("not a BTT"); 4823 } 4824 llvm_unreachable("Unknown type trait or not implemented"); 4825 } 4826 4827 ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT, 4828 SourceLocation KWLoc, 4829 ParsedType Ty, 4830 Expr* DimExpr, 4831 SourceLocation RParen) { 4832 TypeSourceInfo *TSInfo; 4833 QualType T = GetTypeFromParser(Ty, &TSInfo); 4834 if (!TSInfo) 4835 TSInfo = Context.getTrivialTypeSourceInfo(T); 4836 4837 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen); 4838 } 4839 4840 static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT, 4841 QualType T, Expr *DimExpr, 4842 SourceLocation KeyLoc) { 4843 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type"); 4844 4845 switch(ATT) { 4846 case ATT_ArrayRank: 4847 if (T->isArrayType()) { 4848 unsigned Dim = 0; 4849 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) { 4850 ++Dim; 4851 T = AT->getElementType(); 4852 } 4853 return Dim; 4854 } 4855 return 0; 4856 4857 case ATT_ArrayExtent: { 4858 llvm::APSInt Value; 4859 uint64_t Dim; 4860 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value, 4861 diag::err_dimension_expr_not_constant_integer, 4862 false).isInvalid()) 4863 return 0; 4864 if (Value.isSigned() && Value.isNegative()) { 4865 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) 4866 << DimExpr->getSourceRange(); 4867 return 0; 4868 } 4869 Dim = Value.getLimitedValue(); 4870 4871 if (T->isArrayType()) { 4872 unsigned D = 0; 4873 bool Matched = false; 4874 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) { 4875 if (Dim == D) { 4876 Matched = true; 4877 break; 4878 } 4879 ++D; 4880 T = AT->getElementType(); 4881 } 4882 4883 if (Matched && T->isArrayType()) { 4884 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T)) 4885 return CAT->getSize().getLimitedValue(); 4886 } 4887 } 4888 return 0; 4889 } 4890 } 4891 llvm_unreachable("Unknown type trait or not implemented"); 4892 } 4893 4894 ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT, 4895 SourceLocation KWLoc, 4896 TypeSourceInfo *TSInfo, 4897 Expr* DimExpr, 4898 SourceLocation RParen) { 4899 QualType T = TSInfo->getType(); 4900 4901 // FIXME: This should likely be tracked as an APInt to remove any host 4902 // assumptions about the width of size_t on the target. 4903 uint64_t Value = 0; 4904 if (!T->isDependentType()) 4905 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc); 4906 4907 // While the specification for these traits from the Embarcadero C++ 4908 // compiler's documentation says the return type is 'unsigned int', Clang 4909 // returns 'size_t'. On Windows, the primary platform for the Embarcadero 4910 // compiler, there is no difference. On several other platforms this is an 4911 // important distinction. 4912 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr, 4913 RParen, Context.getSizeType()); 4914 } 4915 4916 ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET, 4917 SourceLocation KWLoc, 4918 Expr *Queried, 4919 SourceLocation RParen) { 4920 // If error parsing the expression, ignore. 4921 if (!Queried) 4922 return ExprError(); 4923 4924 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen); 4925 4926 return Result; 4927 } 4928 4929 static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) { 4930 switch (ET) { 4931 case ET_IsLValueExpr: return E->isLValue(); 4932 case ET_IsRValueExpr: return E->isRValue(); 4933 } 4934 llvm_unreachable("Expression trait not covered by switch"); 4935 } 4936 4937 ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET, 4938 SourceLocation KWLoc, 4939 Expr *Queried, 4940 SourceLocation RParen) { 4941 if (Queried->isTypeDependent()) { 4942 // Delay type-checking for type-dependent expressions. 4943 } else if (Queried->getType()->isPlaceholderType()) { 4944 ExprResult PE = CheckPlaceholderExpr(Queried); 4945 if (PE.isInvalid()) return ExprError(); 4946 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen); 4947 } 4948 4949 bool Value = EvaluateExpressionTrait(ET, Queried); 4950 4951 return new (Context) 4952 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy); 4953 } 4954 4955 QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, 4956 ExprValueKind &VK, 4957 SourceLocation Loc, 4958 bool isIndirect) { 4959 assert(!LHS.get()->getType()->isPlaceholderType() && 4960 !RHS.get()->getType()->isPlaceholderType() && 4961 "placeholders should have been weeded out by now"); 4962 4963 // The LHS undergoes lvalue conversions if this is ->*. 4964 if (isIndirect) { 4965 LHS = DefaultLvalueConversion(LHS.get()); 4966 if (LHS.isInvalid()) return QualType(); 4967 } 4968 4969 // The RHS always undergoes lvalue conversions. 4970 RHS = DefaultLvalueConversion(RHS.get()); 4971 if (RHS.isInvalid()) return QualType(); 4972 4973 const char *OpSpelling = isIndirect ? "->*" : ".*"; 4974 // C++ 5.5p2 4975 // The binary operator .* [p3: ->*] binds its second operand, which shall 4976 // be of type "pointer to member of T" (where T is a completely-defined 4977 // class type) [...] 4978 QualType RHSType = RHS.get()->getType(); 4979 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>(); 4980 if (!MemPtr) { 4981 Diag(Loc, diag::err_bad_memptr_rhs) 4982 << OpSpelling << RHSType << RHS.get()->getSourceRange(); 4983 return QualType(); 4984 } 4985 4986 QualType Class(MemPtr->getClass(), 0); 4987 4988 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the 4989 // member pointer points must be completely-defined. However, there is no 4990 // reason for this semantic distinction, and the rule is not enforced by 4991 // other compilers. Therefore, we do not check this property, as it is 4992 // likely to be considered a defect. 4993 4994 // C++ 5.5p2 4995 // [...] to its first operand, which shall be of class T or of a class of 4996 // which T is an unambiguous and accessible base class. [p3: a pointer to 4997 // such a class] 4998 QualType LHSType = LHS.get()->getType(); 4999 if (isIndirect) { 5000 if (const PointerType *Ptr = LHSType->getAs<PointerType>()) 5001 LHSType = Ptr->getPointeeType(); 5002 else { 5003 Diag(Loc, diag::err_bad_memptr_lhs) 5004 << OpSpelling << 1 << LHSType 5005 << FixItHint::CreateReplacement(SourceRange(Loc), ".*"); 5006 return QualType(); 5007 } 5008 } 5009 5010 if (!Context.hasSameUnqualifiedType(Class, LHSType)) { 5011 // If we want to check the hierarchy, we need a complete type. 5012 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs, 5013 OpSpelling, (int)isIndirect)) { 5014 return QualType(); 5015 } 5016 5017 if (!IsDerivedFrom(Loc, LHSType, Class)) { 5018 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling 5019 << (int)isIndirect << LHS.get()->getType(); 5020 return QualType(); 5021 } 5022 5023 CXXCastPath BasePath; 5024 if (CheckDerivedToBaseConversion(LHSType, Class, Loc, 5025 SourceRange(LHS.get()->getLocStart(), 5026 RHS.get()->getLocEnd()), 5027 &BasePath)) 5028 return QualType(); 5029 5030 // Cast LHS to type of use. 5031 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class; 5032 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind(); 5033 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK, 5034 &BasePath); 5035 } 5036 5037 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) { 5038 // Diagnose use of pointer-to-member type which when used as 5039 // the functional cast in a pointer-to-member expression. 5040 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect; 5041 return QualType(); 5042 } 5043 5044 // C++ 5.5p2 5045 // The result is an object or a function of the type specified by the 5046 // second operand. 5047 // The cv qualifiers are the union of those in the pointer and the left side, 5048 // in accordance with 5.5p5 and 5.2.5. 5049 QualType Result = MemPtr->getPointeeType(); 5050 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers()); 5051 5052 // C++0x [expr.mptr.oper]p6: 5053 // In a .* expression whose object expression is an rvalue, the program is 5054 // ill-formed if the second operand is a pointer to member function with 5055 // ref-qualifier &. In a ->* expression or in a .* expression whose object 5056 // expression is an lvalue, the program is ill-formed if the second operand 5057 // is a pointer to member function with ref-qualifier &&. 5058 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) { 5059 switch (Proto->getRefQualifier()) { 5060 case RQ_None: 5061 // Do nothing 5062 break; 5063 5064 case RQ_LValue: 5065 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) 5066 Diag(Loc, diag::err_pointer_to_member_oper_value_classify) 5067 << RHSType << 1 << LHS.get()->getSourceRange(); 5068 break; 5069 5070 case RQ_RValue: 5071 if (isIndirect || !LHS.get()->Classify(Context).isRValue()) 5072 Diag(Loc, diag::err_pointer_to_member_oper_value_classify) 5073 << RHSType << 0 << LHS.get()->getSourceRange(); 5074 break; 5075 } 5076 } 5077 5078 // C++ [expr.mptr.oper]p6: 5079 // The result of a .* expression whose second operand is a pointer 5080 // to a data member is of the same value category as its 5081 // first operand. The result of a .* expression whose second 5082 // operand is a pointer to a member function is a prvalue. The 5083 // result of an ->* expression is an lvalue if its second operand 5084 // is a pointer to data member and a prvalue otherwise. 5085 if (Result->isFunctionType()) { 5086 VK = VK_RValue; 5087 return Context.BoundMemberTy; 5088 } else if (isIndirect) { 5089 VK = VK_LValue; 5090 } else { 5091 VK = LHS.get()->getValueKind(); 5092 } 5093 5094 return Result; 5095 } 5096 5097 /// \brief Try to convert a type to another according to C++11 5.16p3. 5098 /// 5099 /// This is part of the parameter validation for the ? operator. If either 5100 /// value operand is a class type, the two operands are attempted to be 5101 /// converted to each other. This function does the conversion in one direction. 5102 /// It returns true if the program is ill-formed and has already been diagnosed 5103 /// as such. 5104 static bool TryClassUnification(Sema &Self, Expr *From, Expr *To, 5105 SourceLocation QuestionLoc, 5106 bool &HaveConversion, 5107 QualType &ToType) { 5108 HaveConversion = false; 5109 ToType = To->getType(); 5110 5111 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(), 5112 SourceLocation()); 5113 // C++11 5.16p3 5114 // The process for determining whether an operand expression E1 of type T1 5115 // can be converted to match an operand expression E2 of type T2 is defined 5116 // as follows: 5117 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be 5118 // implicitly converted to type "lvalue reference to T2", subject to the 5119 // constraint that in the conversion the reference must bind directly to 5120 // an lvalue. 5121 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be 5122 // implicitly conveted to the type "rvalue reference to R2", subject to 5123 // the constraint that the reference must bind directly. 5124 if (To->isLValue() || To->isXValue()) { 5125 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType) 5126 : Self.Context.getRValueReferenceType(ToType); 5127 5128 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); 5129 5130 InitializationSequence InitSeq(Self, Entity, Kind, From); 5131 if (InitSeq.isDirectReferenceBinding()) { 5132 ToType = T; 5133 HaveConversion = true; 5134 return false; 5135 } 5136 5137 if (InitSeq.isAmbiguous()) 5138 return InitSeq.Diagnose(Self, Entity, Kind, From); 5139 } 5140 5141 // -- If E2 is an rvalue, or if the conversion above cannot be done: 5142 // -- if E1 and E2 have class type, and the underlying class types are 5143 // the same or one is a base class of the other: 5144 QualType FTy = From->getType(); 5145 QualType TTy = To->getType(); 5146 const RecordType *FRec = FTy->getAs<RecordType>(); 5147 const RecordType *TRec = TTy->getAs<RecordType>(); 5148 bool FDerivedFromT = FRec && TRec && FRec != TRec && 5149 Self.IsDerivedFrom(QuestionLoc, FTy, TTy); 5150 if (FRec && TRec && (FRec == TRec || FDerivedFromT || 5151 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) { 5152 // E1 can be converted to match E2 if the class of T2 is the 5153 // same type as, or a base class of, the class of T1, and 5154 // [cv2 > cv1]. 5155 if (FRec == TRec || FDerivedFromT) { 5156 if (TTy.isAtLeastAsQualifiedAs(FTy)) { 5157 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); 5158 InitializationSequence InitSeq(Self, Entity, Kind, From); 5159 if (InitSeq) { 5160 HaveConversion = true; 5161 return false; 5162 } 5163 5164 if (InitSeq.isAmbiguous()) 5165 return InitSeq.Diagnose(Self, Entity, Kind, From); 5166 } 5167 } 5168 5169 return false; 5170 } 5171 5172 // -- Otherwise: E1 can be converted to match E2 if E1 can be 5173 // implicitly converted to the type that expression E2 would have 5174 // if E2 were converted to an rvalue (or the type it has, if E2 is 5175 // an rvalue). 5176 // 5177 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not 5178 // to the array-to-pointer or function-to-pointer conversions. 5179 if (!TTy->getAs<TagType>()) 5180 TTy = TTy.getUnqualifiedType(); 5181 5182 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); 5183 InitializationSequence InitSeq(Self, Entity, Kind, From); 5184 HaveConversion = !InitSeq.Failed(); 5185 ToType = TTy; 5186 if (InitSeq.isAmbiguous()) 5187 return InitSeq.Diagnose(Self, Entity, Kind, From); 5188 5189 return false; 5190 } 5191 5192 /// \brief Try to find a common type for two according to C++0x 5.16p5. 5193 /// 5194 /// This is part of the parameter validation for the ? operator. If either 5195 /// value operand is a class type, overload resolution is used to find a 5196 /// conversion to a common type. 5197 static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS, 5198 SourceLocation QuestionLoc) { 5199 Expr *Args[2] = { LHS.get(), RHS.get() }; 5200 OverloadCandidateSet CandidateSet(QuestionLoc, 5201 OverloadCandidateSet::CSK_Operator); 5202 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 5203 CandidateSet); 5204 5205 OverloadCandidateSet::iterator Best; 5206 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) { 5207 case OR_Success: { 5208 // We found a match. Perform the conversions on the arguments and move on. 5209 ExprResult LHSRes = 5210 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0], 5211 Best->Conversions[0], Sema::AA_Converting); 5212 if (LHSRes.isInvalid()) 5213 break; 5214 LHS = LHSRes; 5215 5216 ExprResult RHSRes = 5217 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1], 5218 Best->Conversions[1], Sema::AA_Converting); 5219 if (RHSRes.isInvalid()) 5220 break; 5221 RHS = RHSRes; 5222 if (Best->Function) 5223 Self.MarkFunctionReferenced(QuestionLoc, Best->Function); 5224 return false; 5225 } 5226 5227 case OR_No_Viable_Function: 5228 5229 // Emit a better diagnostic if one of the expressions is a null pointer 5230 // constant and the other is a pointer type. In this case, the user most 5231 // likely forgot to take the address of the other expression. 5232 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 5233 return true; 5234 5235 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 5236 << LHS.get()->getType() << RHS.get()->getType() 5237 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5238 return true; 5239 5240 case OR_Ambiguous: 5241 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl) 5242 << LHS.get()->getType() << RHS.get()->getType() 5243 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5244 // FIXME: Print the possible common types by printing the return types of 5245 // the viable candidates. 5246 break; 5247 5248 case OR_Deleted: 5249 llvm_unreachable("Conditional operator has only built-in overloads"); 5250 } 5251 return true; 5252 } 5253 5254 /// \brief Perform an "extended" implicit conversion as returned by 5255 /// TryClassUnification. 5256 static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) { 5257 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); 5258 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(), 5259 SourceLocation()); 5260 Expr *Arg = E.get(); 5261 InitializationSequence InitSeq(Self, Entity, Kind, Arg); 5262 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg); 5263 if (Result.isInvalid()) 5264 return true; 5265 5266 E = Result; 5267 return false; 5268 } 5269 5270 /// \brief Check the operands of ?: under C++ semantics. 5271 /// 5272 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y 5273 /// extension. In this case, LHS == Cond. (But they're not aliases.) 5274 QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 5275 ExprResult &RHS, ExprValueKind &VK, 5276 ExprObjectKind &OK, 5277 SourceLocation QuestionLoc) { 5278 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++ 5279 // interface pointers. 5280 5281 // C++11 [expr.cond]p1 5282 // The first expression is contextually converted to bool. 5283 if (!Cond.get()->isTypeDependent()) { 5284 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get()); 5285 if (CondRes.isInvalid()) 5286 return QualType(); 5287 Cond = CondRes; 5288 } 5289 5290 // Assume r-value. 5291 VK = VK_RValue; 5292 OK = OK_Ordinary; 5293 5294 // Either of the arguments dependent? 5295 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent()) 5296 return Context.DependentTy; 5297 5298 // C++11 [expr.cond]p2 5299 // If either the second or the third operand has type (cv) void, ... 5300 QualType LTy = LHS.get()->getType(); 5301 QualType RTy = RHS.get()->getType(); 5302 bool LVoid = LTy->isVoidType(); 5303 bool RVoid = RTy->isVoidType(); 5304 if (LVoid || RVoid) { 5305 // ... one of the following shall hold: 5306 // -- The second or the third operand (but not both) is a (possibly 5307 // parenthesized) throw-expression; the result is of the type 5308 // and value category of the other. 5309 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts()); 5310 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts()); 5311 if (LThrow != RThrow) { 5312 Expr *NonThrow = LThrow ? RHS.get() : LHS.get(); 5313 VK = NonThrow->getValueKind(); 5314 // DR (no number yet): the result is a bit-field if the 5315 // non-throw-expression operand is a bit-field. 5316 OK = NonThrow->getObjectKind(); 5317 return NonThrow->getType(); 5318 } 5319 5320 // -- Both the second and third operands have type void; the result is of 5321 // type void and is a prvalue. 5322 if (LVoid && RVoid) 5323 return Context.VoidTy; 5324 5325 // Neither holds, error. 5326 Diag(QuestionLoc, diag::err_conditional_void_nonvoid) 5327 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1) 5328 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5329 return QualType(); 5330 } 5331 5332 // Neither is void. 5333 5334 // C++11 [expr.cond]p3 5335 // Otherwise, if the second and third operand have different types, and 5336 // either has (cv) class type [...] an attempt is made to convert each of 5337 // those operands to the type of the other. 5338 if (!Context.hasSameType(LTy, RTy) && 5339 (LTy->isRecordType() || RTy->isRecordType())) { 5340 // These return true if a single direction is already ambiguous. 5341 QualType L2RType, R2LType; 5342 bool HaveL2R, HaveR2L; 5343 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType)) 5344 return QualType(); 5345 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType)) 5346 return QualType(); 5347 5348 // If both can be converted, [...] the program is ill-formed. 5349 if (HaveL2R && HaveR2L) { 5350 Diag(QuestionLoc, diag::err_conditional_ambiguous) 5351 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5352 return QualType(); 5353 } 5354 5355 // If exactly one conversion is possible, that conversion is applied to 5356 // the chosen operand and the converted operands are used in place of the 5357 // original operands for the remainder of this section. 5358 if (HaveL2R) { 5359 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid()) 5360 return QualType(); 5361 LTy = LHS.get()->getType(); 5362 } else if (HaveR2L) { 5363 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid()) 5364 return QualType(); 5365 RTy = RHS.get()->getType(); 5366 } 5367 } 5368 5369 // C++11 [expr.cond]p3 5370 // if both are glvalues of the same value category and the same type except 5371 // for cv-qualification, an attempt is made to convert each of those 5372 // operands to the type of the other. 5373 // FIXME: 5374 // Resolving a defect in P0012R1: we extend this to cover all cases where 5375 // one of the operands is reference-compatible with the other, in order 5376 // to support conditionals between functions differing in noexcept. 5377 ExprValueKind LVK = LHS.get()->getValueKind(); 5378 ExprValueKind RVK = RHS.get()->getValueKind(); 5379 if (!Context.hasSameType(LTy, RTy) && 5380 LVK == RVK && LVK != VK_RValue) { 5381 // DerivedToBase was already handled by the class-specific case above. 5382 // FIXME: Should we allow ObjC conversions here? 5383 bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion; 5384 if (CompareReferenceRelationship( 5385 QuestionLoc, LTy, RTy, DerivedToBase, 5386 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible && 5387 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion) { 5388 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK); 5389 RTy = RHS.get()->getType(); 5390 } else if (CompareReferenceRelationship( 5391 QuestionLoc, RTy, LTy, DerivedToBase, 5392 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible && 5393 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion) { 5394 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK); 5395 LTy = LHS.get()->getType(); 5396 } 5397 } 5398 5399 // C++11 [expr.cond]p4 5400 // If the second and third operands are glvalues of the same value 5401 // category and have the same type, the result is of that type and 5402 // value category and it is a bit-field if the second or the third 5403 // operand is a bit-field, or if both are bit-fields. 5404 // We only extend this to bitfields, not to the crazy other kinds of 5405 // l-values. 5406 bool Same = Context.hasSameType(LTy, RTy); 5407 if (Same && LVK == RVK && LVK != VK_RValue && 5408 LHS.get()->isOrdinaryOrBitFieldObject() && 5409 RHS.get()->isOrdinaryOrBitFieldObject()) { 5410 VK = LHS.get()->getValueKind(); 5411 if (LHS.get()->getObjectKind() == OK_BitField || 5412 RHS.get()->getObjectKind() == OK_BitField) 5413 OK = OK_BitField; 5414 5415 // If we have function pointer types, unify them anyway to unify their 5416 // exception specifications, if any. 5417 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) { 5418 Qualifiers Qs = LTy.getQualifiers(); 5419 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS, 5420 /*ConvertArgs*/false); 5421 LTy = Context.getQualifiedType(LTy, Qs); 5422 5423 assert(!LTy.isNull() && "failed to find composite pointer type for " 5424 "canonically equivalent function ptr types"); 5425 assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type"); 5426 } 5427 5428 return LTy; 5429 } 5430 5431 // C++11 [expr.cond]p5 5432 // Otherwise, the result is a prvalue. If the second and third operands 5433 // do not have the same type, and either has (cv) class type, ... 5434 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) { 5435 // ... overload resolution is used to determine the conversions (if any) 5436 // to be applied to the operands. If the overload resolution fails, the 5437 // program is ill-formed. 5438 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc)) 5439 return QualType(); 5440 } 5441 5442 // C++11 [expr.cond]p6 5443 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard 5444 // conversions are performed on the second and third operands. 5445 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 5446 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 5447 if (LHS.isInvalid() || RHS.isInvalid()) 5448 return QualType(); 5449 LTy = LHS.get()->getType(); 5450 RTy = RHS.get()->getType(); 5451 5452 // After those conversions, one of the following shall hold: 5453 // -- The second and third operands have the same type; the result 5454 // is of that type. If the operands have class type, the result 5455 // is a prvalue temporary of the result type, which is 5456 // copy-initialized from either the second operand or the third 5457 // operand depending on the value of the first operand. 5458 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) { 5459 if (LTy->isRecordType()) { 5460 // The operands have class type. Make a temporary copy. 5461 if (RequireNonAbstractType(QuestionLoc, LTy, 5462 diag::err_allocation_of_abstract_type)) 5463 return QualType(); 5464 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy); 5465 5466 ExprResult LHSCopy = PerformCopyInitialization(Entity, 5467 SourceLocation(), 5468 LHS); 5469 if (LHSCopy.isInvalid()) 5470 return QualType(); 5471 5472 ExprResult RHSCopy = PerformCopyInitialization(Entity, 5473 SourceLocation(), 5474 RHS); 5475 if (RHSCopy.isInvalid()) 5476 return QualType(); 5477 5478 LHS = LHSCopy; 5479 RHS = RHSCopy; 5480 } 5481 5482 // If we have function pointer types, unify them anyway to unify their 5483 // exception specifications, if any. 5484 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) { 5485 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS); 5486 assert(!LTy.isNull() && "failed to find composite pointer type for " 5487 "canonically equivalent function ptr types"); 5488 } 5489 5490 return LTy; 5491 } 5492 5493 // Extension: conditional operator involving vector types. 5494 if (LTy->isVectorType() || RTy->isVectorType()) 5495 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 5496 /*AllowBothBool*/true, 5497 /*AllowBoolConversions*/false); 5498 5499 // -- The second and third operands have arithmetic or enumeration type; 5500 // the usual arithmetic conversions are performed to bring them to a 5501 // common type, and the result is of that type. 5502 if (LTy->isArithmeticType() && RTy->isArithmeticType()) { 5503 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 5504 if (LHS.isInvalid() || RHS.isInvalid()) 5505 return QualType(); 5506 if (ResTy.isNull()) { 5507 Diag(QuestionLoc, 5508 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy 5509 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5510 return QualType(); 5511 } 5512 5513 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 5514 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 5515 5516 return ResTy; 5517 } 5518 5519 // -- The second and third operands have pointer type, or one has pointer 5520 // type and the other is a null pointer constant, or both are null 5521 // pointer constants, at least one of which is non-integral; pointer 5522 // conversions and qualification conversions are performed to bring them 5523 // to their composite pointer type. The result is of the composite 5524 // pointer type. 5525 // -- The second and third operands have pointer to member type, or one has 5526 // pointer to member type and the other is a null pointer constant; 5527 // pointer to member conversions and qualification conversions are 5528 // performed to bring them to a common type, whose cv-qualification 5529 // shall match the cv-qualification of either the second or the third 5530 // operand. The result is of the common type. 5531 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS); 5532 if (!Composite.isNull()) 5533 return Composite; 5534 5535 // Similarly, attempt to find composite type of two objective-c pointers. 5536 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc); 5537 if (!Composite.isNull()) 5538 return Composite; 5539 5540 // Check if we are using a null with a non-pointer type. 5541 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 5542 return QualType(); 5543 5544 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 5545 << LHS.get()->getType() << RHS.get()->getType() 5546 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5547 return QualType(); 5548 } 5549 5550 static FunctionProtoType::ExceptionSpecInfo 5551 mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1, 5552 FunctionProtoType::ExceptionSpecInfo ESI2, 5553 SmallVectorImpl<QualType> &ExceptionTypeStorage) { 5554 ExceptionSpecificationType EST1 = ESI1.Type; 5555 ExceptionSpecificationType EST2 = ESI2.Type; 5556 5557 // If either of them can throw anything, that is the result. 5558 if (EST1 == EST_None) return ESI1; 5559 if (EST2 == EST_None) return ESI2; 5560 if (EST1 == EST_MSAny) return ESI1; 5561 if (EST2 == EST_MSAny) return ESI2; 5562 5563 // If either of them is non-throwing, the result is the other. 5564 if (EST1 == EST_DynamicNone) return ESI2; 5565 if (EST2 == EST_DynamicNone) return ESI1; 5566 if (EST1 == EST_BasicNoexcept) return ESI2; 5567 if (EST2 == EST_BasicNoexcept) return ESI1; 5568 5569 // If either of them is a non-value-dependent computed noexcept, that 5570 // determines the result. 5571 if (EST2 == EST_ComputedNoexcept && ESI2.NoexceptExpr && 5572 !ESI2.NoexceptExpr->isValueDependent()) 5573 return !ESI2.NoexceptExpr->EvaluateKnownConstInt(S.Context) ? ESI2 : ESI1; 5574 if (EST1 == EST_ComputedNoexcept && ESI1.NoexceptExpr && 5575 !ESI1.NoexceptExpr->isValueDependent()) 5576 return !ESI1.NoexceptExpr->EvaluateKnownConstInt(S.Context) ? ESI1 : ESI2; 5577 // If we're left with value-dependent computed noexcept expressions, we're 5578 // stuck. Before C++17, we can just drop the exception specification entirely, 5579 // since it's not actually part of the canonical type. And this should never 5580 // happen in C++17, because it would mean we were computing the composite 5581 // pointer type of dependent types, which should never happen. 5582 if (EST1 == EST_ComputedNoexcept || EST2 == EST_ComputedNoexcept) { 5583 assert(!S.getLangOpts().CPlusPlus1z && 5584 "computing composite pointer type of dependent types"); 5585 return FunctionProtoType::ExceptionSpecInfo(); 5586 } 5587 5588 // Switch over the possibilities so that people adding new values know to 5589 // update this function. 5590 switch (EST1) { 5591 case EST_None: 5592 case EST_DynamicNone: 5593 case EST_MSAny: 5594 case EST_BasicNoexcept: 5595 case EST_ComputedNoexcept: 5596 llvm_unreachable("handled above"); 5597 5598 case EST_Dynamic: { 5599 // This is the fun case: both exception specifications are dynamic. Form 5600 // the union of the two lists. 5601 assert(EST2 == EST_Dynamic && "other cases should already be handled"); 5602 llvm::SmallPtrSet<QualType, 8> Found; 5603 for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions}) 5604 for (QualType E : Exceptions) 5605 if (Found.insert(S.Context.getCanonicalType(E)).second) 5606 ExceptionTypeStorage.push_back(E); 5607 5608 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic); 5609 Result.Exceptions = ExceptionTypeStorage; 5610 return Result; 5611 } 5612 5613 case EST_Unevaluated: 5614 case EST_Uninstantiated: 5615 case EST_Unparsed: 5616 llvm_unreachable("shouldn't see unresolved exception specifications here"); 5617 } 5618 5619 llvm_unreachable("invalid ExceptionSpecificationType"); 5620 } 5621 5622 /// \brief Find a merged pointer type and convert the two expressions to it. 5623 /// 5624 /// This finds the composite pointer type (or member pointer type) for @p E1 5625 /// and @p E2 according to C++1z 5p14. It converts both expressions to this 5626 /// type and returns it. 5627 /// It does not emit diagnostics. 5628 /// 5629 /// \param Loc The location of the operator requiring these two expressions to 5630 /// be converted to the composite pointer type. 5631 /// 5632 /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type. 5633 QualType Sema::FindCompositePointerType(SourceLocation Loc, 5634 Expr *&E1, Expr *&E2, 5635 bool ConvertArgs) { 5636 assert(getLangOpts().CPlusPlus && "This function assumes C++"); 5637 5638 // C++1z [expr]p14: 5639 // The composite pointer type of two operands p1 and p2 having types T1 5640 // and T2 5641 QualType T1 = E1->getType(), T2 = E2->getType(); 5642 5643 // where at least one is a pointer or pointer to member type or 5644 // std::nullptr_t is: 5645 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() || 5646 T1->isNullPtrType(); 5647 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() || 5648 T2->isNullPtrType(); 5649 if (!T1IsPointerLike && !T2IsPointerLike) 5650 return QualType(); 5651 5652 // - if both p1 and p2 are null pointer constants, std::nullptr_t; 5653 // This can't actually happen, following the standard, but we also use this 5654 // to implement the end of [expr.conv], which hits this case. 5655 // 5656 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively; 5657 if (T1IsPointerLike && 5658 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 5659 if (ConvertArgs) 5660 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType() 5661 ? CK_NullToMemberPointer 5662 : CK_NullToPointer).get(); 5663 return T1; 5664 } 5665 if (T2IsPointerLike && 5666 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 5667 if (ConvertArgs) 5668 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType() 5669 ? CK_NullToMemberPointer 5670 : CK_NullToPointer).get(); 5671 return T2; 5672 } 5673 5674 // Now both have to be pointers or member pointers. 5675 if (!T1IsPointerLike || !T2IsPointerLike) 5676 return QualType(); 5677 assert(!T1->isNullPtrType() && !T2->isNullPtrType() && 5678 "nullptr_t should be a null pointer constant"); 5679 5680 // - if T1 or T2 is "pointer to cv1 void" and the other type is 5681 // "pointer to cv2 T", "pointer to cv12 void", where cv12 is 5682 // the union of cv1 and cv2; 5683 // - if T1 or T2 is "pointer to noexcept function" and the other type is 5684 // "pointer to function", where the function types are otherwise the same, 5685 // "pointer to function"; 5686 // FIXME: This rule is defective: it should also permit removing noexcept 5687 // from a pointer to member function. As a Clang extension, we also 5688 // permit removing 'noreturn', so we generalize this rule to; 5689 // - [Clang] If T1 and T2 are both of type "pointer to function" or 5690 // "pointer to member function" and the pointee types can be unified 5691 // by a function pointer conversion, that conversion is applied 5692 // before checking the following rules. 5693 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1 5694 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3), 5695 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1, 5696 // respectively; 5697 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer 5698 // to member of C2 of type cv2 U2" where C1 is reference-related to C2 or 5699 // C2 is reference-related to C1 (8.6.3), the cv-combined type of T2 and 5700 // T1 or the cv-combined type of T1 and T2, respectively; 5701 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and 5702 // T2; 5703 // 5704 // If looked at in the right way, these bullets all do the same thing. 5705 // What we do here is, we build the two possible cv-combined types, and try 5706 // the conversions in both directions. If only one works, or if the two 5707 // composite types are the same, we have succeeded. 5708 // FIXME: extended qualifiers? 5709 // 5710 // Note that this will fail to find a composite pointer type for "pointer 5711 // to void" and "pointer to function". We can't actually perform the final 5712 // conversion in this case, even though a composite pointer type formally 5713 // exists. 5714 SmallVector<unsigned, 4> QualifierUnion; 5715 SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass; 5716 QualType Composite1 = T1; 5717 QualType Composite2 = T2; 5718 unsigned NeedConstBefore = 0; 5719 while (true) { 5720 const PointerType *Ptr1, *Ptr2; 5721 if ((Ptr1 = Composite1->getAs<PointerType>()) && 5722 (Ptr2 = Composite2->getAs<PointerType>())) { 5723 Composite1 = Ptr1->getPointeeType(); 5724 Composite2 = Ptr2->getPointeeType(); 5725 5726 // If we're allowed to create a non-standard composite type, keep track 5727 // of where we need to fill in additional 'const' qualifiers. 5728 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers()) 5729 NeedConstBefore = QualifierUnion.size(); 5730 5731 QualifierUnion.push_back( 5732 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); 5733 MemberOfClass.push_back(std::make_pair(nullptr, nullptr)); 5734 continue; 5735 } 5736 5737 const MemberPointerType *MemPtr1, *MemPtr2; 5738 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) && 5739 (MemPtr2 = Composite2->getAs<MemberPointerType>())) { 5740 Composite1 = MemPtr1->getPointeeType(); 5741 Composite2 = MemPtr2->getPointeeType(); 5742 5743 // If we're allowed to create a non-standard composite type, keep track 5744 // of where we need to fill in additional 'const' qualifiers. 5745 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers()) 5746 NeedConstBefore = QualifierUnion.size(); 5747 5748 QualifierUnion.push_back( 5749 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); 5750 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(), 5751 MemPtr2->getClass())); 5752 continue; 5753 } 5754 5755 // FIXME: block pointer types? 5756 5757 // Cannot unwrap any more types. 5758 break; 5759 } 5760 5761 // Apply the function pointer conversion to unify the types. We've already 5762 // unwrapped down to the function types, and we want to merge rather than 5763 // just convert, so do this ourselves rather than calling 5764 // IsFunctionConversion. 5765 // 5766 // FIXME: In order to match the standard wording as closely as possible, we 5767 // currently only do this under a single level of pointers. Ideally, we would 5768 // allow this in general, and set NeedConstBefore to the relevant depth on 5769 // the side(s) where we changed anything. 5770 if (QualifierUnion.size() == 1) { 5771 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) { 5772 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) { 5773 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo(); 5774 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo(); 5775 5776 // The result is noreturn if both operands are. 5777 bool Noreturn = 5778 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn(); 5779 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn); 5780 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn); 5781 5782 // The result is nothrow if both operands are. 5783 SmallVector<QualType, 8> ExceptionTypeStorage; 5784 EPI1.ExceptionSpec = EPI2.ExceptionSpec = 5785 mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec, 5786 ExceptionTypeStorage); 5787 5788 Composite1 = Context.getFunctionType(FPT1->getReturnType(), 5789 FPT1->getParamTypes(), EPI1); 5790 Composite2 = Context.getFunctionType(FPT2->getReturnType(), 5791 FPT2->getParamTypes(), EPI2); 5792 } 5793 } 5794 } 5795 5796 if (NeedConstBefore) { 5797 // Extension: Add 'const' to qualifiers that come before the first qualifier 5798 // mismatch, so that our (non-standard!) composite type meets the 5799 // requirements of C++ [conv.qual]p4 bullet 3. 5800 for (unsigned I = 0; I != NeedConstBefore; ++I) 5801 if ((QualifierUnion[I] & Qualifiers::Const) == 0) 5802 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const; 5803 } 5804 5805 // Rewrap the composites as pointers or member pointers with the union CVRs. 5806 auto MOC = MemberOfClass.rbegin(); 5807 for (unsigned CVR : llvm::reverse(QualifierUnion)) { 5808 Qualifiers Quals = Qualifiers::fromCVRMask(CVR); 5809 auto Classes = *MOC++; 5810 if (Classes.first && Classes.second) { 5811 // Rebuild member pointer type 5812 Composite1 = Context.getMemberPointerType( 5813 Context.getQualifiedType(Composite1, Quals), Classes.first); 5814 Composite2 = Context.getMemberPointerType( 5815 Context.getQualifiedType(Composite2, Quals), Classes.second); 5816 } else { 5817 // Rebuild pointer type 5818 Composite1 = 5819 Context.getPointerType(Context.getQualifiedType(Composite1, Quals)); 5820 Composite2 = 5821 Context.getPointerType(Context.getQualifiedType(Composite2, Quals)); 5822 } 5823 } 5824 5825 struct Conversion { 5826 Sema &S; 5827 Expr *&E1, *&E2; 5828 QualType Composite; 5829 InitializedEntity Entity; 5830 InitializationKind Kind; 5831 InitializationSequence E1ToC, E2ToC; 5832 bool Viable; 5833 5834 Conversion(Sema &S, SourceLocation Loc, Expr *&E1, Expr *&E2, 5835 QualType Composite) 5836 : S(S), E1(E1), E2(E2), Composite(Composite), 5837 Entity(InitializedEntity::InitializeTemporary(Composite)), 5838 Kind(InitializationKind::CreateCopy(Loc, SourceLocation())), 5839 E1ToC(S, Entity, Kind, E1), E2ToC(S, Entity, Kind, E2), 5840 Viable(E1ToC && E2ToC) {} 5841 5842 bool perform() { 5843 ExprResult E1Result = E1ToC.Perform(S, Entity, Kind, E1); 5844 if (E1Result.isInvalid()) 5845 return true; 5846 E1 = E1Result.getAs<Expr>(); 5847 5848 ExprResult E2Result = E2ToC.Perform(S, Entity, Kind, E2); 5849 if (E2Result.isInvalid()) 5850 return true; 5851 E2 = E2Result.getAs<Expr>(); 5852 5853 return false; 5854 } 5855 }; 5856 5857 // Try to convert to each composite pointer type. 5858 Conversion C1(*this, Loc, E1, E2, Composite1); 5859 if (C1.Viable && Context.hasSameType(Composite1, Composite2)) { 5860 if (ConvertArgs && C1.perform()) 5861 return QualType(); 5862 return C1.Composite; 5863 } 5864 Conversion C2(*this, Loc, E1, E2, Composite2); 5865 5866 if (C1.Viable == C2.Viable) { 5867 // Either Composite1 and Composite2 are viable and are different, or 5868 // neither is viable. 5869 // FIXME: How both be viable and different? 5870 return QualType(); 5871 } 5872 5873 // Convert to the chosen type. 5874 if (ConvertArgs && (C1.Viable ? C1 : C2).perform()) 5875 return QualType(); 5876 5877 return C1.Viable ? C1.Composite : C2.Composite; 5878 } 5879 5880 ExprResult Sema::MaybeBindToTemporary(Expr *E) { 5881 if (!E) 5882 return ExprError(); 5883 5884 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?"); 5885 5886 // If the result is a glvalue, we shouldn't bind it. 5887 if (!E->isRValue()) 5888 return E; 5889 5890 // In ARC, calls that return a retainable type can return retained, 5891 // in which case we have to insert a consuming cast. 5892 if (getLangOpts().ObjCAutoRefCount && 5893 E->getType()->isObjCRetainableType()) { 5894 5895 bool ReturnsRetained; 5896 5897 // For actual calls, we compute this by examining the type of the 5898 // called value. 5899 if (CallExpr *Call = dyn_cast<CallExpr>(E)) { 5900 Expr *Callee = Call->getCallee()->IgnoreParens(); 5901 QualType T = Callee->getType(); 5902 5903 if (T == Context.BoundMemberTy) { 5904 // Handle pointer-to-members. 5905 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee)) 5906 T = BinOp->getRHS()->getType(); 5907 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee)) 5908 T = Mem->getMemberDecl()->getType(); 5909 } 5910 5911 if (const PointerType *Ptr = T->getAs<PointerType>()) 5912 T = Ptr->getPointeeType(); 5913 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>()) 5914 T = Ptr->getPointeeType(); 5915 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>()) 5916 T = MemPtr->getPointeeType(); 5917 5918 const FunctionType *FTy = T->getAs<FunctionType>(); 5919 assert(FTy && "call to value not of function type?"); 5920 ReturnsRetained = FTy->getExtInfo().getProducesResult(); 5921 5922 // ActOnStmtExpr arranges things so that StmtExprs of retainable 5923 // type always produce a +1 object. 5924 } else if (isa<StmtExpr>(E)) { 5925 ReturnsRetained = true; 5926 5927 // We hit this case with the lambda conversion-to-block optimization; 5928 // we don't want any extra casts here. 5929 } else if (isa<CastExpr>(E) && 5930 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) { 5931 return E; 5932 5933 // For message sends and property references, we try to find an 5934 // actual method. FIXME: we should infer retention by selector in 5935 // cases where we don't have an actual method. 5936 } else { 5937 ObjCMethodDecl *D = nullptr; 5938 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) { 5939 D = Send->getMethodDecl(); 5940 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) { 5941 D = BoxedExpr->getBoxingMethod(); 5942 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) { 5943 D = ArrayLit->getArrayWithObjectsMethod(); 5944 } else if (ObjCDictionaryLiteral *DictLit 5945 = dyn_cast<ObjCDictionaryLiteral>(E)) { 5946 D = DictLit->getDictWithObjectsMethod(); 5947 } 5948 5949 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>()); 5950 5951 // Don't do reclaims on performSelector calls; despite their 5952 // return type, the invoked method doesn't necessarily actually 5953 // return an object. 5954 if (!ReturnsRetained && 5955 D && D->getMethodFamily() == OMF_performSelector) 5956 return E; 5957 } 5958 5959 // Don't reclaim an object of Class type. 5960 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType()) 5961 return E; 5962 5963 Cleanup.setExprNeedsCleanups(true); 5964 5965 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject 5966 : CK_ARCReclaimReturnedObject); 5967 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr, 5968 VK_RValue); 5969 } 5970 5971 if (!getLangOpts().CPlusPlus) 5972 return E; 5973 5974 // Search for the base element type (cf. ASTContext::getBaseElementType) with 5975 // a fast path for the common case that the type is directly a RecordType. 5976 const Type *T = Context.getCanonicalType(E->getType().getTypePtr()); 5977 const RecordType *RT = nullptr; 5978 while (!RT) { 5979 switch (T->getTypeClass()) { 5980 case Type::Record: 5981 RT = cast<RecordType>(T); 5982 break; 5983 case Type::ConstantArray: 5984 case Type::IncompleteArray: 5985 case Type::VariableArray: 5986 case Type::DependentSizedArray: 5987 T = cast<ArrayType>(T)->getElementType().getTypePtr(); 5988 break; 5989 default: 5990 return E; 5991 } 5992 } 5993 5994 // That should be enough to guarantee that this type is complete, if we're 5995 // not processing a decltype expression. 5996 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 5997 if (RD->isInvalidDecl() || RD->isDependentContext()) 5998 return E; 5999 6000 bool IsDecltype = ExprEvalContexts.back().IsDecltype; 6001 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD); 6002 6003 if (Destructor) { 6004 MarkFunctionReferenced(E->getExprLoc(), Destructor); 6005 CheckDestructorAccess(E->getExprLoc(), Destructor, 6006 PDiag(diag::err_access_dtor_temp) 6007 << E->getType()); 6008 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc())) 6009 return ExprError(); 6010 6011 // If destructor is trivial, we can avoid the extra copy. 6012 if (Destructor->isTrivial()) 6013 return E; 6014 6015 // We need a cleanup, but we don't need to remember the temporary. 6016 Cleanup.setExprNeedsCleanups(true); 6017 } 6018 6019 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor); 6020 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E); 6021 6022 if (IsDecltype) 6023 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind); 6024 6025 return Bind; 6026 } 6027 6028 ExprResult 6029 Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) { 6030 if (SubExpr.isInvalid()) 6031 return ExprError(); 6032 6033 return MaybeCreateExprWithCleanups(SubExpr.get()); 6034 } 6035 6036 Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) { 6037 assert(SubExpr && "subexpression can't be null!"); 6038 6039 CleanupVarDeclMarking(); 6040 6041 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects; 6042 assert(ExprCleanupObjects.size() >= FirstCleanup); 6043 assert(Cleanup.exprNeedsCleanups() || 6044 ExprCleanupObjects.size() == FirstCleanup); 6045 if (!Cleanup.exprNeedsCleanups()) 6046 return SubExpr; 6047 6048 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup, 6049 ExprCleanupObjects.size() - FirstCleanup); 6050 6051 auto *E = ExprWithCleanups::Create( 6052 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups); 6053 DiscardCleanupsInEvaluationContext(); 6054 6055 return E; 6056 } 6057 6058 Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) { 6059 assert(SubStmt && "sub-statement can't be null!"); 6060 6061 CleanupVarDeclMarking(); 6062 6063 if (!Cleanup.exprNeedsCleanups()) 6064 return SubStmt; 6065 6066 // FIXME: In order to attach the temporaries, wrap the statement into 6067 // a StmtExpr; currently this is only used for asm statements. 6068 // This is hacky, either create a new CXXStmtWithTemporaries statement or 6069 // a new AsmStmtWithTemporaries. 6070 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, SubStmt, 6071 SourceLocation(), 6072 SourceLocation()); 6073 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(), 6074 SourceLocation()); 6075 return MaybeCreateExprWithCleanups(E); 6076 } 6077 6078 /// Process the expression contained within a decltype. For such expressions, 6079 /// certain semantic checks on temporaries are delayed until this point, and 6080 /// are omitted for the 'topmost' call in the decltype expression. If the 6081 /// topmost call bound a temporary, strip that temporary off the expression. 6082 ExprResult Sema::ActOnDecltypeExpression(Expr *E) { 6083 assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression"); 6084 6085 // C++11 [expr.call]p11: 6086 // If a function call is a prvalue of object type, 6087 // -- if the function call is either 6088 // -- the operand of a decltype-specifier, or 6089 // -- the right operand of a comma operator that is the operand of a 6090 // decltype-specifier, 6091 // a temporary object is not introduced for the prvalue. 6092 6093 // Recursively rebuild ParenExprs and comma expressions to strip out the 6094 // outermost CXXBindTemporaryExpr, if any. 6095 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 6096 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr()); 6097 if (SubExpr.isInvalid()) 6098 return ExprError(); 6099 if (SubExpr.get() == PE->getSubExpr()) 6100 return E; 6101 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get()); 6102 } 6103 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 6104 if (BO->getOpcode() == BO_Comma) { 6105 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS()); 6106 if (RHS.isInvalid()) 6107 return ExprError(); 6108 if (RHS.get() == BO->getRHS()) 6109 return E; 6110 return new (Context) BinaryOperator( 6111 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(), 6112 BO->getObjectKind(), BO->getOperatorLoc(), BO->isFPContractable()); 6113 } 6114 } 6115 6116 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E); 6117 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr()) 6118 : nullptr; 6119 if (TopCall) 6120 E = TopCall; 6121 else 6122 TopBind = nullptr; 6123 6124 // Disable the special decltype handling now. 6125 ExprEvalContexts.back().IsDecltype = false; 6126 6127 // In MS mode, don't perform any extra checking of call return types within a 6128 // decltype expression. 6129 if (getLangOpts().MSVCCompat) 6130 return E; 6131 6132 // Perform the semantic checks we delayed until this point. 6133 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size(); 6134 I != N; ++I) { 6135 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I]; 6136 if (Call == TopCall) 6137 continue; 6138 6139 if (CheckCallReturnType(Call->getCallReturnType(Context), 6140 Call->getLocStart(), 6141 Call, Call->getDirectCallee())) 6142 return ExprError(); 6143 } 6144 6145 // Now all relevant types are complete, check the destructors are accessible 6146 // and non-deleted, and annotate them on the temporaries. 6147 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size(); 6148 I != N; ++I) { 6149 CXXBindTemporaryExpr *Bind = 6150 ExprEvalContexts.back().DelayedDecltypeBinds[I]; 6151 if (Bind == TopBind) 6152 continue; 6153 6154 CXXTemporary *Temp = Bind->getTemporary(); 6155 6156 CXXRecordDecl *RD = 6157 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 6158 CXXDestructorDecl *Destructor = LookupDestructor(RD); 6159 Temp->setDestructor(Destructor); 6160 6161 MarkFunctionReferenced(Bind->getExprLoc(), Destructor); 6162 CheckDestructorAccess(Bind->getExprLoc(), Destructor, 6163 PDiag(diag::err_access_dtor_temp) 6164 << Bind->getType()); 6165 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc())) 6166 return ExprError(); 6167 6168 // We need a cleanup, but we don't need to remember the temporary. 6169 Cleanup.setExprNeedsCleanups(true); 6170 } 6171 6172 // Possibly strip off the top CXXBindTemporaryExpr. 6173 return E; 6174 } 6175 6176 /// Note a set of 'operator->' functions that were used for a member access. 6177 static void noteOperatorArrows(Sema &S, 6178 ArrayRef<FunctionDecl *> OperatorArrows) { 6179 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0; 6180 // FIXME: Make this configurable? 6181 unsigned Limit = 9; 6182 if (OperatorArrows.size() > Limit) { 6183 // Produce Limit-1 normal notes and one 'skipping' note. 6184 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2; 6185 SkipCount = OperatorArrows.size() - (Limit - 1); 6186 } 6187 6188 for (unsigned I = 0; I < OperatorArrows.size(); /**/) { 6189 if (I == SkipStart) { 6190 S.Diag(OperatorArrows[I]->getLocation(), 6191 diag::note_operator_arrows_suppressed) 6192 << SkipCount; 6193 I += SkipCount; 6194 } else { 6195 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here) 6196 << OperatorArrows[I]->getCallResultType(); 6197 ++I; 6198 } 6199 } 6200 } 6201 6202 ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, 6203 SourceLocation OpLoc, 6204 tok::TokenKind OpKind, 6205 ParsedType &ObjectType, 6206 bool &MayBePseudoDestructor) { 6207 // Since this might be a postfix expression, get rid of ParenListExprs. 6208 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base); 6209 if (Result.isInvalid()) return ExprError(); 6210 Base = Result.get(); 6211 6212 Result = CheckPlaceholderExpr(Base); 6213 if (Result.isInvalid()) return ExprError(); 6214 Base = Result.get(); 6215 6216 QualType BaseType = Base->getType(); 6217 MayBePseudoDestructor = false; 6218 if (BaseType->isDependentType()) { 6219 // If we have a pointer to a dependent type and are using the -> operator, 6220 // the object type is the type that the pointer points to. We might still 6221 // have enough information about that type to do something useful. 6222 if (OpKind == tok::arrow) 6223 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) 6224 BaseType = Ptr->getPointeeType(); 6225 6226 ObjectType = ParsedType::make(BaseType); 6227 MayBePseudoDestructor = true; 6228 return Base; 6229 } 6230 6231 // C++ [over.match.oper]p8: 6232 // [...] When operator->returns, the operator-> is applied to the value 6233 // returned, with the original second operand. 6234 if (OpKind == tok::arrow) { 6235 QualType StartingType = BaseType; 6236 bool NoArrowOperatorFound = false; 6237 bool FirstIteration = true; 6238 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext); 6239 // The set of types we've considered so far. 6240 llvm::SmallPtrSet<CanQualType,8> CTypes; 6241 SmallVector<FunctionDecl*, 8> OperatorArrows; 6242 CTypes.insert(Context.getCanonicalType(BaseType)); 6243 6244 while (BaseType->isRecordType()) { 6245 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) { 6246 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded) 6247 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange(); 6248 noteOperatorArrows(*this, OperatorArrows); 6249 Diag(OpLoc, diag::note_operator_arrow_depth) 6250 << getLangOpts().ArrowDepth; 6251 return ExprError(); 6252 } 6253 6254 Result = BuildOverloadedArrowExpr( 6255 S, Base, OpLoc, 6256 // When in a template specialization and on the first loop iteration, 6257 // potentially give the default diagnostic (with the fixit in a 6258 // separate note) instead of having the error reported back to here 6259 // and giving a diagnostic with a fixit attached to the error itself. 6260 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization()) 6261 ? nullptr 6262 : &NoArrowOperatorFound); 6263 if (Result.isInvalid()) { 6264 if (NoArrowOperatorFound) { 6265 if (FirstIteration) { 6266 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 6267 << BaseType << 1 << Base->getSourceRange() 6268 << FixItHint::CreateReplacement(OpLoc, "."); 6269 OpKind = tok::period; 6270 break; 6271 } 6272 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 6273 << BaseType << Base->getSourceRange(); 6274 CallExpr *CE = dyn_cast<CallExpr>(Base); 6275 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) { 6276 Diag(CD->getLocStart(), 6277 diag::note_member_reference_arrow_from_operator_arrow); 6278 } 6279 } 6280 return ExprError(); 6281 } 6282 Base = Result.get(); 6283 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base)) 6284 OperatorArrows.push_back(OpCall->getDirectCallee()); 6285 BaseType = Base->getType(); 6286 CanQualType CBaseType = Context.getCanonicalType(BaseType); 6287 if (!CTypes.insert(CBaseType).second) { 6288 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType; 6289 noteOperatorArrows(*this, OperatorArrows); 6290 return ExprError(); 6291 } 6292 FirstIteration = false; 6293 } 6294 6295 if (OpKind == tok::arrow && 6296 (BaseType->isPointerType() || BaseType->isObjCObjectPointerType())) 6297 BaseType = BaseType->getPointeeType(); 6298 } 6299 6300 // Objective-C properties allow "." access on Objective-C pointer types, 6301 // so adjust the base type to the object type itself. 6302 if (BaseType->isObjCObjectPointerType()) 6303 BaseType = BaseType->getPointeeType(); 6304 6305 // C++ [basic.lookup.classref]p2: 6306 // [...] If the type of the object expression is of pointer to scalar 6307 // type, the unqualified-id is looked up in the context of the complete 6308 // postfix-expression. 6309 // 6310 // This also indicates that we could be parsing a pseudo-destructor-name. 6311 // Note that Objective-C class and object types can be pseudo-destructor 6312 // expressions or normal member (ivar or property) access expressions, and 6313 // it's legal for the type to be incomplete if this is a pseudo-destructor 6314 // call. We'll do more incomplete-type checks later in the lookup process, 6315 // so just skip this check for ObjC types. 6316 if (BaseType->isObjCObjectOrInterfaceType()) { 6317 ObjectType = ParsedType::make(BaseType); 6318 MayBePseudoDestructor = true; 6319 return Base; 6320 } else if (!BaseType->isRecordType()) { 6321 ObjectType = nullptr; 6322 MayBePseudoDestructor = true; 6323 return Base; 6324 } 6325 6326 // The object type must be complete (or dependent), or 6327 // C++11 [expr.prim.general]p3: 6328 // Unlike the object expression in other contexts, *this is not required to 6329 // be of complete type for purposes of class member access (5.2.5) outside 6330 // the member function body. 6331 if (!BaseType->isDependentType() && 6332 !isThisOutsideMemberFunctionBody(BaseType) && 6333 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access)) 6334 return ExprError(); 6335 6336 // C++ [basic.lookup.classref]p2: 6337 // If the id-expression in a class member access (5.2.5) is an 6338 // unqualified-id, and the type of the object expression is of a class 6339 // type C (or of pointer to a class type C), the unqualified-id is looked 6340 // up in the scope of class C. [...] 6341 ObjectType = ParsedType::make(BaseType); 6342 return Base; 6343 } 6344 6345 static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base, 6346 tok::TokenKind& OpKind, SourceLocation OpLoc) { 6347 if (Base->hasPlaceholderType()) { 6348 ExprResult result = S.CheckPlaceholderExpr(Base); 6349 if (result.isInvalid()) return true; 6350 Base = result.get(); 6351 } 6352 ObjectType = Base->getType(); 6353 6354 // C++ [expr.pseudo]p2: 6355 // The left-hand side of the dot operator shall be of scalar type. The 6356 // left-hand side of the arrow operator shall be of pointer to scalar type. 6357 // This scalar type is the object type. 6358 // Note that this is rather different from the normal handling for the 6359 // arrow operator. 6360 if (OpKind == tok::arrow) { 6361 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) { 6362 ObjectType = Ptr->getPointeeType(); 6363 } else if (!Base->isTypeDependent()) { 6364 // The user wrote "p->" when they probably meant "p."; fix it. 6365 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 6366 << ObjectType << true 6367 << FixItHint::CreateReplacement(OpLoc, "."); 6368 if (S.isSFINAEContext()) 6369 return true; 6370 6371 OpKind = tok::period; 6372 } 6373 } 6374 6375 return false; 6376 } 6377 6378 ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base, 6379 SourceLocation OpLoc, 6380 tok::TokenKind OpKind, 6381 const CXXScopeSpec &SS, 6382 TypeSourceInfo *ScopeTypeInfo, 6383 SourceLocation CCLoc, 6384 SourceLocation TildeLoc, 6385 PseudoDestructorTypeStorage Destructed) { 6386 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo(); 6387 6388 QualType ObjectType; 6389 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) 6390 return ExprError(); 6391 6392 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() && 6393 !ObjectType->isVectorType()) { 6394 if (getLangOpts().MSVCCompat && ObjectType->isVoidType()) 6395 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange(); 6396 else { 6397 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar) 6398 << ObjectType << Base->getSourceRange(); 6399 return ExprError(); 6400 } 6401 } 6402 6403 // C++ [expr.pseudo]p2: 6404 // [...] The cv-unqualified versions of the object type and of the type 6405 // designated by the pseudo-destructor-name shall be the same type. 6406 if (DestructedTypeInfo) { 6407 QualType DestructedType = DestructedTypeInfo->getType(); 6408 SourceLocation DestructedTypeStart 6409 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(); 6410 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) { 6411 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) { 6412 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch) 6413 << ObjectType << DestructedType << Base->getSourceRange() 6414 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange(); 6415 6416 // Recover by setting the destructed type to the object type. 6417 DestructedType = ObjectType; 6418 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType, 6419 DestructedTypeStart); 6420 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 6421 } else if (DestructedType.getObjCLifetime() != 6422 ObjectType.getObjCLifetime()) { 6423 6424 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) { 6425 // Okay: just pretend that the user provided the correctly-qualified 6426 // type. 6427 } else { 6428 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals) 6429 << ObjectType << DestructedType << Base->getSourceRange() 6430 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange(); 6431 } 6432 6433 // Recover by setting the destructed type to the object type. 6434 DestructedType = ObjectType; 6435 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType, 6436 DestructedTypeStart); 6437 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 6438 } 6439 } 6440 } 6441 6442 // C++ [expr.pseudo]p2: 6443 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the 6444 // form 6445 // 6446 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name 6447 // 6448 // shall designate the same scalar type. 6449 if (ScopeTypeInfo) { 6450 QualType ScopeType = ScopeTypeInfo->getType(); 6451 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() && 6452 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) { 6453 6454 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(), 6455 diag::err_pseudo_dtor_type_mismatch) 6456 << ObjectType << ScopeType << Base->getSourceRange() 6457 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange(); 6458 6459 ScopeType = QualType(); 6460 ScopeTypeInfo = nullptr; 6461 } 6462 } 6463 6464 Expr *Result 6465 = new (Context) CXXPseudoDestructorExpr(Context, Base, 6466 OpKind == tok::arrow, OpLoc, 6467 SS.getWithLocInContext(Context), 6468 ScopeTypeInfo, 6469 CCLoc, 6470 TildeLoc, 6471 Destructed); 6472 6473 return Result; 6474 } 6475 6476 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 6477 SourceLocation OpLoc, 6478 tok::TokenKind OpKind, 6479 CXXScopeSpec &SS, 6480 UnqualifiedId &FirstTypeName, 6481 SourceLocation CCLoc, 6482 SourceLocation TildeLoc, 6483 UnqualifiedId &SecondTypeName) { 6484 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId || 6485 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) && 6486 "Invalid first type name in pseudo-destructor"); 6487 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId || 6488 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) && 6489 "Invalid second type name in pseudo-destructor"); 6490 6491 QualType ObjectType; 6492 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) 6493 return ExprError(); 6494 6495 // Compute the object type that we should use for name lookup purposes. Only 6496 // record types and dependent types matter. 6497 ParsedType ObjectTypePtrForLookup; 6498 if (!SS.isSet()) { 6499 if (ObjectType->isRecordType()) 6500 ObjectTypePtrForLookup = ParsedType::make(ObjectType); 6501 else if (ObjectType->isDependentType()) 6502 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy); 6503 } 6504 6505 // Convert the name of the type being destructed (following the ~) into a 6506 // type (with source-location information). 6507 QualType DestructedType; 6508 TypeSourceInfo *DestructedTypeInfo = nullptr; 6509 PseudoDestructorTypeStorage Destructed; 6510 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) { 6511 ParsedType T = getTypeName(*SecondTypeName.Identifier, 6512 SecondTypeName.StartLocation, 6513 S, &SS, true, false, ObjectTypePtrForLookup); 6514 if (!T && 6515 ((SS.isSet() && !computeDeclContext(SS, false)) || 6516 (!SS.isSet() && ObjectType->isDependentType()))) { 6517 // The name of the type being destroyed is a dependent name, and we 6518 // couldn't find anything useful in scope. Just store the identifier and 6519 // it's location, and we'll perform (qualified) name lookup again at 6520 // template instantiation time. 6521 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier, 6522 SecondTypeName.StartLocation); 6523 } else if (!T) { 6524 Diag(SecondTypeName.StartLocation, 6525 diag::err_pseudo_dtor_destructor_non_type) 6526 << SecondTypeName.Identifier << ObjectType; 6527 if (isSFINAEContext()) 6528 return ExprError(); 6529 6530 // Recover by assuming we had the right type all along. 6531 DestructedType = ObjectType; 6532 } else 6533 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo); 6534 } else { 6535 // Resolve the template-id to a type. 6536 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId; 6537 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 6538 TemplateId->NumArgs); 6539 TypeResult T = ActOnTemplateIdType(TemplateId->SS, 6540 TemplateId->TemplateKWLoc, 6541 TemplateId->Template, 6542 TemplateId->TemplateNameLoc, 6543 TemplateId->LAngleLoc, 6544 TemplateArgsPtr, 6545 TemplateId->RAngleLoc); 6546 if (T.isInvalid() || !T.get()) { 6547 // Recover by assuming we had the right type all along. 6548 DestructedType = ObjectType; 6549 } else 6550 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo); 6551 } 6552 6553 // If we've performed some kind of recovery, (re-)build the type source 6554 // information. 6555 if (!DestructedType.isNull()) { 6556 if (!DestructedTypeInfo) 6557 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType, 6558 SecondTypeName.StartLocation); 6559 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 6560 } 6561 6562 // Convert the name of the scope type (the type prior to '::') into a type. 6563 TypeSourceInfo *ScopeTypeInfo = nullptr; 6564 QualType ScopeType; 6565 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId || 6566 FirstTypeName.Identifier) { 6567 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) { 6568 ParsedType T = getTypeName(*FirstTypeName.Identifier, 6569 FirstTypeName.StartLocation, 6570 S, &SS, true, false, ObjectTypePtrForLookup); 6571 if (!T) { 6572 Diag(FirstTypeName.StartLocation, 6573 diag::err_pseudo_dtor_destructor_non_type) 6574 << FirstTypeName.Identifier << ObjectType; 6575 6576 if (isSFINAEContext()) 6577 return ExprError(); 6578 6579 // Just drop this type. It's unnecessary anyway. 6580 ScopeType = QualType(); 6581 } else 6582 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo); 6583 } else { 6584 // Resolve the template-id to a type. 6585 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId; 6586 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 6587 TemplateId->NumArgs); 6588 TypeResult T = ActOnTemplateIdType(TemplateId->SS, 6589 TemplateId->TemplateKWLoc, 6590 TemplateId->Template, 6591 TemplateId->TemplateNameLoc, 6592 TemplateId->LAngleLoc, 6593 TemplateArgsPtr, 6594 TemplateId->RAngleLoc); 6595 if (T.isInvalid() || !T.get()) { 6596 // Recover by dropping this type. 6597 ScopeType = QualType(); 6598 } else 6599 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo); 6600 } 6601 } 6602 6603 if (!ScopeType.isNull() && !ScopeTypeInfo) 6604 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType, 6605 FirstTypeName.StartLocation); 6606 6607 6608 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS, 6609 ScopeTypeInfo, CCLoc, TildeLoc, 6610 Destructed); 6611 } 6612 6613 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 6614 SourceLocation OpLoc, 6615 tok::TokenKind OpKind, 6616 SourceLocation TildeLoc, 6617 const DeclSpec& DS) { 6618 QualType ObjectType; 6619 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) 6620 return ExprError(); 6621 6622 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(), 6623 false); 6624 6625 TypeLocBuilder TLB; 6626 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T); 6627 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc()); 6628 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T); 6629 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo); 6630 6631 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(), 6632 nullptr, SourceLocation(), TildeLoc, 6633 Destructed); 6634 } 6635 6636 ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl, 6637 CXXConversionDecl *Method, 6638 bool HadMultipleCandidates) { 6639 if (Method->getParent()->isLambda() && 6640 Method->getConversionType()->isBlockPointerType()) { 6641 // This is a lambda coversion to block pointer; check if the argument 6642 // is a LambdaExpr. 6643 Expr *SubE = E; 6644 CastExpr *CE = dyn_cast<CastExpr>(SubE); 6645 if (CE && CE->getCastKind() == CK_NoOp) 6646 SubE = CE->getSubExpr(); 6647 SubE = SubE->IgnoreParens(); 6648 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE)) 6649 SubE = BE->getSubExpr(); 6650 if (isa<LambdaExpr>(SubE)) { 6651 // For the conversion to block pointer on a lambda expression, we 6652 // construct a special BlockLiteral instead; this doesn't really make 6653 // a difference in ARC, but outside of ARC the resulting block literal 6654 // follows the normal lifetime rules for block literals instead of being 6655 // autoreleased. 6656 DiagnosticErrorTrap Trap(Diags); 6657 PushExpressionEvaluationContext(PotentiallyEvaluated); 6658 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(), 6659 E->getExprLoc(), 6660 Method, E); 6661 PopExpressionEvaluationContext(); 6662 6663 if (Exp.isInvalid()) 6664 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv); 6665 return Exp; 6666 } 6667 } 6668 6669 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr, 6670 FoundDecl, Method); 6671 if (Exp.isInvalid()) 6672 return true; 6673 6674 MemberExpr *ME = new (Context) MemberExpr( 6675 Exp.get(), /*IsArrow=*/false, SourceLocation(), Method, SourceLocation(), 6676 Context.BoundMemberTy, VK_RValue, OK_Ordinary); 6677 if (HadMultipleCandidates) 6678 ME->setHadMultipleCandidates(true); 6679 MarkMemberReferenced(ME); 6680 6681 QualType ResultType = Method->getReturnType(); 6682 ExprValueKind VK = Expr::getValueKindForType(ResultType); 6683 ResultType = ResultType.getNonLValueExprType(Context); 6684 6685 CXXMemberCallExpr *CE = 6686 new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK, 6687 Exp.get()->getLocEnd()); 6688 return CE; 6689 } 6690 6691 ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, 6692 SourceLocation RParen) { 6693 // If the operand is an unresolved lookup expression, the expression is ill- 6694 // formed per [over.over]p1, because overloaded function names cannot be used 6695 // without arguments except in explicit contexts. 6696 ExprResult R = CheckPlaceholderExpr(Operand); 6697 if (R.isInvalid()) 6698 return R; 6699 6700 // The operand may have been modified when checking the placeholder type. 6701 Operand = R.get(); 6702 6703 if (ActiveTemplateInstantiations.empty() && 6704 Operand->HasSideEffects(Context, false)) { 6705 // The expression operand for noexcept is in an unevaluated expression 6706 // context, so side effects could result in unintended consequences. 6707 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context); 6708 } 6709 6710 CanThrowResult CanThrow = canThrow(Operand); 6711 return new (Context) 6712 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen); 6713 } 6714 6715 ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation, 6716 Expr *Operand, SourceLocation RParen) { 6717 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen); 6718 } 6719 6720 static bool IsSpecialDiscardedValue(Expr *E) { 6721 // In C++11, discarded-value expressions of a certain form are special, 6722 // according to [expr]p10: 6723 // The lvalue-to-rvalue conversion (4.1) is applied only if the 6724 // expression is an lvalue of volatile-qualified type and it has 6725 // one of the following forms: 6726 E = E->IgnoreParens(); 6727 6728 // - id-expression (5.1.1), 6729 if (isa<DeclRefExpr>(E)) 6730 return true; 6731 6732 // - subscripting (5.2.1), 6733 if (isa<ArraySubscriptExpr>(E)) 6734 return true; 6735 6736 // - class member access (5.2.5), 6737 if (isa<MemberExpr>(E)) 6738 return true; 6739 6740 // - indirection (5.3.1), 6741 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) 6742 if (UO->getOpcode() == UO_Deref) 6743 return true; 6744 6745 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 6746 // - pointer-to-member operation (5.5), 6747 if (BO->isPtrMemOp()) 6748 return true; 6749 6750 // - comma expression (5.18) where the right operand is one of the above. 6751 if (BO->getOpcode() == BO_Comma) 6752 return IsSpecialDiscardedValue(BO->getRHS()); 6753 } 6754 6755 // - conditional expression (5.16) where both the second and the third 6756 // operands are one of the above, or 6757 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) 6758 return IsSpecialDiscardedValue(CO->getTrueExpr()) && 6759 IsSpecialDiscardedValue(CO->getFalseExpr()); 6760 // The related edge case of "*x ?: *x". 6761 if (BinaryConditionalOperator *BCO = 6762 dyn_cast<BinaryConditionalOperator>(E)) { 6763 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr())) 6764 return IsSpecialDiscardedValue(OVE->getSourceExpr()) && 6765 IsSpecialDiscardedValue(BCO->getFalseExpr()); 6766 } 6767 6768 // Objective-C++ extensions to the rule. 6769 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E)) 6770 return true; 6771 6772 return false; 6773 } 6774 6775 /// Perform the conversions required for an expression used in a 6776 /// context that ignores the result. 6777 ExprResult Sema::IgnoredValueConversions(Expr *E) { 6778 if (E->hasPlaceholderType()) { 6779 ExprResult result = CheckPlaceholderExpr(E); 6780 if (result.isInvalid()) return E; 6781 E = result.get(); 6782 } 6783 6784 // C99 6.3.2.1: 6785 // [Except in specific positions,] an lvalue that does not have 6786 // array type is converted to the value stored in the 6787 // designated object (and is no longer an lvalue). 6788 if (E->isRValue()) { 6789 // In C, function designators (i.e. expressions of function type) 6790 // are r-values, but we still want to do function-to-pointer decay 6791 // on them. This is both technically correct and convenient for 6792 // some clients. 6793 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType()) 6794 return DefaultFunctionArrayConversion(E); 6795 6796 return E; 6797 } 6798 6799 if (getLangOpts().CPlusPlus) { 6800 // The C++11 standard defines the notion of a discarded-value expression; 6801 // normally, we don't need to do anything to handle it, but if it is a 6802 // volatile lvalue with a special form, we perform an lvalue-to-rvalue 6803 // conversion. 6804 if (getLangOpts().CPlusPlus11 && E->isGLValue() && 6805 E->getType().isVolatileQualified() && 6806 IsSpecialDiscardedValue(E)) { 6807 ExprResult Res = DefaultLvalueConversion(E); 6808 if (Res.isInvalid()) 6809 return E; 6810 E = Res.get(); 6811 } 6812 return E; 6813 } 6814 6815 // GCC seems to also exclude expressions of incomplete enum type. 6816 if (const EnumType *T = E->getType()->getAs<EnumType>()) { 6817 if (!T->getDecl()->isComplete()) { 6818 // FIXME: stupid workaround for a codegen bug! 6819 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get(); 6820 return E; 6821 } 6822 } 6823 6824 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 6825 if (Res.isInvalid()) 6826 return E; 6827 E = Res.get(); 6828 6829 if (!E->getType()->isVoidType()) 6830 RequireCompleteType(E->getExprLoc(), E->getType(), 6831 diag::err_incomplete_type); 6832 return E; 6833 } 6834 6835 // If we can unambiguously determine whether Var can never be used 6836 // in a constant expression, return true. 6837 // - if the variable and its initializer are non-dependent, then 6838 // we can unambiguously check if the variable is a constant expression. 6839 // - if the initializer is not value dependent - we can determine whether 6840 // it can be used to initialize a constant expression. If Init can not 6841 // be used to initialize a constant expression we conclude that Var can 6842 // never be a constant expression. 6843 // - FXIME: if the initializer is dependent, we can still do some analysis and 6844 // identify certain cases unambiguously as non-const by using a Visitor: 6845 // - such as those that involve odr-use of a ParmVarDecl, involve a new 6846 // delete, lambda-expr, dynamic-cast, reinterpret-cast etc... 6847 static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var, 6848 ASTContext &Context) { 6849 if (isa<ParmVarDecl>(Var)) return true; 6850 const VarDecl *DefVD = nullptr; 6851 6852 // If there is no initializer - this can not be a constant expression. 6853 if (!Var->getAnyInitializer(DefVD)) return true; 6854 assert(DefVD); 6855 if (DefVD->isWeak()) return false; 6856 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 6857 6858 Expr *Init = cast<Expr>(Eval->Value); 6859 6860 if (Var->getType()->isDependentType() || Init->isValueDependent()) { 6861 // FIXME: Teach the constant evaluator to deal with the non-dependent parts 6862 // of value-dependent expressions, and use it here to determine whether the 6863 // initializer is a potential constant expression. 6864 return false; 6865 } 6866 6867 return !IsVariableAConstantExpression(Var, Context); 6868 } 6869 6870 /// \brief Check if the current lambda has any potential captures 6871 /// that must be captured by any of its enclosing lambdas that are ready to 6872 /// capture. If there is a lambda that can capture a nested 6873 /// potential-capture, go ahead and do so. Also, check to see if any 6874 /// variables are uncaptureable or do not involve an odr-use so do not 6875 /// need to be captured. 6876 6877 static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures( 6878 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) { 6879 6880 assert(!S.isUnevaluatedContext()); 6881 assert(S.CurContext->isDependentContext()); 6882 assert(CurrentLSI->CallOperator == S.CurContext && 6883 "The current call operator must be synchronized with Sema's CurContext"); 6884 6885 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent(); 6886 6887 ArrayRef<const FunctionScopeInfo *> FunctionScopesArrayRef( 6888 S.FunctionScopes.data(), S.FunctionScopes.size()); 6889 6890 // All the potentially captureable variables in the current nested 6891 // lambda (within a generic outer lambda), must be captured by an 6892 // outer lambda that is enclosed within a non-dependent context. 6893 const unsigned NumPotentialCaptures = 6894 CurrentLSI->getNumPotentialVariableCaptures(); 6895 for (unsigned I = 0; I != NumPotentialCaptures; ++I) { 6896 Expr *VarExpr = nullptr; 6897 VarDecl *Var = nullptr; 6898 CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr); 6899 // If the variable is clearly identified as non-odr-used and the full 6900 // expression is not instantiation dependent, only then do we not 6901 // need to check enclosing lambda's for speculative captures. 6902 // For e.g.: 6903 // Even though 'x' is not odr-used, it should be captured. 6904 // int test() { 6905 // const int x = 10; 6906 // auto L = [=](auto a) { 6907 // (void) +x + a; 6908 // }; 6909 // } 6910 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) && 6911 !IsFullExprInstantiationDependent) 6912 continue; 6913 6914 // If we have a capture-capable lambda for the variable, go ahead and 6915 // capture the variable in that lambda (and all its enclosing lambdas). 6916 if (const Optional<unsigned> Index = 6917 getStackIndexOfNearestEnclosingCaptureCapableLambda( 6918 FunctionScopesArrayRef, Var, S)) { 6919 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue(); 6920 MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S, 6921 &FunctionScopeIndexOfCapturableLambda); 6922 } 6923 const bool IsVarNeverAConstantExpression = 6924 VariableCanNeverBeAConstantExpression(Var, S.Context); 6925 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) { 6926 // This full expression is not instantiation dependent or the variable 6927 // can not be used in a constant expression - which means 6928 // this variable must be odr-used here, so diagnose a 6929 // capture violation early, if the variable is un-captureable. 6930 // This is purely for diagnosing errors early. Otherwise, this 6931 // error would get diagnosed when the lambda becomes capture ready. 6932 QualType CaptureType, DeclRefType; 6933 SourceLocation ExprLoc = VarExpr->getExprLoc(); 6934 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit, 6935 /*EllipsisLoc*/ SourceLocation(), 6936 /*BuildAndDiagnose*/false, CaptureType, 6937 DeclRefType, nullptr)) { 6938 // We will never be able to capture this variable, and we need 6939 // to be able to in any and all instantiations, so diagnose it. 6940 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit, 6941 /*EllipsisLoc*/ SourceLocation(), 6942 /*BuildAndDiagnose*/true, CaptureType, 6943 DeclRefType, nullptr); 6944 } 6945 } 6946 } 6947 6948 // Check if 'this' needs to be captured. 6949 if (CurrentLSI->hasPotentialThisCapture()) { 6950 // If we have a capture-capable lambda for 'this', go ahead and capture 6951 // 'this' in that lambda (and all its enclosing lambdas). 6952 if (const Optional<unsigned> Index = 6953 getStackIndexOfNearestEnclosingCaptureCapableLambda( 6954 FunctionScopesArrayRef, /*0 is 'this'*/ nullptr, S)) { 6955 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue(); 6956 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation, 6957 /*Explicit*/ false, /*BuildAndDiagnose*/ true, 6958 &FunctionScopeIndexOfCapturableLambda); 6959 } 6960 } 6961 6962 // Reset all the potential captures at the end of each full-expression. 6963 CurrentLSI->clearPotentialCaptures(); 6964 } 6965 6966 static ExprResult attemptRecovery(Sema &SemaRef, 6967 const TypoCorrectionConsumer &Consumer, 6968 const TypoCorrection &TC) { 6969 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(), 6970 Consumer.getLookupResult().getLookupKind()); 6971 const CXXScopeSpec *SS = Consumer.getSS(); 6972 CXXScopeSpec NewSS; 6973 6974 // Use an approprate CXXScopeSpec for building the expr. 6975 if (auto *NNS = TC.getCorrectionSpecifier()) 6976 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange()); 6977 else if (SS && !TC.WillReplaceSpecifier()) 6978 NewSS = *SS; 6979 6980 if (auto *ND = TC.getFoundDecl()) { 6981 R.setLookupName(ND->getDeclName()); 6982 R.addDecl(ND); 6983 if (ND->isCXXClassMember()) { 6984 // Figure out the correct naming class to add to the LookupResult. 6985 CXXRecordDecl *Record = nullptr; 6986 if (auto *NNS = TC.getCorrectionSpecifier()) 6987 Record = NNS->getAsType()->getAsCXXRecordDecl(); 6988 if (!Record) 6989 Record = 6990 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext()); 6991 if (Record) 6992 R.setNamingClass(Record); 6993 6994 // Detect and handle the case where the decl might be an implicit 6995 // member. 6996 bool MightBeImplicitMember; 6997 if (!Consumer.isAddressOfOperand()) 6998 MightBeImplicitMember = true; 6999 else if (!NewSS.isEmpty()) 7000 MightBeImplicitMember = false; 7001 else if (R.isOverloadedResult()) 7002 MightBeImplicitMember = false; 7003 else if (R.isUnresolvableResult()) 7004 MightBeImplicitMember = true; 7005 else 7006 MightBeImplicitMember = isa<FieldDecl>(ND) || 7007 isa<IndirectFieldDecl>(ND) || 7008 isa<MSPropertyDecl>(ND); 7009 7010 if (MightBeImplicitMember) 7011 return SemaRef.BuildPossibleImplicitMemberExpr( 7012 NewSS, /*TemplateKWLoc*/ SourceLocation(), R, 7013 /*TemplateArgs*/ nullptr, /*S*/ nullptr); 7014 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) { 7015 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(), 7016 Ivar->getIdentifier()); 7017 } 7018 } 7019 7020 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false, 7021 /*AcceptInvalidDecl*/ true); 7022 } 7023 7024 namespace { 7025 class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> { 7026 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs; 7027 7028 public: 7029 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs) 7030 : TypoExprs(TypoExprs) {} 7031 bool VisitTypoExpr(TypoExpr *TE) { 7032 TypoExprs.insert(TE); 7033 return true; 7034 } 7035 }; 7036 7037 class TransformTypos : public TreeTransform<TransformTypos> { 7038 typedef TreeTransform<TransformTypos> BaseTransform; 7039 7040 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the 7041 // process of being initialized. 7042 llvm::function_ref<ExprResult(Expr *)> ExprFilter; 7043 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs; 7044 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache; 7045 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution; 7046 7047 /// \brief Emit diagnostics for all of the TypoExprs encountered. 7048 /// If the TypoExprs were successfully corrected, then the diagnostics should 7049 /// suggest the corrections. Otherwise the diagnostics will not suggest 7050 /// anything (having been passed an empty TypoCorrection). 7051 void EmitAllDiagnostics() { 7052 for (auto E : TypoExprs) { 7053 TypoExpr *TE = cast<TypoExpr>(E); 7054 auto &State = SemaRef.getTypoExprState(TE); 7055 if (State.DiagHandler) { 7056 TypoCorrection TC = State.Consumer->getCurrentCorrection(); 7057 ExprResult Replacement = TransformCache[TE]; 7058 7059 // Extract the NamedDecl from the transformed TypoExpr and add it to the 7060 // TypoCorrection, replacing the existing decls. This ensures the right 7061 // NamedDecl is used in diagnostics e.g. in the case where overload 7062 // resolution was used to select one from several possible decls that 7063 // had been stored in the TypoCorrection. 7064 if (auto *ND = getDeclFromExpr( 7065 Replacement.isInvalid() ? nullptr : Replacement.get())) 7066 TC.setCorrectionDecl(ND); 7067 7068 State.DiagHandler(TC); 7069 } 7070 SemaRef.clearDelayedTypo(TE); 7071 } 7072 } 7073 7074 /// \brief If corrections for the first TypoExpr have been exhausted for a 7075 /// given combination of the other TypoExprs, retry those corrections against 7076 /// the next combination of substitutions for the other TypoExprs by advancing 7077 /// to the next potential correction of the second TypoExpr. For the second 7078 /// and subsequent TypoExprs, if its stream of corrections has been exhausted, 7079 /// the stream is reset and the next TypoExpr's stream is advanced by one (a 7080 /// TypoExpr's correction stream is advanced by removing the TypoExpr from the 7081 /// TransformCache). Returns true if there is still any untried combinations 7082 /// of corrections. 7083 bool CheckAndAdvanceTypoExprCorrectionStreams() { 7084 for (auto TE : TypoExprs) { 7085 auto &State = SemaRef.getTypoExprState(TE); 7086 TransformCache.erase(TE); 7087 if (!State.Consumer->finished()) 7088 return true; 7089 State.Consumer->resetCorrectionStream(); 7090 } 7091 return false; 7092 } 7093 7094 NamedDecl *getDeclFromExpr(Expr *E) { 7095 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E)) 7096 E = OverloadResolution[OE]; 7097 7098 if (!E) 7099 return nullptr; 7100 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 7101 return DRE->getFoundDecl(); 7102 if (auto *ME = dyn_cast<MemberExpr>(E)) 7103 return ME->getFoundDecl(); 7104 // FIXME: Add any other expr types that could be be seen by the delayed typo 7105 // correction TreeTransform for which the corresponding TypoCorrection could 7106 // contain multiple decls. 7107 return nullptr; 7108 } 7109 7110 ExprResult TryTransform(Expr *E) { 7111 Sema::SFINAETrap Trap(SemaRef); 7112 ExprResult Res = TransformExpr(E); 7113 if (Trap.hasErrorOccurred() || Res.isInvalid()) 7114 return ExprError(); 7115 7116 return ExprFilter(Res.get()); 7117 } 7118 7119 public: 7120 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter) 7121 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {} 7122 7123 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc, 7124 MultiExprArg Args, 7125 SourceLocation RParenLoc, 7126 Expr *ExecConfig = nullptr) { 7127 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args, 7128 RParenLoc, ExecConfig); 7129 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) { 7130 if (Result.isUsable()) { 7131 Expr *ResultCall = Result.get(); 7132 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall)) 7133 ResultCall = BE->getSubExpr(); 7134 if (auto *CE = dyn_cast<CallExpr>(ResultCall)) 7135 OverloadResolution[OE] = CE->getCallee(); 7136 } 7137 } 7138 return Result; 7139 } 7140 7141 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); } 7142 7143 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); } 7144 7145 ExprResult TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) { 7146 return Owned(E); 7147 } 7148 7149 ExprResult TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) { 7150 return Owned(E); 7151 } 7152 7153 ExprResult Transform(Expr *E) { 7154 ExprResult Res; 7155 while (true) { 7156 Res = TryTransform(E); 7157 7158 // Exit if either the transform was valid or if there were no TypoExprs 7159 // to transform that still have any untried correction candidates.. 7160 if (!Res.isInvalid() || 7161 !CheckAndAdvanceTypoExprCorrectionStreams()) 7162 break; 7163 } 7164 7165 // Ensure none of the TypoExprs have multiple typo correction candidates 7166 // with the same edit length that pass all the checks and filters. 7167 // TODO: Properly handle various permutations of possible corrections when 7168 // there is more than one potentially ambiguous typo correction. 7169 // Also, disable typo correction while attempting the transform when 7170 // handling potentially ambiguous typo corrections as any new TypoExprs will 7171 // have been introduced by the application of one of the correction 7172 // candidates and add little to no value if corrected. 7173 SemaRef.DisableTypoCorrection = true; 7174 while (!AmbiguousTypoExprs.empty()) { 7175 auto TE = AmbiguousTypoExprs.back(); 7176 auto Cached = TransformCache[TE]; 7177 auto &State = SemaRef.getTypoExprState(TE); 7178 State.Consumer->saveCurrentPosition(); 7179 TransformCache.erase(TE); 7180 if (!TryTransform(E).isInvalid()) { 7181 State.Consumer->resetCorrectionStream(); 7182 TransformCache.erase(TE); 7183 Res = ExprError(); 7184 break; 7185 } 7186 AmbiguousTypoExprs.remove(TE); 7187 State.Consumer->restoreSavedPosition(); 7188 TransformCache[TE] = Cached; 7189 } 7190 SemaRef.DisableTypoCorrection = false; 7191 7192 // Ensure that all of the TypoExprs within the current Expr have been found. 7193 if (!Res.isUsable()) 7194 FindTypoExprs(TypoExprs).TraverseStmt(E); 7195 7196 EmitAllDiagnostics(); 7197 7198 return Res; 7199 } 7200 7201 ExprResult TransformTypoExpr(TypoExpr *E) { 7202 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the 7203 // cached transformation result if there is one and the TypoExpr isn't the 7204 // first one that was encountered. 7205 auto &CacheEntry = TransformCache[E]; 7206 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) { 7207 return CacheEntry; 7208 } 7209 7210 auto &State = SemaRef.getTypoExprState(E); 7211 assert(State.Consumer && "Cannot transform a cleared TypoExpr"); 7212 7213 // For the first TypoExpr and an uncached TypoExpr, find the next likely 7214 // typo correction and return it. 7215 while (TypoCorrection TC = State.Consumer->getNextCorrection()) { 7216 if (InitDecl && TC.getFoundDecl() == InitDecl) 7217 continue; 7218 ExprResult NE = State.RecoveryHandler ? 7219 State.RecoveryHandler(SemaRef, E, TC) : 7220 attemptRecovery(SemaRef, *State.Consumer, TC); 7221 if (!NE.isInvalid()) { 7222 // Check whether there may be a second viable correction with the same 7223 // edit distance; if so, remember this TypoExpr may have an ambiguous 7224 // correction so it can be more thoroughly vetted later. 7225 TypoCorrection Next; 7226 if ((Next = State.Consumer->peekNextCorrection()) && 7227 Next.getEditDistance(false) == TC.getEditDistance(false)) { 7228 AmbiguousTypoExprs.insert(E); 7229 } else { 7230 AmbiguousTypoExprs.remove(E); 7231 } 7232 assert(!NE.isUnset() && 7233 "Typo was transformed into a valid-but-null ExprResult"); 7234 return CacheEntry = NE; 7235 } 7236 } 7237 return CacheEntry = ExprError(); 7238 } 7239 }; 7240 } 7241 7242 ExprResult 7243 Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl, 7244 llvm::function_ref<ExprResult(Expr *)> Filter) { 7245 // If the current evaluation context indicates there are uncorrected typos 7246 // and the current expression isn't guaranteed to not have typos, try to 7247 // resolve any TypoExpr nodes that might be in the expression. 7248 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos && 7249 (E->isTypeDependent() || E->isValueDependent() || 7250 E->isInstantiationDependent())) { 7251 auto TyposInContext = ExprEvalContexts.back().NumTypos; 7252 assert(TyposInContext < ~0U && "Recursive call of CorrectDelayedTyposInExpr"); 7253 ExprEvalContexts.back().NumTypos = ~0U; 7254 auto TyposResolved = DelayedTypos.size(); 7255 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E); 7256 ExprEvalContexts.back().NumTypos = TyposInContext; 7257 TyposResolved -= DelayedTypos.size(); 7258 if (Result.isInvalid() || Result.get() != E) { 7259 ExprEvalContexts.back().NumTypos -= TyposResolved; 7260 return Result; 7261 } 7262 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?"); 7263 } 7264 return E; 7265 } 7266 7267 ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC, 7268 bool DiscardedValue, 7269 bool IsConstexpr, 7270 bool IsLambdaInitCaptureInitializer) { 7271 ExprResult FullExpr = FE; 7272 7273 if (!FullExpr.get()) 7274 return ExprError(); 7275 7276 // If we are an init-expression in a lambdas init-capture, we should not 7277 // diagnose an unexpanded pack now (will be diagnosed once lambda-expr 7278 // containing full-expression is done). 7279 // template<class ... Ts> void test(Ts ... t) { 7280 // test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now. 7281 // return a; 7282 // }() ...); 7283 // } 7284 // FIXME: This is a hack. It would be better if we pushed the lambda scope 7285 // when we parse the lambda introducer, and teach capturing (but not 7286 // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a 7287 // corresponding class yet (that is, have LambdaScopeInfo either represent a 7288 // lambda where we've entered the introducer but not the body, or represent a 7289 // lambda where we've entered the body, depending on where the 7290 // parser/instantiation has got to). 7291 if (!IsLambdaInitCaptureInitializer && 7292 DiagnoseUnexpandedParameterPack(FullExpr.get())) 7293 return ExprError(); 7294 7295 // Top-level expressions default to 'id' when we're in a debugger. 7296 if (DiscardedValue && getLangOpts().DebuggerCastResultToId && 7297 FullExpr.get()->getType() == Context.UnknownAnyTy) { 7298 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType()); 7299 if (FullExpr.isInvalid()) 7300 return ExprError(); 7301 } 7302 7303 if (DiscardedValue) { 7304 FullExpr = CheckPlaceholderExpr(FullExpr.get()); 7305 if (FullExpr.isInvalid()) 7306 return ExprError(); 7307 7308 FullExpr = IgnoredValueConversions(FullExpr.get()); 7309 if (FullExpr.isInvalid()) 7310 return ExprError(); 7311 } 7312 7313 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get()); 7314 if (FullExpr.isInvalid()) 7315 return ExprError(); 7316 7317 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr); 7318 7319 // At the end of this full expression (which could be a deeply nested 7320 // lambda), if there is a potential capture within the nested lambda, 7321 // have the outer capture-able lambda try and capture it. 7322 // Consider the following code: 7323 // void f(int, int); 7324 // void f(const int&, double); 7325 // void foo() { 7326 // const int x = 10, y = 20; 7327 // auto L = [=](auto a) { 7328 // auto M = [=](auto b) { 7329 // f(x, b); <-- requires x to be captured by L and M 7330 // f(y, a); <-- requires y to be captured by L, but not all Ms 7331 // }; 7332 // }; 7333 // } 7334 7335 // FIXME: Also consider what happens for something like this that involves 7336 // the gnu-extension statement-expressions or even lambda-init-captures: 7337 // void f() { 7338 // const int n = 0; 7339 // auto L = [&](auto a) { 7340 // +n + ({ 0; a; }); 7341 // }; 7342 // } 7343 // 7344 // Here, we see +n, and then the full-expression 0; ends, so we don't 7345 // capture n (and instead remove it from our list of potential captures), 7346 // and then the full-expression +n + ({ 0; }); ends, but it's too late 7347 // for us to see that we need to capture n after all. 7348 7349 LambdaScopeInfo *const CurrentLSI = getCurLambda(); 7350 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer 7351 // even if CurContext is not a lambda call operator. Refer to that Bug Report 7352 // for an example of the code that might cause this asynchrony. 7353 // By ensuring we are in the context of a lambda's call operator 7354 // we can fix the bug (we only need to check whether we need to capture 7355 // if we are within a lambda's body); but per the comments in that 7356 // PR, a proper fix would entail : 7357 // "Alternative suggestion: 7358 // - Add to Sema an integer holding the smallest (outermost) scope 7359 // index that we are *lexically* within, and save/restore/set to 7360 // FunctionScopes.size() in InstantiatingTemplate's 7361 // constructor/destructor. 7362 // - Teach the handful of places that iterate over FunctionScopes to 7363 // stop at the outermost enclosing lexical scope." 7364 const bool IsInLambdaDeclContext = isLambdaCallOperator(CurContext); 7365 if (IsInLambdaDeclContext && CurrentLSI && 7366 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid()) 7367 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI, 7368 *this); 7369 return MaybeCreateExprWithCleanups(FullExpr); 7370 } 7371 7372 StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) { 7373 if (!FullStmt) return StmtError(); 7374 7375 return MaybeCreateStmtWithCleanups(FullStmt); 7376 } 7377 7378 Sema::IfExistsResult 7379 Sema::CheckMicrosoftIfExistsSymbol(Scope *S, 7380 CXXScopeSpec &SS, 7381 const DeclarationNameInfo &TargetNameInfo) { 7382 DeclarationName TargetName = TargetNameInfo.getName(); 7383 if (!TargetName) 7384 return IER_DoesNotExist; 7385 7386 // If the name itself is dependent, then the result is dependent. 7387 if (TargetName.isDependentName()) 7388 return IER_Dependent; 7389 7390 // Do the redeclaration lookup in the current scope. 7391 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName, 7392 Sema::NotForRedeclaration); 7393 LookupParsedName(R, S, &SS); 7394 R.suppressDiagnostics(); 7395 7396 switch (R.getResultKind()) { 7397 case LookupResult::Found: 7398 case LookupResult::FoundOverloaded: 7399 case LookupResult::FoundUnresolvedValue: 7400 case LookupResult::Ambiguous: 7401 return IER_Exists; 7402 7403 case LookupResult::NotFound: 7404 return IER_DoesNotExist; 7405 7406 case LookupResult::NotFoundInCurrentInstantiation: 7407 return IER_Dependent; 7408 } 7409 7410 llvm_unreachable("Invalid LookupResult Kind!"); 7411 } 7412 7413 Sema::IfExistsResult 7414 Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, 7415 bool IsIfExists, CXXScopeSpec &SS, 7416 UnqualifiedId &Name) { 7417 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 7418 7419 // Check for unexpanded parameter packs. 7420 SmallVector<UnexpandedParameterPack, 4> Unexpanded; 7421 collectUnexpandedParameterPacks(SS, Unexpanded); 7422 collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded); 7423 if (!Unexpanded.empty()) { 7424 DiagnoseUnexpandedParameterPacks(KeywordLoc, 7425 IsIfExists? UPPC_IfExists 7426 : UPPC_IfNotExists, 7427 Unexpanded); 7428 return IER_Error; 7429 } 7430 7431 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo); 7432 } 7433