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