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