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