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