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