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