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