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