SemaExprCXX.cpp revision 8999fe1bc367b3ecc878d135c7b31e3479da56f4
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// This file implements semantic analysis for C++ expressions. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Sema/SemaInternal.h" 15#include "clang/Sema/DeclSpec.h" 16#include "clang/Sema/Initialization.h" 17#include "clang/Sema/Lookup.h" 18#include "clang/Sema/ParsedTemplate.h" 19#include "clang/Sema/ScopeInfo.h" 20#include "clang/Sema/TemplateDeduction.h" 21#include "clang/AST/ASTContext.h" 22#include "clang/AST/CXXInheritance.h" 23#include "clang/AST/DeclObjC.h" 24#include "clang/AST/ExprCXX.h" 25#include "clang/AST/ExprObjC.h" 26#include "clang/AST/TypeLoc.h" 27#include "clang/Basic/PartialDiagnostic.h" 28#include "clang/Basic/TargetInfo.h" 29#include "clang/Lex/Preprocessor.h" 30#include "llvm/ADT/STLExtras.h" 31using namespace clang; 32using namespace sema; 33 34ParsedType Sema::getDestructorName(SourceLocation TildeLoc, 35 IdentifierInfo &II, 36 SourceLocation NameLoc, 37 Scope *S, CXXScopeSpec &SS, 38 ParsedType ObjectTypePtr, 39 bool EnteringContext) { 40 // Determine where to perform name lookup. 41 42 // FIXME: This area of the standard is very messy, and the current 43 // wording is rather unclear about which scopes we search for the 44 // destructor name; see core issues 399 and 555. Issue 399 in 45 // particular shows where the current description of destructor name 46 // lookup is completely out of line with existing practice, e.g., 47 // this appears to be ill-formed: 48 // 49 // namespace N { 50 // template <typename T> struct S { 51 // ~S(); 52 // }; 53 // } 54 // 55 // void f(N::S<int>* s) { 56 // s->N::S<int>::~S(); 57 // } 58 // 59 // See also PR6358 and PR6359. 60 // For this reason, we're currently only doing the C++03 version of this 61 // code; the C++0x version has to wait until we get a proper spec. 62 QualType SearchType; 63 DeclContext *LookupCtx = 0; 64 bool isDependent = false; 65 bool LookInScope = false; 66 67 // If we have an object type, it's because we are in a 68 // pseudo-destructor-expression or a member access expression, and 69 // we know what type we're looking for. 70 if (ObjectTypePtr) 71 SearchType = GetTypeFromParser(ObjectTypePtr); 72 73 if (SS.isSet()) { 74 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep(); 75 76 bool AlreadySearched = false; 77 bool LookAtPrefix = true; 78 // C++ [basic.lookup.qual]p6: 79 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier, 80 // the type-names are looked up as types in the scope designated by the 81 // nested-name-specifier. In a qualified-id of the form: 82 // 83 // ::[opt] nested-name-specifier ~ class-name 84 // 85 // where the nested-name-specifier designates a namespace scope, and in 86 // a qualified-id of the form: 87 // 88 // ::opt nested-name-specifier class-name :: ~ class-name 89 // 90 // the class-names are looked up as types in the scope designated by 91 // the nested-name-specifier. 92 // 93 // Here, we check the first case (completely) and determine whether the 94 // code below is permitted to look at the prefix of the 95 // nested-name-specifier. 96 DeclContext *DC = computeDeclContext(SS, EnteringContext); 97 if (DC && DC->isFileContext()) { 98 AlreadySearched = true; 99 LookupCtx = DC; 100 isDependent = false; 101 } else if (DC && isa<CXXRecordDecl>(DC)) 102 LookAtPrefix = false; 103 104 // The second case from the C++03 rules quoted further above. 105 NestedNameSpecifier *Prefix = 0; 106 if (AlreadySearched) { 107 // Nothing left to do. 108 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) { 109 CXXScopeSpec PrefixSS; 110 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data())); 111 LookupCtx = computeDeclContext(PrefixSS, EnteringContext); 112 isDependent = isDependentScopeSpecifier(PrefixSS); 113 } else if (ObjectTypePtr) { 114 LookupCtx = computeDeclContext(SearchType); 115 isDependent = SearchType->isDependentType(); 116 } else { 117 LookupCtx = computeDeclContext(SS, EnteringContext); 118 isDependent = LookupCtx && LookupCtx->isDependentContext(); 119 } 120 121 LookInScope = false; 122 } else if (ObjectTypePtr) { 123 // C++ [basic.lookup.classref]p3: 124 // If the unqualified-id is ~type-name, the type-name is looked up 125 // in the context of the entire postfix-expression. If the type T 126 // of the object expression is of a class type C, the type-name is 127 // also looked up in the scope of class C. At least one of the 128 // lookups shall find a name that refers to (possibly 129 // cv-qualified) T. 130 LookupCtx = computeDeclContext(SearchType); 131 isDependent = SearchType->isDependentType(); 132 assert((isDependent || !SearchType->isIncompleteType()) && 133 "Caller should have completed object type"); 134 135 LookInScope = true; 136 } else { 137 // Perform lookup into the current scope (only). 138 LookInScope = true; 139 } 140 141 TypeDecl *NonMatchingTypeDecl = 0; 142 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName); 143 for (unsigned Step = 0; Step != 2; ++Step) { 144 // Look for the name first in the computed lookup context (if we 145 // have one) and, if that fails to find a match, in the scope (if 146 // we're allowed to look there). 147 Found.clear(); 148 if (Step == 0 && LookupCtx) 149 LookupQualifiedName(Found, LookupCtx); 150 else if (Step == 1 && LookInScope && S) 151 LookupName(Found, S); 152 else 153 continue; 154 155 // FIXME: Should we be suppressing ambiguities here? 156 if (Found.isAmbiguous()) 157 return ParsedType(); 158 159 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) { 160 QualType T = Context.getTypeDeclType(Type); 161 162 if (SearchType.isNull() || SearchType->isDependentType() || 163 Context.hasSameUnqualifiedType(T, SearchType)) { 164 // We found our type! 165 166 return ParsedType::make(T); 167 } 168 169 if (!SearchType.isNull()) 170 NonMatchingTypeDecl = Type; 171 } 172 173 // If the name that we found is a class template name, and it is 174 // the same name as the template name in the last part of the 175 // nested-name-specifier (if present) or the object type, then 176 // this is the destructor for that class. 177 // FIXME: This is a workaround until we get real drafting for core 178 // issue 399, for which there isn't even an obvious direction. 179 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) { 180 QualType MemberOfType; 181 if (SS.isSet()) { 182 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) { 183 // Figure out the type of the context, if it has one. 184 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) 185 MemberOfType = Context.getTypeDeclType(Record); 186 } 187 } 188 if (MemberOfType.isNull()) 189 MemberOfType = SearchType; 190 191 if (MemberOfType.isNull()) 192 continue; 193 194 // We're referring into a class template specialization. If the 195 // class template we found is the same as the template being 196 // specialized, we found what we are looking for. 197 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) { 198 if (ClassTemplateSpecializationDecl *Spec 199 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { 200 if (Spec->getSpecializedTemplate()->getCanonicalDecl() == 201 Template->getCanonicalDecl()) 202 return ParsedType::make(MemberOfType); 203 } 204 205 continue; 206 } 207 208 // We're referring to an unresolved class template 209 // specialization. Determine whether we class template we found 210 // is the same as the template being specialized or, if we don't 211 // know which template is being specialized, that it at least 212 // has the same name. 213 if (const TemplateSpecializationType *SpecType 214 = MemberOfType->getAs<TemplateSpecializationType>()) { 215 TemplateName SpecName = SpecType->getTemplateName(); 216 217 // The class template we found is the same template being 218 // specialized. 219 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) { 220 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl()) 221 return ParsedType::make(MemberOfType); 222 223 continue; 224 } 225 226 // The class template we found has the same name as the 227 // (dependent) template name being specialized. 228 if (DependentTemplateName *DepTemplate 229 = SpecName.getAsDependentTemplateName()) { 230 if (DepTemplate->isIdentifier() && 231 DepTemplate->getIdentifier() == Template->getIdentifier()) 232 return ParsedType::make(MemberOfType); 233 234 continue; 235 } 236 } 237 } 238 } 239 240 if (isDependent) { 241 // We didn't find our type, but that's okay: it's dependent 242 // anyway. 243 244 // FIXME: What if we have no nested-name-specifier? 245 QualType T = CheckTypenameType(ETK_None, SourceLocation(), 246 SS.getWithLocInContext(Context), 247 II, NameLoc); 248 return ParsedType::make(T); 249 } 250 251 if (NonMatchingTypeDecl) { 252 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl); 253 Diag(NameLoc, diag::err_destructor_expr_type_mismatch) 254 << T << SearchType; 255 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here) 256 << T; 257 } else if (ObjectTypePtr) 258 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type) 259 << &II; 260 else 261 Diag(NameLoc, diag::err_destructor_class_name); 262 263 return ParsedType(); 264} 265 266/// \brief Build a C++ typeid expression with a type operand. 267ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, 268 SourceLocation TypeidLoc, 269 TypeSourceInfo *Operand, 270 SourceLocation RParenLoc) { 271 // C++ [expr.typeid]p4: 272 // The top-level cv-qualifiers of the lvalue expression or the type-id 273 // that is the operand of typeid are always ignored. 274 // If the type of the type-id is a class type or a reference to a class 275 // type, the class shall be completely-defined. 276 Qualifiers Quals; 277 QualType T 278 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(), 279 Quals); 280 if (T->getAs<RecordType>() && 281 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) 282 return ExprError(); 283 284 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(), 285 Operand, 286 SourceRange(TypeidLoc, RParenLoc))); 287} 288 289/// \brief Build a C++ typeid expression with an expression operand. 290ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, 291 SourceLocation TypeidLoc, 292 Expr *E, 293 SourceLocation RParenLoc) { 294 bool isUnevaluatedOperand = true; 295 if (E && !E->isTypeDependent()) { 296 QualType T = E->getType(); 297 if (const RecordType *RecordT = T->getAs<RecordType>()) { 298 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl()); 299 // C++ [expr.typeid]p3: 300 // [...] If the type of the expression is a class type, the class 301 // shall be completely-defined. 302 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) 303 return ExprError(); 304 305 // C++ [expr.typeid]p3: 306 // When typeid is applied to an expression other than an glvalue of a 307 // polymorphic class type [...] [the] expression is an unevaluated 308 // operand. [...] 309 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) { 310 isUnevaluatedOperand = false; 311 312 // We require a vtable to query the type at run time. 313 MarkVTableUsed(TypeidLoc, RecordD); 314 } 315 } 316 317 // C++ [expr.typeid]p4: 318 // [...] If the type of the type-id is a reference to a possibly 319 // cv-qualified type, the result of the typeid expression refers to a 320 // std::type_info object representing the cv-unqualified referenced 321 // type. 322 Qualifiers Quals; 323 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals); 324 if (!Context.hasSameType(T, UnqualT)) { 325 T = UnqualT; 326 ImpCastExprToType(E, UnqualT, CK_NoOp, CastCategory(E)); 327 } 328 } 329 330 // If this is an unevaluated operand, clear out the set of 331 // declaration references we have been computing and eliminate any 332 // temporaries introduced in its computation. 333 if (isUnevaluatedOperand) 334 ExprEvalContexts.back().Context = Unevaluated; 335 336 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(), 337 E, 338 SourceRange(TypeidLoc, RParenLoc))); 339} 340 341/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression); 342ExprResult 343Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, 344 bool isType, void *TyOrExpr, SourceLocation RParenLoc) { 345 // Find the std::type_info type. 346 if (!StdNamespace) 347 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); 348 349 if (!CXXTypeInfoDecl) { 350 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info"); 351 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName); 352 LookupQualifiedName(R, getStdNamespace()); 353 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>(); 354 if (!CXXTypeInfoDecl) 355 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); 356 } 357 358 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl); 359 360 if (isType) { 361 // The operand is a type; handle it as such. 362 TypeSourceInfo *TInfo = 0; 363 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr), 364 &TInfo); 365 if (T.isNull()) 366 return ExprError(); 367 368 if (!TInfo) 369 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); 370 371 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc); 372 } 373 374 // The operand is an expression. 375 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc); 376} 377 378/// Retrieve the UuidAttr associated with QT. 379static UuidAttr *GetUuidAttrOfType(QualType QT) { 380 // Optionally remove one level of pointer, reference or array indirection. 381 const Type *Ty = QT.getTypePtr();; 382 if (QT->isPointerType() || QT->isReferenceType()) 383 Ty = QT->getPointeeType().getTypePtr(); 384 else if (QT->isArrayType()) 385 Ty = cast<ArrayType>(QT)->getElementType().getTypePtr(); 386 387 // Loop all class definition and declaration looking for an uuid attribute. 388 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 389 while (RD) { 390 if (UuidAttr *Uuid = RD->getAttr<UuidAttr>()) 391 return Uuid; 392 RD = RD->getPreviousDeclaration(); 393 } 394 return 0; 395} 396 397/// \brief Build a Microsoft __uuidof expression with a type operand. 398ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType, 399 SourceLocation TypeidLoc, 400 TypeSourceInfo *Operand, 401 SourceLocation RParenLoc) { 402 if (!Operand->getType()->isDependentType()) { 403 if (!GetUuidAttrOfType(Operand->getType())) 404 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid)); 405 } 406 407 // FIXME: add __uuidof semantic analysis for type operand. 408 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(), 409 Operand, 410 SourceRange(TypeidLoc, RParenLoc))); 411} 412 413/// \brief Build a Microsoft __uuidof expression with an expression operand. 414ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType, 415 SourceLocation TypeidLoc, 416 Expr *E, 417 SourceLocation RParenLoc) { 418 if (!E->getType()->isDependentType()) { 419 if (!GetUuidAttrOfType(E->getType()) && 420 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 421 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid)); 422 } 423 // FIXME: add __uuidof semantic analysis for type operand. 424 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(), 425 E, 426 SourceRange(TypeidLoc, RParenLoc))); 427} 428 429/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression); 430ExprResult 431Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, 432 bool isType, void *TyOrExpr, SourceLocation RParenLoc) { 433 // If MSVCGuidDecl has not been cached, do the lookup. 434 if (!MSVCGuidDecl) { 435 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID"); 436 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName); 437 LookupQualifiedName(R, Context.getTranslationUnitDecl()); 438 MSVCGuidDecl = R.getAsSingle<RecordDecl>(); 439 if (!MSVCGuidDecl) 440 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof)); 441 } 442 443 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl); 444 445 if (isType) { 446 // The operand is a type; handle it as such. 447 TypeSourceInfo *TInfo = 0; 448 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr), 449 &TInfo); 450 if (T.isNull()) 451 return ExprError(); 452 453 if (!TInfo) 454 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); 455 456 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc); 457 } 458 459 // The operand is an expression. 460 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc); 461} 462 463/// ActOnCXXBoolLiteral - Parse {true,false} literals. 464ExprResult 465Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 466 assert((Kind == tok::kw_true || Kind == tok::kw_false) && 467 "Unknown C++ Boolean value!"); 468 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true, 469 Context.BoolTy, OpLoc)); 470} 471 472/// ActOnCXXNullPtrLiteral - Parse 'nullptr'. 473ExprResult 474Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) { 475 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc)); 476} 477 478/// ActOnCXXThrow - Parse throw expressions. 479ExprResult 480Sema::ActOnCXXThrow(SourceLocation OpLoc, Expr *Ex) { 481 // Don't report an error if 'throw' is used in system headers. 482 if (!getLangOptions().CXXExceptions && 483 !getSourceManager().isInSystemHeader(OpLoc)) 484 Diag(OpLoc, diag::err_exceptions_disabled) << "throw"; 485 486 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex)) 487 return ExprError(); 488 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc)); 489} 490 491/// CheckCXXThrowOperand - Validate the operand of a throw. 492bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) { 493 // C++ [except.throw]p3: 494 // A throw-expression initializes a temporary object, called the exception 495 // object, the type of which is determined by removing any top-level 496 // cv-qualifiers from the static type of the operand of throw and adjusting 497 // the type from "array of T" or "function returning T" to "pointer to T" 498 // or "pointer to function returning T", [...] 499 if (E->getType().hasQualifiers()) 500 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp, 501 CastCategory(E)); 502 503 DefaultFunctionArrayConversion(E); 504 505 // If the type of the exception would be an incomplete type or a pointer 506 // to an incomplete type other than (cv) void the program is ill-formed. 507 QualType Ty = E->getType(); 508 bool isPointer = false; 509 if (const PointerType* Ptr = Ty->getAs<PointerType>()) { 510 Ty = Ptr->getPointeeType(); 511 isPointer = true; 512 } 513 if (!isPointer || !Ty->isVoidType()) { 514 if (RequireCompleteType(ThrowLoc, Ty, 515 PDiag(isPointer ? diag::err_throw_incomplete_ptr 516 : diag::err_throw_incomplete) 517 << E->getSourceRange())) 518 return true; 519 520 if (RequireNonAbstractType(ThrowLoc, E->getType(), 521 PDiag(diag::err_throw_abstract_type) 522 << E->getSourceRange())) 523 return true; 524 } 525 526 // Initialize the exception result. This implicitly weeds out 527 // abstract types or types with inaccessible copy constructors. 528 const VarDecl *NRVOVariable = getCopyElisionCandidate(QualType(), E, false); 529 530 // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p32. 531 InitializedEntity Entity = 532 InitializedEntity::InitializeException(ThrowLoc, E->getType(), 533 /*NRVO=*/false); 534 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable, 535 QualType(), E); 536 if (Res.isInvalid()) 537 return true; 538 E = Res.takeAs<Expr>(); 539 540 // If the exception has class type, we need additional handling. 541 const RecordType *RecordTy = Ty->getAs<RecordType>(); 542 if (!RecordTy) 543 return false; 544 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 545 546 // If we are throwing a polymorphic class type or pointer thereof, 547 // exception handling will make use of the vtable. 548 MarkVTableUsed(ThrowLoc, RD); 549 550 // If a pointer is thrown, the referenced object will not be destroyed. 551 if (isPointer) 552 return false; 553 554 // If the class has a non-trivial destructor, we must be able to call it. 555 if (RD->hasTrivialDestructor()) 556 return false; 557 558 CXXDestructorDecl *Destructor 559 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD)); 560 if (!Destructor) 561 return false; 562 563 MarkDeclarationReferenced(E->getExprLoc(), Destructor); 564 CheckDestructorAccess(E->getExprLoc(), Destructor, 565 PDiag(diag::err_access_dtor_exception) << Ty); 566 return false; 567} 568 569CXXMethodDecl *Sema::tryCaptureCXXThis() { 570 // Ignore block scopes: we can capture through them. 571 // Ignore nested enum scopes: we'll diagnose non-constant expressions 572 // where they're invalid, and other uses are legitimate. 573 // Don't ignore nested class scopes: you can't use 'this' in a local class. 574 DeclContext *DC = CurContext; 575 while (true) { 576 if (isa<BlockDecl>(DC)) DC = cast<BlockDecl>(DC)->getDeclContext(); 577 else if (isa<EnumDecl>(DC)) DC = cast<EnumDecl>(DC)->getDeclContext(); 578 else break; 579 } 580 581 // If we're not in an instance method, error out. 582 CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC); 583 if (!method || !method->isInstance()) 584 return 0; 585 586 // Mark that we're closing on 'this' in all the block scopes, if applicable. 587 for (unsigned idx = FunctionScopes.size() - 1; 588 isa<BlockScopeInfo>(FunctionScopes[idx]); 589 --idx) 590 cast<BlockScopeInfo>(FunctionScopes[idx])->CapturesCXXThis = true; 591 592 return method; 593} 594 595ExprResult Sema::ActOnCXXThis(SourceLocation loc) { 596 /// C++ 9.3.2: In the body of a non-static member function, the keyword this 597 /// is a non-lvalue expression whose value is the address of the object for 598 /// which the function is called. 599 600 CXXMethodDecl *method = tryCaptureCXXThis(); 601 if (!method) return Diag(loc, diag::err_invalid_this_use); 602 603 return Owned(new (Context) CXXThisExpr(loc, method->getThisType(Context), 604 /*isImplicit=*/false)); 605} 606 607ExprResult 608Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep, 609 SourceLocation LParenLoc, 610 MultiExprArg exprs, 611 SourceLocation RParenLoc) { 612 if (!TypeRep) 613 return ExprError(); 614 615 TypeSourceInfo *TInfo; 616 QualType Ty = GetTypeFromParser(TypeRep, &TInfo); 617 if (!TInfo) 618 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation()); 619 620 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc); 621} 622 623/// ActOnCXXTypeConstructExpr - Parse construction of a specified type. 624/// Can be interpreted either as function-style casting ("int(x)") 625/// or class type construction ("ClassType(x,y,z)") 626/// or creation of a value-initialized type ("int()"). 627ExprResult 628Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo, 629 SourceLocation LParenLoc, 630 MultiExprArg exprs, 631 SourceLocation RParenLoc) { 632 QualType Ty = TInfo->getType(); 633 unsigned NumExprs = exprs.size(); 634 Expr **Exprs = (Expr**)exprs.get(); 635 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc(); 636 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc); 637 638 if (Ty->isDependentType() || 639 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) { 640 exprs.release(); 641 642 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo, 643 LParenLoc, 644 Exprs, NumExprs, 645 RParenLoc)); 646 } 647 648 if (Ty->isArrayType()) 649 return ExprError(Diag(TyBeginLoc, 650 diag::err_value_init_for_array_type) << FullRange); 651 if (!Ty->isVoidType() && 652 RequireCompleteType(TyBeginLoc, Ty, 653 PDiag(diag::err_invalid_incomplete_type_use) 654 << FullRange)) 655 return ExprError(); 656 657 if (RequireNonAbstractType(TyBeginLoc, Ty, 658 diag::err_allocation_of_abstract_type)) 659 return ExprError(); 660 661 662 // C++ [expr.type.conv]p1: 663 // If the expression list is a single expression, the type conversion 664 // expression is equivalent (in definedness, and if defined in meaning) to the 665 // corresponding cast expression. 666 // 667 if (NumExprs == 1) { 668 CastKind Kind = CK_Invalid; 669 ExprValueKind VK = VK_RValue; 670 CXXCastPath BasePath; 671 if (CheckCastTypes(TInfo->getTypeLoc().getSourceRange(), Ty, Exprs[0], 672 Kind, VK, BasePath, 673 /*FunctionalStyle=*/true)) 674 return ExprError(); 675 676 exprs.release(); 677 678 return Owned(CXXFunctionalCastExpr::Create(Context, 679 Ty.getNonLValueExprType(Context), 680 VK, TInfo, TyBeginLoc, Kind, 681 Exprs[0], &BasePath, 682 RParenLoc)); 683 } 684 685 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo); 686 InitializationKind Kind 687 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc, 688 LParenLoc, RParenLoc) 689 : InitializationKind::CreateValue(TyBeginLoc, 690 LParenLoc, RParenLoc); 691 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs); 692 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs)); 693 694 // FIXME: Improve AST representation? 695 return move(Result); 696} 697 698/// doesUsualArrayDeleteWantSize - Answers whether the usual 699/// operator delete[] for the given type has a size_t parameter. 700static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc, 701 QualType allocType) { 702 const RecordType *record = 703 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>(); 704 if (!record) return false; 705 706 // Try to find an operator delete[] in class scope. 707 708 DeclarationName deleteName = 709 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete); 710 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName); 711 S.LookupQualifiedName(ops, record->getDecl()); 712 713 // We're just doing this for information. 714 ops.suppressDiagnostics(); 715 716 // Very likely: there's no operator delete[]. 717 if (ops.empty()) return false; 718 719 // If it's ambiguous, it should be illegal to call operator delete[] 720 // on this thing, so it doesn't matter if we allocate extra space or not. 721 if (ops.isAmbiguous()) return false; 722 723 LookupResult::Filter filter = ops.makeFilter(); 724 while (filter.hasNext()) { 725 NamedDecl *del = filter.next()->getUnderlyingDecl(); 726 727 // C++0x [basic.stc.dynamic.deallocation]p2: 728 // A template instance is never a usual deallocation function, 729 // regardless of its signature. 730 if (isa<FunctionTemplateDecl>(del)) { 731 filter.erase(); 732 continue; 733 } 734 735 // C++0x [basic.stc.dynamic.deallocation]p2: 736 // If class T does not declare [an operator delete[] with one 737 // parameter] but does declare a member deallocation function 738 // named operator delete[] with exactly two parameters, the 739 // second of which has type std::size_t, then this function 740 // is a usual deallocation function. 741 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) { 742 filter.erase(); 743 continue; 744 } 745 } 746 filter.done(); 747 748 if (!ops.isSingleResult()) return false; 749 750 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl()); 751 return (del->getNumParams() == 2); 752} 753 754/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.: 755/// @code new (memory) int[size][4] @endcode 756/// or 757/// @code ::new Foo(23, "hello") @endcode 758/// For the interpretation of this heap of arguments, consult the base version. 759ExprResult 760Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 761 SourceLocation PlacementLParen, MultiExprArg PlacementArgs, 762 SourceLocation PlacementRParen, SourceRange TypeIdParens, 763 Declarator &D, SourceLocation ConstructorLParen, 764 MultiExprArg ConstructorArgs, 765 SourceLocation ConstructorRParen) { 766 bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto; 767 768 Expr *ArraySize = 0; 769 // If the specified type is an array, unwrap it and save the expression. 770 if (D.getNumTypeObjects() > 0 && 771 D.getTypeObject(0).Kind == DeclaratorChunk::Array) { 772 DeclaratorChunk &Chunk = D.getTypeObject(0); 773 if (TypeContainsAuto) 774 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto) 775 << D.getSourceRange()); 776 if (Chunk.Arr.hasStatic) 777 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new) 778 << D.getSourceRange()); 779 if (!Chunk.Arr.NumElts) 780 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size) 781 << D.getSourceRange()); 782 783 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts); 784 D.DropFirstTypeObject(); 785 } 786 787 // Every dimension shall be of constant size. 788 if (ArraySize) { 789 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) { 790 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array) 791 break; 792 793 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr; 794 if (Expr *NumElts = (Expr *)Array.NumElts) { 795 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() && 796 !NumElts->isIntegerConstantExpr(Context)) { 797 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst) 798 << NumElts->getSourceRange(); 799 return ExprError(); 800 } 801 } 802 } 803 } 804 805 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0, /*OwnedDecl=*/0, 806 /*AllowAuto=*/true); 807 QualType AllocType = TInfo->getType(); 808 if (D.isInvalidType()) 809 return ExprError(); 810 811 return BuildCXXNew(StartLoc, UseGlobal, 812 PlacementLParen, 813 move(PlacementArgs), 814 PlacementRParen, 815 TypeIdParens, 816 AllocType, 817 TInfo, 818 ArraySize, 819 ConstructorLParen, 820 move(ConstructorArgs), 821 ConstructorRParen, 822 TypeContainsAuto); 823} 824 825ExprResult 826Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal, 827 SourceLocation PlacementLParen, 828 MultiExprArg PlacementArgs, 829 SourceLocation PlacementRParen, 830 SourceRange TypeIdParens, 831 QualType AllocType, 832 TypeSourceInfo *AllocTypeInfo, 833 Expr *ArraySize, 834 SourceLocation ConstructorLParen, 835 MultiExprArg ConstructorArgs, 836 SourceLocation ConstructorRParen, 837 bool TypeMayContainAuto) { 838 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange(); 839 840 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 841 if (TypeMayContainAuto && AllocType->getContainedAutoType()) { 842 if (ConstructorArgs.size() == 0) 843 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg) 844 << AllocType << TypeRange); 845 if (ConstructorArgs.size() != 1) { 846 Expr *FirstBad = ConstructorArgs.get()[1]; 847 return ExprError(Diag(FirstBad->getSourceRange().getBegin(), 848 diag::err_auto_new_ctor_multiple_expressions) 849 << AllocType << TypeRange); 850 } 851 QualType DeducedType; 852 if (!DeduceAutoType(AllocType, ConstructorArgs.get()[0], DeducedType)) 853 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure) 854 << AllocType 855 << ConstructorArgs.get()[0]->getType() 856 << TypeRange 857 << ConstructorArgs.get()[0]->getSourceRange()); 858 859 AllocType = DeducedType; 860 AllocTypeInfo = Context.getTrivialTypeSourceInfo(AllocType, StartLoc); 861 } 862 863 // Per C++0x [expr.new]p5, the type being constructed may be a 864 // typedef of an array type. 865 if (!ArraySize) { 866 if (const ConstantArrayType *Array 867 = Context.getAsConstantArrayType(AllocType)) { 868 ArraySize = IntegerLiteral::Create(Context, Array->getSize(), 869 Context.getSizeType(), 870 TypeRange.getEnd()); 871 AllocType = Array->getElementType(); 872 } 873 } 874 875 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange)) 876 return ExprError(); 877 878 QualType ResultType = Context.getPointerType(AllocType); 879 880 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral 881 // or enumeration type with a non-negative value." 882 if (ArraySize && !ArraySize->isTypeDependent()) { 883 884 QualType SizeType = ArraySize->getType(); 885 886 ExprResult ConvertedSize 887 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize, 888 PDiag(diag::err_array_size_not_integral), 889 PDiag(diag::err_array_size_incomplete_type) 890 << ArraySize->getSourceRange(), 891 PDiag(diag::err_array_size_explicit_conversion), 892 PDiag(diag::note_array_size_conversion), 893 PDiag(diag::err_array_size_ambiguous_conversion), 894 PDiag(diag::note_array_size_conversion), 895 PDiag(getLangOptions().CPlusPlus0x? 0 896 : diag::ext_array_size_conversion)); 897 if (ConvertedSize.isInvalid()) 898 return ExprError(); 899 900 ArraySize = ConvertedSize.take(); 901 SizeType = ArraySize->getType(); 902 if (!SizeType->isIntegralOrUnscopedEnumerationType()) 903 return ExprError(); 904 905 // Let's see if this is a constant < 0. If so, we reject it out of hand. 906 // We don't care about special rules, so we tell the machinery it's not 907 // evaluated - it gives us a result in more cases. 908 if (!ArraySize->isValueDependent()) { 909 llvm::APSInt Value; 910 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) { 911 if (Value < llvm::APSInt( 912 llvm::APInt::getNullValue(Value.getBitWidth()), 913 Value.isUnsigned())) 914 return ExprError(Diag(ArraySize->getSourceRange().getBegin(), 915 diag::err_typecheck_negative_array_size) 916 << ArraySize->getSourceRange()); 917 918 if (!AllocType->isDependentType()) { 919 unsigned ActiveSizeBits 920 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value); 921 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 922 Diag(ArraySize->getSourceRange().getBegin(), 923 diag::err_array_too_large) 924 << Value.toString(10) 925 << ArraySize->getSourceRange(); 926 return ExprError(); 927 } 928 } 929 } else if (TypeIdParens.isValid()) { 930 // Can't have dynamic array size when the type-id is in parentheses. 931 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst) 932 << ArraySize->getSourceRange() 933 << FixItHint::CreateRemoval(TypeIdParens.getBegin()) 934 << FixItHint::CreateRemoval(TypeIdParens.getEnd()); 935 936 TypeIdParens = SourceRange(); 937 } 938 } 939 940 ImpCastExprToType(ArraySize, Context.getSizeType(), 941 CK_IntegralCast); 942 } 943 944 FunctionDecl *OperatorNew = 0; 945 FunctionDecl *OperatorDelete = 0; 946 Expr **PlaceArgs = (Expr**)PlacementArgs.get(); 947 unsigned NumPlaceArgs = PlacementArgs.size(); 948 949 if (!AllocType->isDependentType() && 950 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) && 951 FindAllocationFunctions(StartLoc, 952 SourceRange(PlacementLParen, PlacementRParen), 953 UseGlobal, AllocType, ArraySize, PlaceArgs, 954 NumPlaceArgs, OperatorNew, OperatorDelete)) 955 return ExprError(); 956 957 // If this is an array allocation, compute whether the usual array 958 // deallocation function for the type has a size_t parameter. 959 bool UsualArrayDeleteWantsSize = false; 960 if (ArraySize && !AllocType->isDependentType()) 961 UsualArrayDeleteWantsSize 962 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType); 963 964 llvm::SmallVector<Expr *, 8> AllPlaceArgs; 965 if (OperatorNew) { 966 // Add default arguments, if any. 967 const FunctionProtoType *Proto = 968 OperatorNew->getType()->getAs<FunctionProtoType>(); 969 VariadicCallType CallType = 970 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply; 971 972 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, 973 Proto, 1, PlaceArgs, NumPlaceArgs, 974 AllPlaceArgs, CallType)) 975 return ExprError(); 976 977 NumPlaceArgs = AllPlaceArgs.size(); 978 if (NumPlaceArgs > 0) 979 PlaceArgs = &AllPlaceArgs[0]; 980 } 981 982 bool Init = ConstructorLParen.isValid(); 983 // --- Choosing a constructor --- 984 CXXConstructorDecl *Constructor = 0; 985 Expr **ConsArgs = (Expr**)ConstructorArgs.get(); 986 unsigned NumConsArgs = ConstructorArgs.size(); 987 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this); 988 989 // Array 'new' can't have any initializers. 990 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) { 991 SourceRange InitRange(ConsArgs[0]->getLocStart(), 992 ConsArgs[NumConsArgs - 1]->getLocEnd()); 993 994 Diag(StartLoc, diag::err_new_array_init_args) << InitRange; 995 return ExprError(); 996 } 997 998 if (!AllocType->isDependentType() && 999 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) { 1000 // C++0x [expr.new]p15: 1001 // A new-expression that creates an object of type T initializes that 1002 // object as follows: 1003 InitializationKind Kind 1004 // - If the new-initializer is omitted, the object is default- 1005 // initialized (8.5); if no initialization is performed, 1006 // the object has indeterminate value 1007 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin()) 1008 // - Otherwise, the new-initializer is interpreted according to the 1009 // initialization rules of 8.5 for direct-initialization. 1010 : InitializationKind::CreateDirect(TypeRange.getBegin(), 1011 ConstructorLParen, 1012 ConstructorRParen); 1013 1014 InitializedEntity Entity 1015 = InitializedEntity::InitializeNew(StartLoc, AllocType); 1016 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs); 1017 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, 1018 move(ConstructorArgs)); 1019 if (FullInit.isInvalid()) 1020 return ExprError(); 1021 1022 // FullInit is our initializer; walk through it to determine if it's a 1023 // constructor call, which CXXNewExpr handles directly. 1024 if (Expr *FullInitExpr = (Expr *)FullInit.get()) { 1025 if (CXXBindTemporaryExpr *Binder 1026 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr)) 1027 FullInitExpr = Binder->getSubExpr(); 1028 if (CXXConstructExpr *Construct 1029 = dyn_cast<CXXConstructExpr>(FullInitExpr)) { 1030 Constructor = Construct->getConstructor(); 1031 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(), 1032 AEnd = Construct->arg_end(); 1033 A != AEnd; ++A) 1034 ConvertedConstructorArgs.push_back(*A); 1035 } else { 1036 // Take the converted initializer. 1037 ConvertedConstructorArgs.push_back(FullInit.release()); 1038 } 1039 } else { 1040 // No initialization required. 1041 } 1042 1043 // Take the converted arguments and use them for the new expression. 1044 NumConsArgs = ConvertedConstructorArgs.size(); 1045 ConsArgs = (Expr **)ConvertedConstructorArgs.take(); 1046 } 1047 1048 // Mark the new and delete operators as referenced. 1049 if (OperatorNew) 1050 MarkDeclarationReferenced(StartLoc, OperatorNew); 1051 if (OperatorDelete) 1052 MarkDeclarationReferenced(StartLoc, OperatorDelete); 1053 1054 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16) 1055 1056 PlacementArgs.release(); 1057 ConstructorArgs.release(); 1058 1059 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew, 1060 PlaceArgs, NumPlaceArgs, TypeIdParens, 1061 ArraySize, Constructor, Init, 1062 ConsArgs, NumConsArgs, OperatorDelete, 1063 UsualArrayDeleteWantsSize, 1064 ResultType, AllocTypeInfo, 1065 StartLoc, 1066 Init ? ConstructorRParen : 1067 TypeRange.getEnd(), 1068 ConstructorLParen, ConstructorRParen)); 1069} 1070 1071/// CheckAllocatedType - Checks that a type is suitable as the allocated type 1072/// in a new-expression. 1073/// dimension off and stores the size expression in ArraySize. 1074bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc, 1075 SourceRange R) { 1076 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an 1077 // abstract class type or array thereof. 1078 if (AllocType->isFunctionType()) 1079 return Diag(Loc, diag::err_bad_new_type) 1080 << AllocType << 0 << R; 1081 else if (AllocType->isReferenceType()) 1082 return Diag(Loc, diag::err_bad_new_type) 1083 << AllocType << 1 << R; 1084 else if (!AllocType->isDependentType() && 1085 RequireCompleteType(Loc, AllocType, 1086 PDiag(diag::err_new_incomplete_type) 1087 << R)) 1088 return true; 1089 else if (RequireNonAbstractType(Loc, AllocType, 1090 diag::err_allocation_of_abstract_type)) 1091 return true; 1092 else if (AllocType->isVariablyModifiedType()) 1093 return Diag(Loc, diag::err_variably_modified_new_type) 1094 << AllocType; 1095 1096 return false; 1097} 1098 1099/// \brief Determine whether the given function is a non-placement 1100/// deallocation function. 1101static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) { 1102 if (FD->isInvalidDecl()) 1103 return false; 1104 1105 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD)) 1106 return Method->isUsualDeallocationFunction(); 1107 1108 return ((FD->getOverloadedOperator() == OO_Delete || 1109 FD->getOverloadedOperator() == OO_Array_Delete) && 1110 FD->getNumParams() == 1); 1111} 1112 1113/// FindAllocationFunctions - Finds the overloads of operator new and delete 1114/// that are appropriate for the allocation. 1115bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 1116 bool UseGlobal, QualType AllocType, 1117 bool IsArray, Expr **PlaceArgs, 1118 unsigned NumPlaceArgs, 1119 FunctionDecl *&OperatorNew, 1120 FunctionDecl *&OperatorDelete) { 1121 // --- Choosing an allocation function --- 1122 // C++ 5.3.4p8 - 14 & 18 1123 // 1) If UseGlobal is true, only look in the global scope. Else, also look 1124 // in the scope of the allocated class. 1125 // 2) If an array size is given, look for operator new[], else look for 1126 // operator new. 1127 // 3) The first argument is always size_t. Append the arguments from the 1128 // placement form. 1129 1130 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs); 1131 // We don't care about the actual value of this argument. 1132 // FIXME: Should the Sema create the expression and embed it in the syntax 1133 // tree? Or should the consumer just recalculate the value? 1134 IntegerLiteral Size(Context, llvm::APInt::getNullValue( 1135 Context.Target.getPointerWidth(0)), 1136 Context.getSizeType(), 1137 SourceLocation()); 1138 AllocArgs[0] = &Size; 1139 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1); 1140 1141 // C++ [expr.new]p8: 1142 // If the allocated type is a non-array type, the allocation 1143 // function's name is operator new and the deallocation function's 1144 // name is operator delete. If the allocated type is an array 1145 // type, the allocation function's name is operator new[] and the 1146 // deallocation function's name is operator delete[]. 1147 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName( 1148 IsArray ? OO_Array_New : OO_New); 1149 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( 1150 IsArray ? OO_Array_Delete : OO_Delete); 1151 1152 QualType AllocElemType = Context.getBaseElementType(AllocType); 1153 1154 if (AllocElemType->isRecordType() && !UseGlobal) { 1155 CXXRecordDecl *Record 1156 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl()); 1157 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0], 1158 AllocArgs.size(), Record, /*AllowMissing=*/true, 1159 OperatorNew)) 1160 return true; 1161 } 1162 if (!OperatorNew) { 1163 // Didn't find a member overload. Look for a global one. 1164 DeclareGlobalNewDelete(); 1165 DeclContext *TUDecl = Context.getTranslationUnitDecl(); 1166 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0], 1167 AllocArgs.size(), TUDecl, /*AllowMissing=*/false, 1168 OperatorNew)) 1169 return true; 1170 } 1171 1172 // We don't need an operator delete if we're running under 1173 // -fno-exceptions. 1174 if (!getLangOptions().Exceptions) { 1175 OperatorDelete = 0; 1176 return false; 1177 } 1178 1179 // FindAllocationOverload can change the passed in arguments, so we need to 1180 // copy them back. 1181 if (NumPlaceArgs > 0) 1182 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs); 1183 1184 // C++ [expr.new]p19: 1185 // 1186 // If the new-expression begins with a unary :: operator, the 1187 // deallocation function's name is looked up in the global 1188 // scope. Otherwise, if the allocated type is a class type T or an 1189 // array thereof, the deallocation function's name is looked up in 1190 // the scope of T. If this lookup fails to find the name, or if 1191 // the allocated type is not a class type or array thereof, the 1192 // deallocation function's name is looked up in the global scope. 1193 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName); 1194 if (AllocElemType->isRecordType() && !UseGlobal) { 1195 CXXRecordDecl *RD 1196 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl()); 1197 LookupQualifiedName(FoundDelete, RD); 1198 } 1199 if (FoundDelete.isAmbiguous()) 1200 return true; // FIXME: clean up expressions? 1201 1202 if (FoundDelete.empty()) { 1203 DeclareGlobalNewDelete(); 1204 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl()); 1205 } 1206 1207 FoundDelete.suppressDiagnostics(); 1208 1209 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches; 1210 1211 // Whether we're looking for a placement operator delete is dictated 1212 // by whether we selected a placement operator new, not by whether 1213 // we had explicit placement arguments. This matters for things like 1214 // struct A { void *operator new(size_t, int = 0); ... }; 1215 // A *a = new A() 1216 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1); 1217 1218 if (isPlacementNew) { 1219 // C++ [expr.new]p20: 1220 // A declaration of a placement deallocation function matches the 1221 // declaration of a placement allocation function if it has the 1222 // same number of parameters and, after parameter transformations 1223 // (8.3.5), all parameter types except the first are 1224 // identical. [...] 1225 // 1226 // To perform this comparison, we compute the function type that 1227 // the deallocation function should have, and use that type both 1228 // for template argument deduction and for comparison purposes. 1229 // 1230 // FIXME: this comparison should ignore CC and the like. 1231 QualType ExpectedFunctionType; 1232 { 1233 const FunctionProtoType *Proto 1234 = OperatorNew->getType()->getAs<FunctionProtoType>(); 1235 1236 llvm::SmallVector<QualType, 4> ArgTypes; 1237 ArgTypes.push_back(Context.VoidPtrTy); 1238 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I) 1239 ArgTypes.push_back(Proto->getArgType(I)); 1240 1241 FunctionProtoType::ExtProtoInfo EPI; 1242 EPI.Variadic = Proto->isVariadic(); 1243 1244 ExpectedFunctionType 1245 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(), 1246 ArgTypes.size(), EPI); 1247 } 1248 1249 for (LookupResult::iterator D = FoundDelete.begin(), 1250 DEnd = FoundDelete.end(); 1251 D != DEnd; ++D) { 1252 FunctionDecl *Fn = 0; 1253 if (FunctionTemplateDecl *FnTmpl 1254 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) { 1255 // Perform template argument deduction to try to match the 1256 // expected function type. 1257 TemplateDeductionInfo Info(Context, StartLoc); 1258 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info)) 1259 continue; 1260 } else 1261 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl()); 1262 1263 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType)) 1264 Matches.push_back(std::make_pair(D.getPair(), Fn)); 1265 } 1266 } else { 1267 // C++ [expr.new]p20: 1268 // [...] Any non-placement deallocation function matches a 1269 // non-placement allocation function. [...] 1270 for (LookupResult::iterator D = FoundDelete.begin(), 1271 DEnd = FoundDelete.end(); 1272 D != DEnd; ++D) { 1273 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl())) 1274 if (isNonPlacementDeallocationFunction(Fn)) 1275 Matches.push_back(std::make_pair(D.getPair(), Fn)); 1276 } 1277 } 1278 1279 // C++ [expr.new]p20: 1280 // [...] If the lookup finds a single matching deallocation 1281 // function, that function will be called; otherwise, no 1282 // deallocation function will be called. 1283 if (Matches.size() == 1) { 1284 OperatorDelete = Matches[0].second; 1285 1286 // C++0x [expr.new]p20: 1287 // If the lookup finds the two-parameter form of a usual 1288 // deallocation function (3.7.4.2) and that function, considered 1289 // as a placement deallocation function, would have been 1290 // selected as a match for the allocation function, the program 1291 // is ill-formed. 1292 if (NumPlaceArgs && getLangOptions().CPlusPlus0x && 1293 isNonPlacementDeallocationFunction(OperatorDelete)) { 1294 Diag(StartLoc, diag::err_placement_new_non_placement_delete) 1295 << SourceRange(PlaceArgs[0]->getLocStart(), 1296 PlaceArgs[NumPlaceArgs - 1]->getLocEnd()); 1297 Diag(OperatorDelete->getLocation(), diag::note_previous_decl) 1298 << DeleteName; 1299 } else { 1300 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(), 1301 Matches[0].first); 1302 } 1303 } 1304 1305 return false; 1306} 1307 1308/// FindAllocationOverload - Find an fitting overload for the allocation 1309/// function in the specified scope. 1310bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range, 1311 DeclarationName Name, Expr** Args, 1312 unsigned NumArgs, DeclContext *Ctx, 1313 bool AllowMissing, FunctionDecl *&Operator) { 1314 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName); 1315 LookupQualifiedName(R, Ctx); 1316 if (R.empty()) { 1317 if (AllowMissing) 1318 return false; 1319 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) 1320 << Name << Range; 1321 } 1322 1323 if (R.isAmbiguous()) 1324 return true; 1325 1326 R.suppressDiagnostics(); 1327 1328 OverloadCandidateSet Candidates(StartLoc); 1329 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end(); 1330 Alloc != AllocEnd; ++Alloc) { 1331 // Even member operator new/delete are implicitly treated as 1332 // static, so don't use AddMemberCandidate. 1333 NamedDecl *D = (*Alloc)->getUnderlyingDecl(); 1334 1335 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) { 1336 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(), 1337 /*ExplicitTemplateArgs=*/0, Args, NumArgs, 1338 Candidates, 1339 /*SuppressUserConversions=*/false); 1340 continue; 1341 } 1342 1343 FunctionDecl *Fn = cast<FunctionDecl>(D); 1344 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates, 1345 /*SuppressUserConversions=*/false); 1346 } 1347 1348 // Do the resolution. 1349 OverloadCandidateSet::iterator Best; 1350 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) { 1351 case OR_Success: { 1352 // Got one! 1353 FunctionDecl *FnDecl = Best->Function; 1354 MarkDeclarationReferenced(StartLoc, FnDecl); 1355 // The first argument is size_t, and the first parameter must be size_t, 1356 // too. This is checked on declaration and can be assumed. (It can't be 1357 // asserted on, though, since invalid decls are left in there.) 1358 // Watch out for variadic allocator function. 1359 unsigned NumArgsInFnDecl = FnDecl->getNumParams(); 1360 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) { 1361 ExprResult Result 1362 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 1363 Context, 1364 FnDecl->getParamDecl(i)), 1365 SourceLocation(), 1366 Owned(Args[i])); 1367 if (Result.isInvalid()) 1368 return true; 1369 1370 Args[i] = Result.takeAs<Expr>(); 1371 } 1372 Operator = FnDecl; 1373 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl); 1374 return false; 1375 } 1376 1377 case OR_No_Viable_Function: 1378 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) 1379 << Name << Range; 1380 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 1381 return true; 1382 1383 case OR_Ambiguous: 1384 Diag(StartLoc, diag::err_ovl_ambiguous_call) 1385 << Name << Range; 1386 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs); 1387 return true; 1388 1389 case OR_Deleted: 1390 Diag(StartLoc, diag::err_ovl_deleted_call) 1391 << Best->Function->isDeleted() 1392 << Name 1393 << Best->Function->getMessageUnavailableAttr( 1394 !Best->Function->isDeleted()) 1395 << Range; 1396 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 1397 return true; 1398 } 1399 assert(false && "Unreachable, bad result from BestViableFunction"); 1400 return true; 1401} 1402 1403 1404/// DeclareGlobalNewDelete - Declare the global forms of operator new and 1405/// delete. These are: 1406/// @code 1407/// // C++03: 1408/// void* operator new(std::size_t) throw(std::bad_alloc); 1409/// void* operator new[](std::size_t) throw(std::bad_alloc); 1410/// void operator delete(void *) throw(); 1411/// void operator delete[](void *) throw(); 1412/// // C++0x: 1413/// void* operator new(std::size_t); 1414/// void* operator new[](std::size_t); 1415/// void operator delete(void *); 1416/// void operator delete[](void *); 1417/// @endcode 1418/// C++0x operator delete is implicitly noexcept. 1419/// Note that the placement and nothrow forms of new are *not* implicitly 1420/// declared. Their use requires including \<new\>. 1421void Sema::DeclareGlobalNewDelete() { 1422 if (GlobalNewDeleteDeclared) 1423 return; 1424 1425 // C++ [basic.std.dynamic]p2: 1426 // [...] The following allocation and deallocation functions (18.4) are 1427 // implicitly declared in global scope in each translation unit of a 1428 // program 1429 // 1430 // C++03: 1431 // void* operator new(std::size_t) throw(std::bad_alloc); 1432 // void* operator new[](std::size_t) throw(std::bad_alloc); 1433 // void operator delete(void*) throw(); 1434 // void operator delete[](void*) throw(); 1435 // C++0x: 1436 // void* operator new(std::size_t); 1437 // void* operator new[](std::size_t); 1438 // void operator delete(void*); 1439 // void operator delete[](void*); 1440 // 1441 // These implicit declarations introduce only the function names operator 1442 // new, operator new[], operator delete, operator delete[]. 1443 // 1444 // Here, we need to refer to std::bad_alloc, so we will implicitly declare 1445 // "std" or "bad_alloc" as necessary to form the exception specification. 1446 // However, we do not make these implicit declarations visible to name 1447 // lookup. 1448 // Note that the C++0x versions of operator delete are deallocation functions, 1449 // and thus are implicitly noexcept. 1450 if (!StdBadAlloc && !getLangOptions().CPlusPlus0x) { 1451 // The "std::bad_alloc" class has not yet been declared, so build it 1452 // implicitly. 1453 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class, 1454 getOrCreateStdNamespace(), 1455 SourceLocation(), SourceLocation(), 1456 &PP.getIdentifierTable().get("bad_alloc"), 1457 0); 1458 getStdBadAlloc()->setImplicit(true); 1459 } 1460 1461 GlobalNewDeleteDeclared = true; 1462 1463 QualType VoidPtr = Context.getPointerType(Context.VoidTy); 1464 QualType SizeT = Context.getSizeType(); 1465 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew; 1466 1467 DeclareGlobalAllocationFunction( 1468 Context.DeclarationNames.getCXXOperatorName(OO_New), 1469 VoidPtr, SizeT, AssumeSaneOperatorNew); 1470 DeclareGlobalAllocationFunction( 1471 Context.DeclarationNames.getCXXOperatorName(OO_Array_New), 1472 VoidPtr, SizeT, AssumeSaneOperatorNew); 1473 DeclareGlobalAllocationFunction( 1474 Context.DeclarationNames.getCXXOperatorName(OO_Delete), 1475 Context.VoidTy, VoidPtr); 1476 DeclareGlobalAllocationFunction( 1477 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete), 1478 Context.VoidTy, VoidPtr); 1479} 1480 1481/// DeclareGlobalAllocationFunction - Declares a single implicit global 1482/// allocation function if it doesn't already exist. 1483void Sema::DeclareGlobalAllocationFunction(DeclarationName Name, 1484 QualType Return, QualType Argument, 1485 bool AddMallocAttr) { 1486 DeclContext *GlobalCtx = Context.getTranslationUnitDecl(); 1487 1488 // Check if this function is already declared. 1489 { 1490 DeclContext::lookup_iterator Alloc, AllocEnd; 1491 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name); 1492 Alloc != AllocEnd; ++Alloc) { 1493 // Only look at non-template functions, as it is the predefined, 1494 // non-templated allocation function we are trying to declare here. 1495 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) { 1496 QualType InitialParamType = 1497 Context.getCanonicalType( 1498 Func->getParamDecl(0)->getType().getUnqualifiedType()); 1499 // FIXME: Do we need to check for default arguments here? 1500 if (Func->getNumParams() == 1 && InitialParamType == Argument) { 1501 if(AddMallocAttr && !Func->hasAttr<MallocAttr>()) 1502 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context)); 1503 return; 1504 } 1505 } 1506 } 1507 } 1508 1509 QualType BadAllocType; 1510 bool HasBadAllocExceptionSpec 1511 = (Name.getCXXOverloadedOperator() == OO_New || 1512 Name.getCXXOverloadedOperator() == OO_Array_New); 1513 if (HasBadAllocExceptionSpec && !getLangOptions().CPlusPlus0x) { 1514 assert(StdBadAlloc && "Must have std::bad_alloc declared"); 1515 BadAllocType = Context.getTypeDeclType(getStdBadAlloc()); 1516 } 1517 1518 FunctionProtoType::ExtProtoInfo EPI; 1519 if (HasBadAllocExceptionSpec) { 1520 if (!getLangOptions().CPlusPlus0x) { 1521 EPI.ExceptionSpecType = EST_Dynamic; 1522 EPI.NumExceptions = 1; 1523 EPI.Exceptions = &BadAllocType; 1524 } 1525 } else { 1526 EPI.ExceptionSpecType = getLangOptions().CPlusPlus0x ? 1527 EST_BasicNoexcept : EST_DynamicNone; 1528 } 1529 1530 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI); 1531 FunctionDecl *Alloc = 1532 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), 1533 SourceLocation(), Name, 1534 FnType, /*TInfo=*/0, SC_None, 1535 SC_None, false, true); 1536 Alloc->setImplicit(); 1537 1538 if (AddMallocAttr) 1539 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context)); 1540 1541 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(), 1542 SourceLocation(), 0, 1543 Argument, /*TInfo=*/0, 1544 SC_None, SC_None, 0); 1545 Alloc->setParams(&Param, 1); 1546 1547 // FIXME: Also add this declaration to the IdentifierResolver, but 1548 // make sure it is at the end of the chain to coincide with the 1549 // global scope. 1550 Context.getTranslationUnitDecl()->addDecl(Alloc); 1551} 1552 1553bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, 1554 DeclarationName Name, 1555 FunctionDecl* &Operator) { 1556 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName); 1557 // Try to find operator delete/operator delete[] in class scope. 1558 LookupQualifiedName(Found, RD); 1559 1560 if (Found.isAmbiguous()) 1561 return true; 1562 1563 Found.suppressDiagnostics(); 1564 1565 llvm::SmallVector<DeclAccessPair,4> Matches; 1566 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end(); 1567 F != FEnd; ++F) { 1568 NamedDecl *ND = (*F)->getUnderlyingDecl(); 1569 1570 // Ignore template operator delete members from the check for a usual 1571 // deallocation function. 1572 if (isa<FunctionTemplateDecl>(ND)) 1573 continue; 1574 1575 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction()) 1576 Matches.push_back(F.getPair()); 1577 } 1578 1579 // There's exactly one suitable operator; pick it. 1580 if (Matches.size() == 1) { 1581 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl()); 1582 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(), 1583 Matches[0]); 1584 return false; 1585 1586 // We found multiple suitable operators; complain about the ambiguity. 1587 } else if (!Matches.empty()) { 1588 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found) 1589 << Name << RD; 1590 1591 for (llvm::SmallVectorImpl<DeclAccessPair>::iterator 1592 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F) 1593 Diag((*F)->getUnderlyingDecl()->getLocation(), 1594 diag::note_member_declared_here) << Name; 1595 return true; 1596 } 1597 1598 // We did find operator delete/operator delete[] declarations, but 1599 // none of them were suitable. 1600 if (!Found.empty()) { 1601 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found) 1602 << Name << RD; 1603 1604 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end(); 1605 F != FEnd; ++F) 1606 Diag((*F)->getUnderlyingDecl()->getLocation(), 1607 diag::note_member_declared_here) << Name; 1608 1609 return true; 1610 } 1611 1612 // Look for a global declaration. 1613 DeclareGlobalNewDelete(); 1614 DeclContext *TUDecl = Context.getTranslationUnitDecl(); 1615 1616 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation()); 1617 Expr* DeallocArgs[1]; 1618 DeallocArgs[0] = &Null; 1619 if (FindAllocationOverload(StartLoc, SourceRange(), Name, 1620 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false, 1621 Operator)) 1622 return true; 1623 1624 assert(Operator && "Did not find a deallocation function!"); 1625 return false; 1626} 1627 1628/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in: 1629/// @code ::delete ptr; @endcode 1630/// or 1631/// @code delete [] ptr; @endcode 1632ExprResult 1633Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, 1634 bool ArrayForm, Expr *Ex) { 1635 // C++ [expr.delete]p1: 1636 // The operand shall have a pointer type, or a class type having a single 1637 // conversion function to a pointer type. The result has type void. 1638 // 1639 // DR599 amends "pointer type" to "pointer to object type" in both cases. 1640 1641 FunctionDecl *OperatorDelete = 0; 1642 bool ArrayFormAsWritten = ArrayForm; 1643 bool UsualArrayDeleteWantsSize = false; 1644 1645 if (!Ex->isTypeDependent()) { 1646 QualType Type = Ex->getType(); 1647 1648 if (const RecordType *Record = Type->getAs<RecordType>()) { 1649 if (RequireCompleteType(StartLoc, Type, 1650 PDiag(diag::err_delete_incomplete_class_type))) 1651 return ExprError(); 1652 1653 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions; 1654 1655 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1656 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions(); 1657 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 1658 E = Conversions->end(); I != E; ++I) { 1659 NamedDecl *D = I.getDecl(); 1660 if (isa<UsingShadowDecl>(D)) 1661 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 1662 1663 // Skip over templated conversion functions; they aren't considered. 1664 if (isa<FunctionTemplateDecl>(D)) 1665 continue; 1666 1667 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 1668 1669 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 1670 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 1671 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType()) 1672 ObjectPtrConversions.push_back(Conv); 1673 } 1674 if (ObjectPtrConversions.size() == 1) { 1675 // We have a single conversion to a pointer-to-object type. Perform 1676 // that conversion. 1677 // TODO: don't redo the conversion calculation. 1678 if (!PerformImplicitConversion(Ex, 1679 ObjectPtrConversions.front()->getConversionType(), 1680 AA_Converting)) { 1681 Type = Ex->getType(); 1682 } 1683 } 1684 else if (ObjectPtrConversions.size() > 1) { 1685 Diag(StartLoc, diag::err_ambiguous_delete_operand) 1686 << Type << Ex->getSourceRange(); 1687 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) 1688 NoteOverloadCandidate(ObjectPtrConversions[i]); 1689 return ExprError(); 1690 } 1691 } 1692 1693 if (!Type->isPointerType()) 1694 return ExprError(Diag(StartLoc, diag::err_delete_operand) 1695 << Type << Ex->getSourceRange()); 1696 1697 QualType Pointee = Type->getAs<PointerType>()->getPointeeType(); 1698 if (Pointee->isVoidType() && !isSFINAEContext()) { 1699 // The C++ standard bans deleting a pointer to a non-object type, which 1700 // effectively bans deletion of "void*". However, most compilers support 1701 // this, so we treat it as a warning unless we're in a SFINAE context. 1702 Diag(StartLoc, diag::ext_delete_void_ptr_operand) 1703 << Type << Ex->getSourceRange(); 1704 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) 1705 return ExprError(Diag(StartLoc, diag::err_delete_operand) 1706 << Type << Ex->getSourceRange()); 1707 else if (!Pointee->isDependentType() && 1708 RequireCompleteType(StartLoc, Pointee, 1709 PDiag(diag::warn_delete_incomplete) 1710 << Ex->getSourceRange())) 1711 return ExprError(); 1712 1713 // C++ [expr.delete]p2: 1714 // [Note: a pointer to a const type can be the operand of a 1715 // delete-expression; it is not necessary to cast away the constness 1716 // (5.2.11) of the pointer expression before it is used as the operand 1717 // of the delete-expression. ] 1718 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy), 1719 CK_NoOp); 1720 1721 if (Pointee->isArrayType() && !ArrayForm) { 1722 Diag(StartLoc, diag::warn_delete_array_type) 1723 << Type << Ex->getSourceRange() 1724 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]"); 1725 ArrayForm = true; 1726 } 1727 1728 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( 1729 ArrayForm ? OO_Array_Delete : OO_Delete); 1730 1731 QualType PointeeElem = Context.getBaseElementType(Pointee); 1732 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) { 1733 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 1734 1735 if (!UseGlobal && 1736 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete)) 1737 return ExprError(); 1738 1739 // If we're allocating an array of records, check whether the 1740 // usual operator delete[] has a size_t parameter. 1741 if (ArrayForm) { 1742 // If the user specifically asked to use the global allocator, 1743 // we'll need to do the lookup into the class. 1744 if (UseGlobal) 1745 UsualArrayDeleteWantsSize = 1746 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem); 1747 1748 // Otherwise, the usual operator delete[] should be the 1749 // function we just found. 1750 else if (isa<CXXMethodDecl>(OperatorDelete)) 1751 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2); 1752 } 1753 1754 if (!RD->hasTrivialDestructor()) 1755 if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) { 1756 MarkDeclarationReferenced(StartLoc, 1757 const_cast<CXXDestructorDecl*>(Dtor)); 1758 DiagnoseUseOfDecl(Dtor, StartLoc); 1759 } 1760 } 1761 1762 if (!OperatorDelete) { 1763 // Look for a global declaration. 1764 DeclareGlobalNewDelete(); 1765 DeclContext *TUDecl = Context.getTranslationUnitDecl(); 1766 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName, 1767 &Ex, 1, TUDecl, /*AllowMissing=*/false, 1768 OperatorDelete)) 1769 return ExprError(); 1770 } 1771 1772 MarkDeclarationReferenced(StartLoc, OperatorDelete); 1773 1774 // Check access and ambiguity of operator delete and destructor. 1775 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) { 1776 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 1777 if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) { 1778 CheckDestructorAccess(Ex->getExprLoc(), Dtor, 1779 PDiag(diag::err_access_dtor) << PointeeElem); 1780 } 1781 } 1782 1783 } 1784 1785 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm, 1786 ArrayFormAsWritten, 1787 UsualArrayDeleteWantsSize, 1788 OperatorDelete, Ex, StartLoc)); 1789} 1790 1791/// \brief Check the use of the given variable as a C++ condition in an if, 1792/// while, do-while, or switch statement. 1793ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar, 1794 SourceLocation StmtLoc, 1795 bool ConvertToBoolean) { 1796 QualType T = ConditionVar->getType(); 1797 1798 // C++ [stmt.select]p2: 1799 // The declarator shall not specify a function or an array. 1800 if (T->isFunctionType()) 1801 return ExprError(Diag(ConditionVar->getLocation(), 1802 diag::err_invalid_use_of_function_type) 1803 << ConditionVar->getSourceRange()); 1804 else if (T->isArrayType()) 1805 return ExprError(Diag(ConditionVar->getLocation(), 1806 diag::err_invalid_use_of_array_type) 1807 << ConditionVar->getSourceRange()); 1808 1809 Expr *Condition = DeclRefExpr::Create(Context, NestedNameSpecifierLoc(), 1810 ConditionVar, 1811 ConditionVar->getLocation(), 1812 ConditionVar->getType().getNonReferenceType(), 1813 VK_LValue); 1814 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc)) 1815 return ExprError(); 1816 1817 return Owned(Condition); 1818} 1819 1820/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid. 1821bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) { 1822 // C++ 6.4p4: 1823 // The value of a condition that is an initialized declaration in a statement 1824 // other than a switch statement is the value of the declared variable 1825 // implicitly converted to type bool. If that conversion is ill-formed, the 1826 // program is ill-formed. 1827 // The value of a condition that is an expression is the value of the 1828 // expression, implicitly converted to bool. 1829 // 1830 return PerformContextuallyConvertToBool(CondExpr); 1831} 1832 1833/// Helper function to determine whether this is the (deprecated) C++ 1834/// conversion from a string literal to a pointer to non-const char or 1835/// non-const wchar_t (for narrow and wide string literals, 1836/// respectively). 1837bool 1838Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) { 1839 // Look inside the implicit cast, if it exists. 1840 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From)) 1841 From = Cast->getSubExpr(); 1842 1843 // A string literal (2.13.4) that is not a wide string literal can 1844 // be converted to an rvalue of type "pointer to char"; a wide 1845 // string literal can be converted to an rvalue of type "pointer 1846 // to wchar_t" (C++ 4.2p2). 1847 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens())) 1848 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) 1849 if (const BuiltinType *ToPointeeType 1850 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) { 1851 // This conversion is considered only when there is an 1852 // explicit appropriate pointer target type (C++ 4.2p2). 1853 if (!ToPtrType->getPointeeType().hasQualifiers() && 1854 ((StrLit->isWide() && ToPointeeType->isWideCharType()) || 1855 (!StrLit->isWide() && 1856 (ToPointeeType->getKind() == BuiltinType::Char_U || 1857 ToPointeeType->getKind() == BuiltinType::Char_S)))) 1858 return true; 1859 } 1860 1861 return false; 1862} 1863 1864static ExprResult BuildCXXCastArgument(Sema &S, 1865 SourceLocation CastLoc, 1866 QualType Ty, 1867 CastKind Kind, 1868 CXXMethodDecl *Method, 1869 NamedDecl *FoundDecl, 1870 Expr *From) { 1871 switch (Kind) { 1872 default: assert(0 && "Unhandled cast kind!"); 1873 case CK_ConstructorConversion: { 1874 ASTOwningVector<Expr*> ConstructorArgs(S); 1875 1876 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method), 1877 MultiExprArg(&From, 1), 1878 CastLoc, ConstructorArgs)) 1879 return ExprError(); 1880 1881 ExprResult Result = 1882 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method), 1883 move_arg(ConstructorArgs), 1884 /*ZeroInit*/ false, CXXConstructExpr::CK_Complete, 1885 SourceRange()); 1886 if (Result.isInvalid()) 1887 return ExprError(); 1888 1889 return S.MaybeBindToTemporary(Result.takeAs<Expr>()); 1890 } 1891 1892 case CK_UserDefinedConversion: { 1893 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!"); 1894 1895 // Create an implicit call expr that calls it. 1896 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method); 1897 if (Result.isInvalid()) 1898 return ExprError(); 1899 1900 return S.MaybeBindToTemporary(Result.get()); 1901 } 1902 } 1903} 1904 1905/// PerformImplicitConversion - Perform an implicit conversion of the 1906/// expression From to the type ToType using the pre-computed implicit 1907/// conversion sequence ICS. Returns true if there was an error, false 1908/// otherwise. The expression From is replaced with the converted 1909/// expression. Action is the kind of conversion we're performing, 1910/// used in the error message. 1911bool 1912Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 1913 const ImplicitConversionSequence &ICS, 1914 AssignmentAction Action, bool CStyle) { 1915 switch (ICS.getKind()) { 1916 case ImplicitConversionSequence::StandardConversion: 1917 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action, 1918 CStyle)) 1919 return true; 1920 break; 1921 1922 case ImplicitConversionSequence::UserDefinedConversion: { 1923 1924 FunctionDecl *FD = ICS.UserDefined.ConversionFunction; 1925 CastKind CastKind; 1926 QualType BeforeToType; 1927 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) { 1928 CastKind = CK_UserDefinedConversion; 1929 1930 // If the user-defined conversion is specified by a conversion function, 1931 // the initial standard conversion sequence converts the source type to 1932 // the implicit object parameter of the conversion function. 1933 BeforeToType = Context.getTagDeclType(Conv->getParent()); 1934 } else { 1935 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD); 1936 CastKind = CK_ConstructorConversion; 1937 // Do no conversion if dealing with ... for the first conversion. 1938 if (!ICS.UserDefined.EllipsisConversion) { 1939 // If the user-defined conversion is specified by a constructor, the 1940 // initial standard conversion sequence converts the source type to the 1941 // type required by the argument of the constructor 1942 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType(); 1943 } 1944 } 1945 // Watch out for elipsis conversion. 1946 if (!ICS.UserDefined.EllipsisConversion) { 1947 if (PerformImplicitConversion(From, BeforeToType, 1948 ICS.UserDefined.Before, AA_Converting, 1949 CStyle)) 1950 return true; 1951 } 1952 1953 ExprResult CastArg 1954 = BuildCXXCastArgument(*this, 1955 From->getLocStart(), 1956 ToType.getNonReferenceType(), 1957 CastKind, cast<CXXMethodDecl>(FD), 1958 ICS.UserDefined.FoundConversionFunction, 1959 From); 1960 1961 if (CastArg.isInvalid()) 1962 return true; 1963 1964 From = CastArg.takeAs<Expr>(); 1965 1966 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After, 1967 AA_Converting, CStyle); 1968 } 1969 1970 case ImplicitConversionSequence::AmbiguousConversion: 1971 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(), 1972 PDiag(diag::err_typecheck_ambiguous_condition) 1973 << From->getSourceRange()); 1974 return true; 1975 1976 case ImplicitConversionSequence::EllipsisConversion: 1977 assert(false && "Cannot perform an ellipsis conversion"); 1978 return false; 1979 1980 case ImplicitConversionSequence::BadConversion: 1981 return true; 1982 } 1983 1984 // Everything went well. 1985 return false; 1986} 1987 1988/// PerformImplicitConversion - Perform an implicit conversion of the 1989/// expression From to the type ToType by following the standard 1990/// conversion sequence SCS. Returns true if there was an error, false 1991/// otherwise. The expression From is replaced with the converted 1992/// expression. Flavor is the context in which we're performing this 1993/// conversion, for use in error messages. 1994bool 1995Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 1996 const StandardConversionSequence& SCS, 1997 AssignmentAction Action, bool CStyle) { 1998 // Overall FIXME: we are recomputing too many types here and doing far too 1999 // much extra work. What this means is that we need to keep track of more 2000 // information that is computed when we try the implicit conversion initially, 2001 // so that we don't need to recompute anything here. 2002 QualType FromType = From->getType(); 2003 2004 if (SCS.CopyConstructor) { 2005 // FIXME: When can ToType be a reference type? 2006 assert(!ToType->isReferenceType()); 2007 if (SCS.Second == ICK_Derived_To_Base) { 2008 ASTOwningVector<Expr*> ConstructorArgs(*this); 2009 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor), 2010 MultiExprArg(*this, &From, 1), 2011 /*FIXME:ConstructLoc*/SourceLocation(), 2012 ConstructorArgs)) 2013 return true; 2014 ExprResult FromResult = 2015 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(), 2016 ToType, SCS.CopyConstructor, 2017 move_arg(ConstructorArgs), 2018 /*ZeroInit*/ false, 2019 CXXConstructExpr::CK_Complete, 2020 SourceRange()); 2021 if (FromResult.isInvalid()) 2022 return true; 2023 From = FromResult.takeAs<Expr>(); 2024 return false; 2025 } 2026 ExprResult FromResult = 2027 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(), 2028 ToType, SCS.CopyConstructor, 2029 MultiExprArg(*this, &From, 1), 2030 /*ZeroInit*/ false, 2031 CXXConstructExpr::CK_Complete, 2032 SourceRange()); 2033 2034 if (FromResult.isInvalid()) 2035 return true; 2036 2037 From = FromResult.takeAs<Expr>(); 2038 return false; 2039 } 2040 2041 // Resolve overloaded function references. 2042 if (Context.hasSameType(FromType, Context.OverloadTy)) { 2043 DeclAccessPair Found; 2044 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, 2045 true, Found); 2046 if (!Fn) 2047 return true; 2048 2049 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin())) 2050 return true; 2051 2052 From = FixOverloadedFunctionReference(From, Found, Fn); 2053 FromType = From->getType(); 2054 } 2055 2056 // Perform the first implicit conversion. 2057 switch (SCS.First) { 2058 case ICK_Identity: 2059 // Nothing to do. 2060 break; 2061 2062 case ICK_Lvalue_To_Rvalue: 2063 // Should this get its own ICK? 2064 if (From->getObjectKind() == OK_ObjCProperty) { 2065 ConvertPropertyForRValue(From); 2066 if (!From->isGLValue()) break; 2067 } 2068 2069 // Check for trivial buffer overflows. 2070 CheckArrayAccess(From); 2071 2072 FromType = FromType.getUnqualifiedType(); 2073 From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue, 2074 From, 0, VK_RValue); 2075 break; 2076 2077 case ICK_Array_To_Pointer: 2078 FromType = Context.getArrayDecayedType(FromType); 2079 ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay); 2080 break; 2081 2082 case ICK_Function_To_Pointer: 2083 FromType = Context.getPointerType(FromType); 2084 ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay); 2085 break; 2086 2087 default: 2088 assert(false && "Improper first standard conversion"); 2089 break; 2090 } 2091 2092 // Perform the second implicit conversion 2093 switch (SCS.Second) { 2094 case ICK_Identity: 2095 // If both sides are functions (or pointers/references to them), there could 2096 // be incompatible exception declarations. 2097 if (CheckExceptionSpecCompatibility(From, ToType)) 2098 return true; 2099 // Nothing else to do. 2100 break; 2101 2102 case ICK_NoReturn_Adjustment: 2103 // If both sides are functions (or pointers/references to them), there could 2104 // be incompatible exception declarations. 2105 if (CheckExceptionSpecCompatibility(From, ToType)) 2106 return true; 2107 2108 ImpCastExprToType(From, ToType, CK_NoOp); 2109 break; 2110 2111 case ICK_Integral_Promotion: 2112 case ICK_Integral_Conversion: 2113 ImpCastExprToType(From, ToType, CK_IntegralCast); 2114 break; 2115 2116 case ICK_Floating_Promotion: 2117 case ICK_Floating_Conversion: 2118 ImpCastExprToType(From, ToType, CK_FloatingCast); 2119 break; 2120 2121 case ICK_Complex_Promotion: 2122 case ICK_Complex_Conversion: { 2123 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType(); 2124 QualType ToEl = ToType->getAs<ComplexType>()->getElementType(); 2125 CastKind CK; 2126 if (FromEl->isRealFloatingType()) { 2127 if (ToEl->isRealFloatingType()) 2128 CK = CK_FloatingComplexCast; 2129 else 2130 CK = CK_FloatingComplexToIntegralComplex; 2131 } else if (ToEl->isRealFloatingType()) { 2132 CK = CK_IntegralComplexToFloatingComplex; 2133 } else { 2134 CK = CK_IntegralComplexCast; 2135 } 2136 ImpCastExprToType(From, ToType, CK); 2137 break; 2138 } 2139 2140 case ICK_Floating_Integral: 2141 if (ToType->isRealFloatingType()) 2142 ImpCastExprToType(From, ToType, CK_IntegralToFloating); 2143 else 2144 ImpCastExprToType(From, ToType, CK_FloatingToIntegral); 2145 break; 2146 2147 case ICK_Compatible_Conversion: 2148 ImpCastExprToType(From, ToType, CK_NoOp); 2149 break; 2150 2151 case ICK_Pointer_Conversion: { 2152 if (SCS.IncompatibleObjC && Action != AA_Casting) { 2153 // Diagnose incompatible Objective-C conversions 2154 Diag(From->getSourceRange().getBegin(), 2155 diag::ext_typecheck_convert_incompatible_pointer) 2156 << From->getType() << ToType << Action 2157 << From->getSourceRange(); 2158 } 2159 2160 CastKind Kind = CK_Invalid; 2161 CXXCastPath BasePath; 2162 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle)) 2163 return true; 2164 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath); 2165 break; 2166 } 2167 2168 case ICK_Pointer_Member: { 2169 CastKind Kind = CK_Invalid; 2170 CXXCastPath BasePath; 2171 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle)) 2172 return true; 2173 if (CheckExceptionSpecCompatibility(From, ToType)) 2174 return true; 2175 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath); 2176 break; 2177 } 2178 case ICK_Boolean_Conversion: { 2179 CastKind Kind = CK_Invalid; 2180 switch (FromType->getScalarTypeKind()) { 2181 case Type::STK_Pointer: Kind = CK_PointerToBoolean; break; 2182 case Type::STK_MemberPointer: Kind = CK_MemberPointerToBoolean; break; 2183 case Type::STK_Bool: llvm_unreachable("bool -> bool conversion?"); 2184 case Type::STK_Integral: Kind = CK_IntegralToBoolean; break; 2185 case Type::STK_Floating: Kind = CK_FloatingToBoolean; break; 2186 case Type::STK_IntegralComplex: Kind = CK_IntegralComplexToBoolean; break; 2187 case Type::STK_FloatingComplex: Kind = CK_FloatingComplexToBoolean; break; 2188 } 2189 2190 ImpCastExprToType(From, Context.BoolTy, Kind); 2191 break; 2192 } 2193 2194 case ICK_Derived_To_Base: { 2195 CXXCastPath BasePath; 2196 if (CheckDerivedToBaseConversion(From->getType(), 2197 ToType.getNonReferenceType(), 2198 From->getLocStart(), 2199 From->getSourceRange(), 2200 &BasePath, 2201 CStyle)) 2202 return true; 2203 2204 ImpCastExprToType(From, ToType.getNonReferenceType(), 2205 CK_DerivedToBase, CastCategory(From), 2206 &BasePath); 2207 break; 2208 } 2209 2210 case ICK_Vector_Conversion: 2211 ImpCastExprToType(From, ToType, CK_BitCast); 2212 break; 2213 2214 case ICK_Vector_Splat: 2215 ImpCastExprToType(From, ToType, CK_VectorSplat); 2216 break; 2217 2218 case ICK_Complex_Real: 2219 // Case 1. x -> _Complex y 2220 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) { 2221 QualType ElType = ToComplex->getElementType(); 2222 bool isFloatingComplex = ElType->isRealFloatingType(); 2223 2224 // x -> y 2225 if (Context.hasSameUnqualifiedType(ElType, From->getType())) { 2226 // do nothing 2227 } else if (From->getType()->isRealFloatingType()) { 2228 ImpCastExprToType(From, ElType, 2229 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral); 2230 } else { 2231 assert(From->getType()->isIntegerType()); 2232 ImpCastExprToType(From, ElType, 2233 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast); 2234 } 2235 // y -> _Complex y 2236 ImpCastExprToType(From, ToType, 2237 isFloatingComplex ? CK_FloatingRealToComplex 2238 : CK_IntegralRealToComplex); 2239 2240 // Case 2. _Complex x -> y 2241 } else { 2242 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>(); 2243 assert(FromComplex); 2244 2245 QualType ElType = FromComplex->getElementType(); 2246 bool isFloatingComplex = ElType->isRealFloatingType(); 2247 2248 // _Complex x -> x 2249 ImpCastExprToType(From, ElType, 2250 isFloatingComplex ? CK_FloatingComplexToReal 2251 : CK_IntegralComplexToReal); 2252 2253 // x -> y 2254 if (Context.hasSameUnqualifiedType(ElType, ToType)) { 2255 // do nothing 2256 } else if (ToType->isRealFloatingType()) { 2257 ImpCastExprToType(From, ToType, 2258 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating); 2259 } else { 2260 assert(ToType->isIntegerType()); 2261 ImpCastExprToType(From, ToType, 2262 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast); 2263 } 2264 } 2265 break; 2266 2267 case ICK_Block_Pointer_Conversion: { 2268 ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast, VK_RValue); 2269 break; 2270 } 2271 2272 case ICK_Lvalue_To_Rvalue: 2273 case ICK_Array_To_Pointer: 2274 case ICK_Function_To_Pointer: 2275 case ICK_Qualification: 2276 case ICK_Num_Conversion_Kinds: 2277 assert(false && "Improper second standard conversion"); 2278 break; 2279 } 2280 2281 switch (SCS.Third) { 2282 case ICK_Identity: 2283 // Nothing to do. 2284 break; 2285 2286 case ICK_Qualification: { 2287 // The qualification keeps the category of the inner expression, unless the 2288 // target type isn't a reference. 2289 ExprValueKind VK = ToType->isReferenceType() ? 2290 CastCategory(From) : VK_RValue; 2291 ImpCastExprToType(From, ToType.getNonLValueExprType(Context), 2292 CK_NoOp, VK); 2293 2294 if (SCS.DeprecatedStringLiteralToCharPtr && 2295 !getLangOptions().WritableStrings) 2296 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion) 2297 << ToType.getNonReferenceType(); 2298 2299 break; 2300 } 2301 2302 default: 2303 assert(false && "Improper third standard conversion"); 2304 break; 2305 } 2306 2307 return false; 2308} 2309 2310ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT, 2311 SourceLocation KWLoc, 2312 ParsedType Ty, 2313 SourceLocation RParen) { 2314 TypeSourceInfo *TSInfo; 2315 QualType T = GetTypeFromParser(Ty, &TSInfo); 2316 2317 if (!TSInfo) 2318 TSInfo = Context.getTrivialTypeSourceInfo(T); 2319 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen); 2320} 2321 2322static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT, QualType T, 2323 SourceLocation KeyLoc) { 2324 // FIXME: For many of these traits, we need a complete type before we can 2325 // check these properties. 2326 assert(!T->isDependentType() && 2327 "Cannot evaluate traits for dependent types."); 2328 ASTContext &C = Self.Context; 2329 switch(UTT) { 2330 default: assert(false && "Unknown type trait or not implemented"); 2331 case UTT_IsPOD: return T->isPODType(); 2332 case UTT_IsLiteral: return T->isLiteralType(); 2333 case UTT_IsClass: // Fallthrough 2334 case UTT_IsUnion: 2335 if (const RecordType *Record = T->getAs<RecordType>()) { 2336 bool Union = Record->getDecl()->isUnion(); 2337 return UTT == UTT_IsUnion ? Union : !Union; 2338 } 2339 return false; 2340 case UTT_IsEnum: return T->isEnumeralType(); 2341 case UTT_IsPolymorphic: 2342 if (const RecordType *Record = T->getAs<RecordType>()) { 2343 // Type traits are only parsed in C++, so we've got CXXRecords. 2344 return cast<CXXRecordDecl>(Record->getDecl())->isPolymorphic(); 2345 } 2346 return false; 2347 case UTT_IsAbstract: 2348 if (const RecordType *RT = T->getAs<RecordType>()) 2349 return cast<CXXRecordDecl>(RT->getDecl())->isAbstract(); 2350 return false; 2351 case UTT_IsEmpty: 2352 if (const RecordType *Record = T->getAs<RecordType>()) { 2353 return !Record->getDecl()->isUnion() 2354 && cast<CXXRecordDecl>(Record->getDecl())->isEmpty(); 2355 } 2356 return false; 2357 case UTT_HasTrivialConstructor: 2358 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 2359 // If __is_pod (type) is true then the trait is true, else if type is 2360 // a cv class or union type (or array thereof) with a trivial default 2361 // constructor ([class.ctor]) then the trait is true, else it is false. 2362 if (T->isPODType()) 2363 return true; 2364 if (const RecordType *RT = 2365 C.getBaseElementType(T)->getAs<RecordType>()) 2366 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialConstructor(); 2367 return false; 2368 case UTT_HasTrivialCopy: 2369 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 2370 // If __is_pod (type) is true or type is a reference type then 2371 // the trait is true, else if type is a cv class or union type 2372 // with a trivial copy constructor ([class.copy]) then the trait 2373 // is true, else it is false. 2374 if (T->isPODType() || T->isReferenceType()) 2375 return true; 2376 if (const RecordType *RT = T->getAs<RecordType>()) 2377 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor(); 2378 return false; 2379 case UTT_HasTrivialAssign: 2380 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 2381 // If type is const qualified or is a reference type then the 2382 // trait is false. Otherwise if __is_pod (type) is true then the 2383 // trait is true, else if type is a cv class or union type with 2384 // a trivial copy assignment ([class.copy]) then the trait is 2385 // true, else it is false. 2386 // Note: the const and reference restrictions are interesting, 2387 // given that const and reference members don't prevent a class 2388 // from having a trivial copy assignment operator (but do cause 2389 // errors if the copy assignment operator is actually used, q.v. 2390 // [class.copy]p12). 2391 2392 if (C.getBaseElementType(T).isConstQualified()) 2393 return false; 2394 if (T->isPODType()) 2395 return true; 2396 if (const RecordType *RT = T->getAs<RecordType>()) 2397 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment(); 2398 return false; 2399 case UTT_HasTrivialDestructor: 2400 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 2401 // If __is_pod (type) is true or type is a reference type 2402 // then the trait is true, else if type is a cv class or union 2403 // type (or array thereof) with a trivial destructor 2404 // ([class.dtor]) then the trait is true, else it is 2405 // false. 2406 if (T->isPODType() || T->isReferenceType()) 2407 return true; 2408 if (const RecordType *RT = 2409 C.getBaseElementType(T)->getAs<RecordType>()) 2410 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor(); 2411 return false; 2412 // TODO: Propagate nothrowness for implicitly declared special members. 2413 case UTT_HasNothrowAssign: 2414 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 2415 // If type is const qualified or is a reference type then the 2416 // trait is false. Otherwise if __has_trivial_assign (type) 2417 // is true then the trait is true, else if type is a cv class 2418 // or union type with copy assignment operators that are known 2419 // not to throw an exception then the trait is true, else it is 2420 // false. 2421 if (C.getBaseElementType(T).isConstQualified()) 2422 return false; 2423 if (T->isReferenceType()) 2424 return false; 2425 if (T->isPODType()) 2426 return true; 2427 if (const RecordType *RT = T->getAs<RecordType>()) { 2428 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl()); 2429 if (RD->hasTrivialCopyAssignment()) 2430 return true; 2431 2432 bool FoundAssign = false; 2433 bool AllNoThrow = true; 2434 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal); 2435 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc), 2436 Sema::LookupOrdinaryName); 2437 if (Self.LookupQualifiedName(Res, RD)) { 2438 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end(); 2439 Op != OpEnd; ++Op) { 2440 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op); 2441 if (Operator->isCopyAssignmentOperator()) { 2442 FoundAssign = true; 2443 const FunctionProtoType *CPT 2444 = Operator->getType()->getAs<FunctionProtoType>(); 2445 if (!CPT->isNothrow(Self.Context)) { 2446 AllNoThrow = false; 2447 break; 2448 } 2449 } 2450 } 2451 } 2452 2453 return FoundAssign && AllNoThrow; 2454 } 2455 return false; 2456 case UTT_HasNothrowCopy: 2457 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 2458 // If __has_trivial_copy (type) is true then the trait is true, else 2459 // if type is a cv class or union type with copy constructors that are 2460 // known not to throw an exception then the trait is true, else it is 2461 // false. 2462 if (T->isPODType() || T->isReferenceType()) 2463 return true; 2464 if (const RecordType *RT = T->getAs<RecordType>()) { 2465 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 2466 if (RD->hasTrivialCopyConstructor()) 2467 return true; 2468 2469 bool FoundConstructor = false; 2470 bool AllNoThrow = true; 2471 unsigned FoundTQs; 2472 DeclContext::lookup_const_iterator Con, ConEnd; 2473 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD); 2474 Con != ConEnd; ++Con) { 2475 // A template constructor is never a copy constructor. 2476 // FIXME: However, it may actually be selected at the actual overload 2477 // resolution point. 2478 if (isa<FunctionTemplateDecl>(*Con)) 2479 continue; 2480 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con); 2481 if (Constructor->isCopyConstructor(FoundTQs)) { 2482 FoundConstructor = true; 2483 const FunctionProtoType *CPT 2484 = Constructor->getType()->getAs<FunctionProtoType>(); 2485 // FIXME: check whether evaluating default arguments can throw. 2486 // For now, we'll be conservative and assume that they can throw. 2487 if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1) { 2488 AllNoThrow = false; 2489 break; 2490 } 2491 } 2492 } 2493 2494 return FoundConstructor && AllNoThrow; 2495 } 2496 return false; 2497 case UTT_HasNothrowConstructor: 2498 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 2499 // If __has_trivial_constructor (type) is true then the trait is 2500 // true, else if type is a cv class or union type (or array 2501 // thereof) with a default constructor that is known not to 2502 // throw an exception then the trait is true, else it is false. 2503 if (T->isPODType()) 2504 return true; 2505 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) { 2506 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 2507 if (RD->hasTrivialConstructor()) 2508 return true; 2509 2510 DeclContext::lookup_const_iterator Con, ConEnd; 2511 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD); 2512 Con != ConEnd; ++Con) { 2513 // FIXME: In C++0x, a constructor template can be a default constructor. 2514 if (isa<FunctionTemplateDecl>(*Con)) 2515 continue; 2516 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con); 2517 if (Constructor->isDefaultConstructor()) { 2518 const FunctionProtoType *CPT 2519 = Constructor->getType()->getAs<FunctionProtoType>(); 2520 // TODO: check whether evaluating default arguments can throw. 2521 // For now, we'll be conservative and assume that they can throw. 2522 return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0; 2523 } 2524 } 2525 } 2526 return false; 2527 case UTT_HasVirtualDestructor: 2528 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 2529 // If type is a class type with a virtual destructor ([class.dtor]) 2530 // then the trait is true, else it is false. 2531 if (const RecordType *Record = T->getAs<RecordType>()) { 2532 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2533 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD)) 2534 return Destructor->isVirtual(); 2535 } 2536 return false; 2537 } 2538} 2539 2540ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT, 2541 SourceLocation KWLoc, 2542 TypeSourceInfo *TSInfo, 2543 SourceLocation RParen) { 2544 QualType T = TSInfo->getType(); 2545 2546 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html 2547 // all traits except __is_class, __is_enum and __is_union require a the type 2548 // to be complete, an array of unknown bound, or void. 2549 if (UTT != UTT_IsClass && UTT != UTT_IsEnum && UTT != UTT_IsUnion) { 2550 QualType E = T; 2551 if (T->isIncompleteArrayType()) 2552 E = Context.getAsArrayType(T)->getElementType(); 2553 if (!T->isVoidType() && 2554 RequireCompleteType(KWLoc, E, 2555 diag::err_incomplete_type_used_in_type_trait_expr)) 2556 return ExprError(); 2557 } 2558 2559 bool Value = false; 2560 if (!T->isDependentType()) 2561 Value = EvaluateUnaryTypeTrait(*this, UTT, T, KWLoc); 2562 2563 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value, 2564 RParen, Context.BoolTy)); 2565} 2566 2567ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT, 2568 SourceLocation KWLoc, 2569 ParsedType LhsTy, 2570 ParsedType RhsTy, 2571 SourceLocation RParen) { 2572 TypeSourceInfo *LhsTSInfo; 2573 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo); 2574 if (!LhsTSInfo) 2575 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT); 2576 2577 TypeSourceInfo *RhsTSInfo; 2578 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo); 2579 if (!RhsTSInfo) 2580 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT); 2581 2582 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen); 2583} 2584 2585static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT, 2586 QualType LhsT, QualType RhsT, 2587 SourceLocation KeyLoc) { 2588 assert((!LhsT->isDependentType() || RhsT->isDependentType()) && 2589 "Cannot evaluate traits for dependent types."); 2590 2591 switch(BTT) { 2592 case BTT_IsBaseOf: { 2593 // C++0x [meta.rel]p2 2594 // Base is a base class of Derived without regard to cv-qualifiers or 2595 // Base and Derived are not unions and name the same class type without 2596 // regard to cv-qualifiers. 2597 2598 const RecordType *lhsRecord = LhsT->getAs<RecordType>(); 2599 if (!lhsRecord) return false; 2600 2601 const RecordType *rhsRecord = RhsT->getAs<RecordType>(); 2602 if (!rhsRecord) return false; 2603 2604 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT) 2605 == (lhsRecord == rhsRecord)); 2606 2607 if (lhsRecord == rhsRecord) 2608 return !lhsRecord->getDecl()->isUnion(); 2609 2610 // C++0x [meta.rel]p2: 2611 // If Base and Derived are class types and are different types 2612 // (ignoring possible cv-qualifiers) then Derived shall be a 2613 // complete type. 2614 if (Self.RequireCompleteType(KeyLoc, RhsT, 2615 diag::err_incomplete_type_used_in_type_trait_expr)) 2616 return false; 2617 2618 return cast<CXXRecordDecl>(rhsRecord->getDecl()) 2619 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl())); 2620 } 2621 2622 case BTT_TypeCompatible: 2623 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(), 2624 RhsT.getUnqualifiedType()); 2625 2626 case BTT_IsConvertibleTo: { 2627 // C++0x [meta.rel]p4: 2628 // Given the following function prototype: 2629 // 2630 // template <class T> 2631 // typename add_rvalue_reference<T>::type create(); 2632 // 2633 // the predicate condition for a template specialization 2634 // is_convertible<From, To> shall be satisfied if and only if 2635 // the return expression in the following code would be 2636 // well-formed, including any implicit conversions to the return 2637 // type of the function: 2638 // 2639 // To test() { 2640 // return create<From>(); 2641 // } 2642 // 2643 // Access checking is performed as if in a context unrelated to To and 2644 // From. Only the validity of the immediate context of the expression 2645 // of the return-statement (including conversions to the return type) 2646 // is considered. 2647 // 2648 // We model the initialization as a copy-initialization of a temporary 2649 // of the appropriate type, which for this expression is identical to the 2650 // return statement (since NRVO doesn't apply). 2651 if (LhsT->isObjectType() || LhsT->isFunctionType()) 2652 LhsT = Self.Context.getRValueReferenceType(LhsT); 2653 2654 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT)); 2655 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context), 2656 Expr::getValueKindForType(LhsT)); 2657 Expr *FromPtr = &From; 2658 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc, 2659 SourceLocation())); 2660 2661 // Perform the initialization within a SFINAE trap at translation unit 2662 // scope. 2663 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true); 2664 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl()); 2665 InitializationSequence Init(Self, To, Kind, &FromPtr, 1); 2666 if (Init.getKind() == InitializationSequence::FailedSequence) 2667 return false; 2668 2669 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1)); 2670 return !Result.isInvalid() && !SFINAE.hasErrorOccurred(); 2671 } 2672 } 2673 llvm_unreachable("Unknown type trait or not implemented"); 2674} 2675 2676ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT, 2677 SourceLocation KWLoc, 2678 TypeSourceInfo *LhsTSInfo, 2679 TypeSourceInfo *RhsTSInfo, 2680 SourceLocation RParen) { 2681 QualType LhsT = LhsTSInfo->getType(); 2682 QualType RhsT = RhsTSInfo->getType(); 2683 2684 if (BTT == BTT_TypeCompatible) { 2685 if (getLangOptions().CPlusPlus) { 2686 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus) 2687 << SourceRange(KWLoc, RParen); 2688 return ExprError(); 2689 } 2690 } 2691 2692 bool Value = false; 2693 if (!LhsT->isDependentType() && !RhsT->isDependentType()) 2694 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc); 2695 2696 // Select trait result type. 2697 QualType ResultType; 2698 switch (BTT) { 2699 case BTT_IsBaseOf: ResultType = Context.BoolTy; break; 2700 case BTT_TypeCompatible: ResultType = Context.IntTy; break; 2701 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break; 2702 } 2703 2704 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo, 2705 RhsTSInfo, Value, RParen, 2706 ResultType)); 2707} 2708 2709QualType Sema::CheckPointerToMemberOperands(Expr *&lex, Expr *&rex, 2710 ExprValueKind &VK, 2711 SourceLocation Loc, 2712 bool isIndirect) { 2713 const char *OpSpelling = isIndirect ? "->*" : ".*"; 2714 // C++ 5.5p2 2715 // The binary operator .* [p3: ->*] binds its second operand, which shall 2716 // be of type "pointer to member of T" (where T is a completely-defined 2717 // class type) [...] 2718 QualType RType = rex->getType(); 2719 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>(); 2720 if (!MemPtr) { 2721 Diag(Loc, diag::err_bad_memptr_rhs) 2722 << OpSpelling << RType << rex->getSourceRange(); 2723 return QualType(); 2724 } 2725 2726 QualType Class(MemPtr->getClass(), 0); 2727 2728 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the 2729 // member pointer points must be completely-defined. However, there is no 2730 // reason for this semantic distinction, and the rule is not enforced by 2731 // other compilers. Therefore, we do not check this property, as it is 2732 // likely to be considered a defect. 2733 2734 // C++ 5.5p2 2735 // [...] to its first operand, which shall be of class T or of a class of 2736 // which T is an unambiguous and accessible base class. [p3: a pointer to 2737 // such a class] 2738 QualType LType = lex->getType(); 2739 if (isIndirect) { 2740 if (const PointerType *Ptr = LType->getAs<PointerType>()) 2741 LType = Ptr->getPointeeType(); 2742 else { 2743 Diag(Loc, diag::err_bad_memptr_lhs) 2744 << OpSpelling << 1 << LType 2745 << FixItHint::CreateReplacement(SourceRange(Loc), ".*"); 2746 return QualType(); 2747 } 2748 } 2749 2750 if (!Context.hasSameUnqualifiedType(Class, LType)) { 2751 // If we want to check the hierarchy, we need a complete type. 2752 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs) 2753 << OpSpelling << (int)isIndirect)) { 2754 return QualType(); 2755 } 2756 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2757 /*DetectVirtual=*/false); 2758 // FIXME: Would it be useful to print full ambiguity paths, or is that 2759 // overkill? 2760 if (!IsDerivedFrom(LType, Class, Paths) || 2761 Paths.isAmbiguous(Context.getCanonicalType(Class))) { 2762 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling 2763 << (int)isIndirect << lex->getType(); 2764 return QualType(); 2765 } 2766 // Cast LHS to type of use. 2767 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class; 2768 ExprValueKind VK = 2769 isIndirect ? VK_RValue : CastCategory(lex); 2770 2771 CXXCastPath BasePath; 2772 BuildBasePathArray(Paths, BasePath); 2773 ImpCastExprToType(lex, UseType, CK_DerivedToBase, VK, &BasePath); 2774 } 2775 2776 if (isa<CXXScalarValueInitExpr>(rex->IgnoreParens())) { 2777 // Diagnose use of pointer-to-member type which when used as 2778 // the functional cast in a pointer-to-member expression. 2779 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect; 2780 return QualType(); 2781 } 2782 2783 // C++ 5.5p2 2784 // The result is an object or a function of the type specified by the 2785 // second operand. 2786 // The cv qualifiers are the union of those in the pointer and the left side, 2787 // in accordance with 5.5p5 and 5.2.5. 2788 // FIXME: This returns a dereferenced member function pointer as a normal 2789 // function type. However, the only operation valid on such functions is 2790 // calling them. There's also a GCC extension to get a function pointer to the 2791 // thing, which is another complication, because this type - unlike the type 2792 // that is the result of this expression - takes the class as the first 2793 // argument. 2794 // We probably need a "MemberFunctionClosureType" or something like that. 2795 QualType Result = MemPtr->getPointeeType(); 2796 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers()); 2797 2798 // C++0x [expr.mptr.oper]p6: 2799 // In a .* expression whose object expression is an rvalue, the program is 2800 // ill-formed if the second operand is a pointer to member function with 2801 // ref-qualifier &. In a ->* expression or in a .* expression whose object 2802 // expression is an lvalue, the program is ill-formed if the second operand 2803 // is a pointer to member function with ref-qualifier &&. 2804 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) { 2805 switch (Proto->getRefQualifier()) { 2806 case RQ_None: 2807 // Do nothing 2808 break; 2809 2810 case RQ_LValue: 2811 if (!isIndirect && !lex->Classify(Context).isLValue()) 2812 Diag(Loc, diag::err_pointer_to_member_oper_value_classify) 2813 << RType << 1 << lex->getSourceRange(); 2814 break; 2815 2816 case RQ_RValue: 2817 if (isIndirect || !lex->Classify(Context).isRValue()) 2818 Diag(Loc, diag::err_pointer_to_member_oper_value_classify) 2819 << RType << 0 << lex->getSourceRange(); 2820 break; 2821 } 2822 } 2823 2824 // C++ [expr.mptr.oper]p6: 2825 // The result of a .* expression whose second operand is a pointer 2826 // to a data member is of the same value category as its 2827 // first operand. The result of a .* expression whose second 2828 // operand is a pointer to a member function is a prvalue. The 2829 // result of an ->* expression is an lvalue if its second operand 2830 // is a pointer to data member and a prvalue otherwise. 2831 if (Result->isFunctionType()) 2832 VK = VK_RValue; 2833 else if (isIndirect) 2834 VK = VK_LValue; 2835 else 2836 VK = lex->getValueKind(); 2837 2838 return Result; 2839} 2840 2841/// \brief Try to convert a type to another according to C++0x 5.16p3. 2842/// 2843/// This is part of the parameter validation for the ? operator. If either 2844/// value operand is a class type, the two operands are attempted to be 2845/// converted to each other. This function does the conversion in one direction. 2846/// It returns true if the program is ill-formed and has already been diagnosed 2847/// as such. 2848static bool TryClassUnification(Sema &Self, Expr *From, Expr *To, 2849 SourceLocation QuestionLoc, 2850 bool &HaveConversion, 2851 QualType &ToType) { 2852 HaveConversion = false; 2853 ToType = To->getType(); 2854 2855 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(), 2856 SourceLocation()); 2857 // C++0x 5.16p3 2858 // The process for determining whether an operand expression E1 of type T1 2859 // can be converted to match an operand expression E2 of type T2 is defined 2860 // as follows: 2861 // -- If E2 is an lvalue: 2862 bool ToIsLvalue = To->isLValue(); 2863 if (ToIsLvalue) { 2864 // E1 can be converted to match E2 if E1 can be implicitly converted to 2865 // type "lvalue reference to T2", subject to the constraint that in the 2866 // conversion the reference must bind directly to E1. 2867 QualType T = Self.Context.getLValueReferenceType(ToType); 2868 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); 2869 2870 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1); 2871 if (InitSeq.isDirectReferenceBinding()) { 2872 ToType = T; 2873 HaveConversion = true; 2874 return false; 2875 } 2876 2877 if (InitSeq.isAmbiguous()) 2878 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1); 2879 } 2880 2881 // -- If E2 is an rvalue, or if the conversion above cannot be done: 2882 // -- if E1 and E2 have class type, and the underlying class types are 2883 // the same or one is a base class of the other: 2884 QualType FTy = From->getType(); 2885 QualType TTy = To->getType(); 2886 const RecordType *FRec = FTy->getAs<RecordType>(); 2887 const RecordType *TRec = TTy->getAs<RecordType>(); 2888 bool FDerivedFromT = FRec && TRec && FRec != TRec && 2889 Self.IsDerivedFrom(FTy, TTy); 2890 if (FRec && TRec && 2891 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) { 2892 // E1 can be converted to match E2 if the class of T2 is the 2893 // same type as, or a base class of, the class of T1, and 2894 // [cv2 > cv1]. 2895 if (FRec == TRec || FDerivedFromT) { 2896 if (TTy.isAtLeastAsQualifiedAs(FTy)) { 2897 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); 2898 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1); 2899 if (InitSeq.getKind() != InitializationSequence::FailedSequence) { 2900 HaveConversion = true; 2901 return false; 2902 } 2903 2904 if (InitSeq.isAmbiguous()) 2905 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1); 2906 } 2907 } 2908 2909 return false; 2910 } 2911 2912 // -- Otherwise: E1 can be converted to match E2 if E1 can be 2913 // implicitly converted to the type that expression E2 would have 2914 // if E2 were converted to an rvalue (or the type it has, if E2 is 2915 // an rvalue). 2916 // 2917 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not 2918 // to the array-to-pointer or function-to-pointer conversions. 2919 if (!TTy->getAs<TagType>()) 2920 TTy = TTy.getUnqualifiedType(); 2921 2922 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); 2923 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1); 2924 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence; 2925 ToType = TTy; 2926 if (InitSeq.isAmbiguous()) 2927 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1); 2928 2929 return false; 2930} 2931 2932/// \brief Try to find a common type for two according to C++0x 5.16p5. 2933/// 2934/// This is part of the parameter validation for the ? operator. If either 2935/// value operand is a class type, overload resolution is used to find a 2936/// conversion to a common type. 2937static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS, 2938 SourceLocation QuestionLoc) { 2939 Expr *Args[2] = { LHS, RHS }; 2940 OverloadCandidateSet CandidateSet(QuestionLoc); 2941 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2, 2942 CandidateSet); 2943 2944 OverloadCandidateSet::iterator Best; 2945 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) { 2946 case OR_Success: 2947 // We found a match. Perform the conversions on the arguments and move on. 2948 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0], 2949 Best->Conversions[0], Sema::AA_Converting) || 2950 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1], 2951 Best->Conversions[1], Sema::AA_Converting)) 2952 break; 2953 if (Best->Function) 2954 Self.MarkDeclarationReferenced(QuestionLoc, Best->Function); 2955 return false; 2956 2957 case OR_No_Viable_Function: 2958 2959 // Emit a better diagnostic if one of the expressions is a null pointer 2960 // constant and the other is a pointer type. In this case, the user most 2961 // likely forgot to take the address of the other expression. 2962 if (Self.DiagnoseConditionalForNull(LHS, RHS, QuestionLoc)) 2963 return true; 2964 2965 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 2966 << LHS->getType() << RHS->getType() 2967 << LHS->getSourceRange() << RHS->getSourceRange(); 2968 return true; 2969 2970 case OR_Ambiguous: 2971 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl) 2972 << LHS->getType() << RHS->getType() 2973 << LHS->getSourceRange() << RHS->getSourceRange(); 2974 // FIXME: Print the possible common types by printing the return types of 2975 // the viable candidates. 2976 break; 2977 2978 case OR_Deleted: 2979 assert(false && "Conditional operator has only built-in overloads"); 2980 break; 2981 } 2982 return true; 2983} 2984 2985/// \brief Perform an "extended" implicit conversion as returned by 2986/// TryClassUnification. 2987static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) { 2988 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); 2989 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(), 2990 SourceLocation()); 2991 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1); 2992 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&E, 1)); 2993 if (Result.isInvalid()) 2994 return true; 2995 2996 E = Result.takeAs<Expr>(); 2997 return false; 2998} 2999 3000/// \brief Check the operands of ?: under C++ semantics. 3001/// 3002/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y 3003/// extension. In this case, LHS == Cond. (But they're not aliases.) 3004QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS, 3005 ExprValueKind &VK, ExprObjectKind &OK, 3006 SourceLocation QuestionLoc) { 3007 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++ 3008 // interface pointers. 3009 3010 // C++0x 5.16p1 3011 // The first expression is contextually converted to bool. 3012 if (!Cond->isTypeDependent()) { 3013 if (CheckCXXBooleanCondition(Cond)) 3014 return QualType(); 3015 } 3016 3017 // Assume r-value. 3018 VK = VK_RValue; 3019 OK = OK_Ordinary; 3020 3021 // Either of the arguments dependent? 3022 if (LHS->isTypeDependent() || RHS->isTypeDependent()) 3023 return Context.DependentTy; 3024 3025 // C++0x 5.16p2 3026 // If either the second or the third operand has type (cv) void, ... 3027 QualType LTy = LHS->getType(); 3028 QualType RTy = RHS->getType(); 3029 bool LVoid = LTy->isVoidType(); 3030 bool RVoid = RTy->isVoidType(); 3031 if (LVoid || RVoid) { 3032 // ... then the [l2r] conversions are performed on the second and third 3033 // operands ... 3034 DefaultFunctionArrayLvalueConversion(LHS); 3035 DefaultFunctionArrayLvalueConversion(RHS); 3036 LTy = LHS->getType(); 3037 RTy = RHS->getType(); 3038 3039 // ... and one of the following shall hold: 3040 // -- The second or the third operand (but not both) is a throw- 3041 // expression; the result is of the type of the other and is an rvalue. 3042 bool LThrow = isa<CXXThrowExpr>(LHS); 3043 bool RThrow = isa<CXXThrowExpr>(RHS); 3044 if (LThrow && !RThrow) 3045 return RTy; 3046 if (RThrow && !LThrow) 3047 return LTy; 3048 3049 // -- Both the second and third operands have type void; the result is of 3050 // type void and is an rvalue. 3051 if (LVoid && RVoid) 3052 return Context.VoidTy; 3053 3054 // Neither holds, error. 3055 Diag(QuestionLoc, diag::err_conditional_void_nonvoid) 3056 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1) 3057 << LHS->getSourceRange() << RHS->getSourceRange(); 3058 return QualType(); 3059 } 3060 3061 // Neither is void. 3062 3063 // C++0x 5.16p3 3064 // Otherwise, if the second and third operand have different types, and 3065 // either has (cv) class type, and attempt is made to convert each of those 3066 // operands to the other. 3067 if (!Context.hasSameType(LTy, RTy) && 3068 (LTy->isRecordType() || RTy->isRecordType())) { 3069 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft; 3070 // These return true if a single direction is already ambiguous. 3071 QualType L2RType, R2LType; 3072 bool HaveL2R, HaveR2L; 3073 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType)) 3074 return QualType(); 3075 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType)) 3076 return QualType(); 3077 3078 // If both can be converted, [...] the program is ill-formed. 3079 if (HaveL2R && HaveR2L) { 3080 Diag(QuestionLoc, diag::err_conditional_ambiguous) 3081 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange(); 3082 return QualType(); 3083 } 3084 3085 // If exactly one conversion is possible, that conversion is applied to 3086 // the chosen operand and the converted operands are used in place of the 3087 // original operands for the remainder of this section. 3088 if (HaveL2R) { 3089 if (ConvertForConditional(*this, LHS, L2RType)) 3090 return QualType(); 3091 LTy = LHS->getType(); 3092 } else if (HaveR2L) { 3093 if (ConvertForConditional(*this, RHS, R2LType)) 3094 return QualType(); 3095 RTy = RHS->getType(); 3096 } 3097 } 3098 3099 // C++0x 5.16p4 3100 // If the second and third operands are glvalues of the same value 3101 // category and have the same type, the result is of that type and 3102 // value category and it is a bit-field if the second or the third 3103 // operand is a bit-field, or if both are bit-fields. 3104 // We only extend this to bitfields, not to the crazy other kinds of 3105 // l-values. 3106 bool Same = Context.hasSameType(LTy, RTy); 3107 if (Same && 3108 LHS->isGLValue() && 3109 LHS->getValueKind() == RHS->getValueKind() && 3110 LHS->isOrdinaryOrBitFieldObject() && 3111 RHS->isOrdinaryOrBitFieldObject()) { 3112 VK = LHS->getValueKind(); 3113 if (LHS->getObjectKind() == OK_BitField || 3114 RHS->getObjectKind() == OK_BitField) 3115 OK = OK_BitField; 3116 return LTy; 3117 } 3118 3119 // C++0x 5.16p5 3120 // Otherwise, the result is an rvalue. If the second and third operands 3121 // do not have the same type, and either has (cv) class type, ... 3122 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) { 3123 // ... overload resolution is used to determine the conversions (if any) 3124 // to be applied to the operands. If the overload resolution fails, the 3125 // program is ill-formed. 3126 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc)) 3127 return QualType(); 3128 } 3129 3130 // C++0x 5.16p6 3131 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard 3132 // conversions are performed on the second and third operands. 3133 DefaultFunctionArrayLvalueConversion(LHS); 3134 DefaultFunctionArrayLvalueConversion(RHS); 3135 LTy = LHS->getType(); 3136 RTy = RHS->getType(); 3137 3138 // After those conversions, one of the following shall hold: 3139 // -- The second and third operands have the same type; the result 3140 // is of that type. If the operands have class type, the result 3141 // is a prvalue temporary of the result type, which is 3142 // copy-initialized from either the second operand or the third 3143 // operand depending on the value of the first operand. 3144 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) { 3145 if (LTy->isRecordType()) { 3146 // The operands have class type. Make a temporary copy. 3147 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy); 3148 ExprResult LHSCopy = PerformCopyInitialization(Entity, 3149 SourceLocation(), 3150 Owned(LHS)); 3151 if (LHSCopy.isInvalid()) 3152 return QualType(); 3153 3154 ExprResult RHSCopy = PerformCopyInitialization(Entity, 3155 SourceLocation(), 3156 Owned(RHS)); 3157 if (RHSCopy.isInvalid()) 3158 return QualType(); 3159 3160 LHS = LHSCopy.takeAs<Expr>(); 3161 RHS = RHSCopy.takeAs<Expr>(); 3162 } 3163 3164 return LTy; 3165 } 3166 3167 // Extension: conditional operator involving vector types. 3168 if (LTy->isVectorType() || RTy->isVectorType()) 3169 return CheckVectorOperands(QuestionLoc, LHS, RHS); 3170 3171 // -- The second and third operands have arithmetic or enumeration type; 3172 // the usual arithmetic conversions are performed to bring them to a 3173 // common type, and the result is of that type. 3174 if (LTy->isArithmeticType() && RTy->isArithmeticType()) { 3175 UsualArithmeticConversions(LHS, RHS); 3176 return LHS->getType(); 3177 } 3178 3179 // -- The second and third operands have pointer type, or one has pointer 3180 // type and the other is a null pointer constant; pointer conversions 3181 // and qualification conversions are performed to bring them to their 3182 // composite pointer type. The result is of the composite pointer type. 3183 // -- The second and third operands have pointer to member type, or one has 3184 // pointer to member type and the other is a null pointer constant; 3185 // pointer to member conversions and qualification conversions are 3186 // performed to bring them to a common type, whose cv-qualification 3187 // shall match the cv-qualification of either the second or the third 3188 // operand. The result is of the common type. 3189 bool NonStandardCompositeType = false; 3190 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS, 3191 isSFINAEContext()? 0 : &NonStandardCompositeType); 3192 if (!Composite.isNull()) { 3193 if (NonStandardCompositeType) 3194 Diag(QuestionLoc, 3195 diag::ext_typecheck_cond_incompatible_operands_nonstandard) 3196 << LTy << RTy << Composite 3197 << LHS->getSourceRange() << RHS->getSourceRange(); 3198 3199 return Composite; 3200 } 3201 3202 // Similarly, attempt to find composite type of two objective-c pointers. 3203 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc); 3204 if (!Composite.isNull()) 3205 return Composite; 3206 3207 // Check if we are using a null with a non-pointer type. 3208 if (DiagnoseConditionalForNull(LHS, RHS, QuestionLoc)) 3209 return QualType(); 3210 3211 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 3212 << LHS->getType() << RHS->getType() 3213 << LHS->getSourceRange() << RHS->getSourceRange(); 3214 return QualType(); 3215} 3216 3217/// \brief Find a merged pointer type and convert the two expressions to it. 3218/// 3219/// This finds the composite pointer type (or member pointer type) for @p E1 3220/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this 3221/// type and returns it. 3222/// It does not emit diagnostics. 3223/// 3224/// \param Loc The location of the operator requiring these two expressions to 3225/// be converted to the composite pointer type. 3226/// 3227/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find 3228/// a non-standard (but still sane) composite type to which both expressions 3229/// can be converted. When such a type is chosen, \c *NonStandardCompositeType 3230/// will be set true. 3231QualType Sema::FindCompositePointerType(SourceLocation Loc, 3232 Expr *&E1, Expr *&E2, 3233 bool *NonStandardCompositeType) { 3234 if (NonStandardCompositeType) 3235 *NonStandardCompositeType = false; 3236 3237 assert(getLangOptions().CPlusPlus && "This function assumes C++"); 3238 QualType T1 = E1->getType(), T2 = E2->getType(); 3239 3240 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() && 3241 !T2->isAnyPointerType() && !T2->isMemberPointerType()) 3242 return QualType(); 3243 3244 // C++0x 5.9p2 3245 // Pointer conversions and qualification conversions are performed on 3246 // pointer operands to bring them to their composite pointer type. If 3247 // one operand is a null pointer constant, the composite pointer type is 3248 // the type of the other operand. 3249 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 3250 if (T2->isMemberPointerType()) 3251 ImpCastExprToType(E1, T2, CK_NullToMemberPointer); 3252 else 3253 ImpCastExprToType(E1, T2, CK_NullToPointer); 3254 return T2; 3255 } 3256 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 3257 if (T1->isMemberPointerType()) 3258 ImpCastExprToType(E2, T1, CK_NullToMemberPointer); 3259 else 3260 ImpCastExprToType(E2, T1, CK_NullToPointer); 3261 return T1; 3262 } 3263 3264 // Now both have to be pointers or member pointers. 3265 if ((!T1->isPointerType() && !T1->isMemberPointerType()) || 3266 (!T2->isPointerType() && !T2->isMemberPointerType())) 3267 return QualType(); 3268 3269 // Otherwise, of one of the operands has type "pointer to cv1 void," then 3270 // the other has type "pointer to cv2 T" and the composite pointer type is 3271 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2. 3272 // Otherwise, the composite pointer type is a pointer type similar to the 3273 // type of one of the operands, with a cv-qualification signature that is 3274 // the union of the cv-qualification signatures of the operand types. 3275 // In practice, the first part here is redundant; it's subsumed by the second. 3276 // What we do here is, we build the two possible composite types, and try the 3277 // conversions in both directions. If only one works, or if the two composite 3278 // types are the same, we have succeeded. 3279 // FIXME: extended qualifiers? 3280 typedef llvm::SmallVector<unsigned, 4> QualifierVector; 3281 QualifierVector QualifierUnion; 3282 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4> 3283 ContainingClassVector; 3284 ContainingClassVector MemberOfClass; 3285 QualType Composite1 = Context.getCanonicalType(T1), 3286 Composite2 = Context.getCanonicalType(T2); 3287 unsigned NeedConstBefore = 0; 3288 do { 3289 const PointerType *Ptr1, *Ptr2; 3290 if ((Ptr1 = Composite1->getAs<PointerType>()) && 3291 (Ptr2 = Composite2->getAs<PointerType>())) { 3292 Composite1 = Ptr1->getPointeeType(); 3293 Composite2 = Ptr2->getPointeeType(); 3294 3295 // If we're allowed to create a non-standard composite type, keep track 3296 // of where we need to fill in additional 'const' qualifiers. 3297 if (NonStandardCompositeType && 3298 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers()) 3299 NeedConstBefore = QualifierUnion.size(); 3300 3301 QualifierUnion.push_back( 3302 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); 3303 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0)); 3304 continue; 3305 } 3306 3307 const MemberPointerType *MemPtr1, *MemPtr2; 3308 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) && 3309 (MemPtr2 = Composite2->getAs<MemberPointerType>())) { 3310 Composite1 = MemPtr1->getPointeeType(); 3311 Composite2 = MemPtr2->getPointeeType(); 3312 3313 // If we're allowed to create a non-standard composite type, keep track 3314 // of where we need to fill in additional 'const' qualifiers. 3315 if (NonStandardCompositeType && 3316 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers()) 3317 NeedConstBefore = QualifierUnion.size(); 3318 3319 QualifierUnion.push_back( 3320 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); 3321 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(), 3322 MemPtr2->getClass())); 3323 continue; 3324 } 3325 3326 // FIXME: block pointer types? 3327 3328 // Cannot unwrap any more types. 3329 break; 3330 } while (true); 3331 3332 if (NeedConstBefore && NonStandardCompositeType) { 3333 // Extension: Add 'const' to qualifiers that come before the first qualifier 3334 // mismatch, so that our (non-standard!) composite type meets the 3335 // requirements of C++ [conv.qual]p4 bullet 3. 3336 for (unsigned I = 0; I != NeedConstBefore; ++I) { 3337 if ((QualifierUnion[I] & Qualifiers::Const) == 0) { 3338 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const; 3339 *NonStandardCompositeType = true; 3340 } 3341 } 3342 } 3343 3344 // Rewrap the composites as pointers or member pointers with the union CVRs. 3345 ContainingClassVector::reverse_iterator MOC 3346 = MemberOfClass.rbegin(); 3347 for (QualifierVector::reverse_iterator 3348 I = QualifierUnion.rbegin(), 3349 E = QualifierUnion.rend(); 3350 I != E; (void)++I, ++MOC) { 3351 Qualifiers Quals = Qualifiers::fromCVRMask(*I); 3352 if (MOC->first && MOC->second) { 3353 // Rebuild member pointer type 3354 Composite1 = Context.getMemberPointerType( 3355 Context.getQualifiedType(Composite1, Quals), 3356 MOC->first); 3357 Composite2 = Context.getMemberPointerType( 3358 Context.getQualifiedType(Composite2, Quals), 3359 MOC->second); 3360 } else { 3361 // Rebuild pointer type 3362 Composite1 3363 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals)); 3364 Composite2 3365 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals)); 3366 } 3367 } 3368 3369 // Try to convert to the first composite pointer type. 3370 InitializedEntity Entity1 3371 = InitializedEntity::InitializeTemporary(Composite1); 3372 InitializationKind Kind 3373 = InitializationKind::CreateCopy(Loc, SourceLocation()); 3374 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1); 3375 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1); 3376 3377 if (E1ToC1 && E2ToC1) { 3378 // Conversion to Composite1 is viable. 3379 if (!Context.hasSameType(Composite1, Composite2)) { 3380 // Composite2 is a different type from Composite1. Check whether 3381 // Composite2 is also viable. 3382 InitializedEntity Entity2 3383 = InitializedEntity::InitializeTemporary(Composite2); 3384 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1); 3385 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1); 3386 if (E1ToC2 && E2ToC2) { 3387 // Both Composite1 and Composite2 are viable and are different; 3388 // this is an ambiguity. 3389 return QualType(); 3390 } 3391 } 3392 3393 // Convert E1 to Composite1 3394 ExprResult E1Result 3395 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1)); 3396 if (E1Result.isInvalid()) 3397 return QualType(); 3398 E1 = E1Result.takeAs<Expr>(); 3399 3400 // Convert E2 to Composite1 3401 ExprResult E2Result 3402 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1)); 3403 if (E2Result.isInvalid()) 3404 return QualType(); 3405 E2 = E2Result.takeAs<Expr>(); 3406 3407 return Composite1; 3408 } 3409 3410 // Check whether Composite2 is viable. 3411 InitializedEntity Entity2 3412 = InitializedEntity::InitializeTemporary(Composite2); 3413 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1); 3414 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1); 3415 if (!E1ToC2 || !E2ToC2) 3416 return QualType(); 3417 3418 // Convert E1 to Composite2 3419 ExprResult E1Result 3420 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1)); 3421 if (E1Result.isInvalid()) 3422 return QualType(); 3423 E1 = E1Result.takeAs<Expr>(); 3424 3425 // Convert E2 to Composite2 3426 ExprResult E2Result 3427 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1)); 3428 if (E2Result.isInvalid()) 3429 return QualType(); 3430 E2 = E2Result.takeAs<Expr>(); 3431 3432 return Composite2; 3433} 3434 3435ExprResult Sema::MaybeBindToTemporary(Expr *E) { 3436 if (!E) 3437 return ExprError(); 3438 3439 if (!Context.getLangOptions().CPlusPlus) 3440 return Owned(E); 3441 3442 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?"); 3443 3444 const RecordType *RT = E->getType()->getAs<RecordType>(); 3445 if (!RT) 3446 return Owned(E); 3447 3448 // If the result is a glvalue, we shouldn't bind it. 3449 if (E->Classify(Context).isGLValue()) 3450 return Owned(E); 3451 3452 // That should be enough to guarantee that this type is complete. 3453 // If it has a trivial destructor, we can avoid the extra copy. 3454 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 3455 if (RD->isInvalidDecl() || RD->hasTrivialDestructor()) 3456 return Owned(E); 3457 3458 CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD)); 3459 ExprTemporaries.push_back(Temp); 3460 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 3461 MarkDeclarationReferenced(E->getExprLoc(), Destructor); 3462 CheckDestructorAccess(E->getExprLoc(), Destructor, 3463 PDiag(diag::err_access_dtor_temp) 3464 << E->getType()); 3465 } 3466 // FIXME: Add the temporary to the temporaries vector. 3467 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E)); 3468} 3469 3470Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) { 3471 assert(SubExpr && "sub expression can't be null!"); 3472 3473 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries; 3474 assert(ExprTemporaries.size() >= FirstTemporary); 3475 if (ExprTemporaries.size() == FirstTemporary) 3476 return SubExpr; 3477 3478 Expr *E = ExprWithCleanups::Create(Context, SubExpr, 3479 &ExprTemporaries[FirstTemporary], 3480 ExprTemporaries.size() - FirstTemporary); 3481 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary, 3482 ExprTemporaries.end()); 3483 3484 return E; 3485} 3486 3487ExprResult 3488Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) { 3489 if (SubExpr.isInvalid()) 3490 return ExprError(); 3491 3492 return Owned(MaybeCreateExprWithCleanups(SubExpr.take())); 3493} 3494 3495Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) { 3496 assert(SubStmt && "sub statement can't be null!"); 3497 3498 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries; 3499 assert(ExprTemporaries.size() >= FirstTemporary); 3500 if (ExprTemporaries.size() == FirstTemporary) 3501 return SubStmt; 3502 3503 // FIXME: In order to attach the temporaries, wrap the statement into 3504 // a StmtExpr; currently this is only used for asm statements. 3505 // This is hacky, either create a new CXXStmtWithTemporaries statement or 3506 // a new AsmStmtWithTemporaries. 3507 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1, 3508 SourceLocation(), 3509 SourceLocation()); 3510 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(), 3511 SourceLocation()); 3512 return MaybeCreateExprWithCleanups(E); 3513} 3514 3515ExprResult 3516Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc, 3517 tok::TokenKind OpKind, ParsedType &ObjectType, 3518 bool &MayBePseudoDestructor) { 3519 // Since this might be a postfix expression, get rid of ParenListExprs. 3520 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base); 3521 if (Result.isInvalid()) return ExprError(); 3522 Base = Result.get(); 3523 3524 QualType BaseType = Base->getType(); 3525 MayBePseudoDestructor = false; 3526 if (BaseType->isDependentType()) { 3527 // If we have a pointer to a dependent type and are using the -> operator, 3528 // the object type is the type that the pointer points to. We might still 3529 // have enough information about that type to do something useful. 3530 if (OpKind == tok::arrow) 3531 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) 3532 BaseType = Ptr->getPointeeType(); 3533 3534 ObjectType = ParsedType::make(BaseType); 3535 MayBePseudoDestructor = true; 3536 return Owned(Base); 3537 } 3538 3539 // C++ [over.match.oper]p8: 3540 // [...] When operator->returns, the operator-> is applied to the value 3541 // returned, with the original second operand. 3542 if (OpKind == tok::arrow) { 3543 // The set of types we've considered so far. 3544 llvm::SmallPtrSet<CanQualType,8> CTypes; 3545 llvm::SmallVector<SourceLocation, 8> Locations; 3546 CTypes.insert(Context.getCanonicalType(BaseType)); 3547 3548 while (BaseType->isRecordType()) { 3549 Result = BuildOverloadedArrowExpr(S, Base, OpLoc); 3550 if (Result.isInvalid()) 3551 return ExprError(); 3552 Base = Result.get(); 3553 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base)) 3554 Locations.push_back(OpCall->getDirectCallee()->getLocation()); 3555 BaseType = Base->getType(); 3556 CanQualType CBaseType = Context.getCanonicalType(BaseType); 3557 if (!CTypes.insert(CBaseType)) { 3558 Diag(OpLoc, diag::err_operator_arrow_circular); 3559 for (unsigned i = 0; i < Locations.size(); i++) 3560 Diag(Locations[i], diag::note_declared_at); 3561 return ExprError(); 3562 } 3563 } 3564 3565 if (BaseType->isPointerType()) 3566 BaseType = BaseType->getPointeeType(); 3567 } 3568 3569 // We could end up with various non-record types here, such as extended 3570 // vector types or Objective-C interfaces. Just return early and let 3571 // ActOnMemberReferenceExpr do the work. 3572 if (!BaseType->isRecordType()) { 3573 // C++ [basic.lookup.classref]p2: 3574 // [...] If the type of the object expression is of pointer to scalar 3575 // type, the unqualified-id is looked up in the context of the complete 3576 // postfix-expression. 3577 // 3578 // This also indicates that we should be parsing a 3579 // pseudo-destructor-name. 3580 ObjectType = ParsedType(); 3581 MayBePseudoDestructor = true; 3582 return Owned(Base); 3583 } 3584 3585 // The object type must be complete (or dependent). 3586 if (!BaseType->isDependentType() && 3587 RequireCompleteType(OpLoc, BaseType, 3588 PDiag(diag::err_incomplete_member_access))) 3589 return ExprError(); 3590 3591 // C++ [basic.lookup.classref]p2: 3592 // If the id-expression in a class member access (5.2.5) is an 3593 // unqualified-id, and the type of the object expression is of a class 3594 // type C (or of pointer to a class type C), the unqualified-id is looked 3595 // up in the scope of class C. [...] 3596 ObjectType = ParsedType::make(BaseType); 3597 return move(Base); 3598} 3599 3600ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc, 3601 Expr *MemExpr) { 3602 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc); 3603 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call) 3604 << isa<CXXPseudoDestructorExpr>(MemExpr) 3605 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()"); 3606 3607 return ActOnCallExpr(/*Scope*/ 0, 3608 MemExpr, 3609 /*LPLoc*/ ExpectedLParenLoc, 3610 MultiExprArg(), 3611 /*RPLoc*/ ExpectedLParenLoc); 3612} 3613 3614ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base, 3615 SourceLocation OpLoc, 3616 tok::TokenKind OpKind, 3617 const CXXScopeSpec &SS, 3618 TypeSourceInfo *ScopeTypeInfo, 3619 SourceLocation CCLoc, 3620 SourceLocation TildeLoc, 3621 PseudoDestructorTypeStorage Destructed, 3622 bool HasTrailingLParen) { 3623 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo(); 3624 3625 // C++ [expr.pseudo]p2: 3626 // The left-hand side of the dot operator shall be of scalar type. The 3627 // left-hand side of the arrow operator shall be of pointer to scalar type. 3628 // This scalar type is the object type. 3629 QualType ObjectType = Base->getType(); 3630 if (OpKind == tok::arrow) { 3631 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) { 3632 ObjectType = Ptr->getPointeeType(); 3633 } else if (!Base->isTypeDependent()) { 3634 // The user wrote "p->" when she probably meant "p."; fix it. 3635 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 3636 << ObjectType << true 3637 << FixItHint::CreateReplacement(OpLoc, "."); 3638 if (isSFINAEContext()) 3639 return ExprError(); 3640 3641 OpKind = tok::period; 3642 } 3643 } 3644 3645 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) { 3646 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar) 3647 << ObjectType << Base->getSourceRange(); 3648 return ExprError(); 3649 } 3650 3651 // C++ [expr.pseudo]p2: 3652 // [...] The cv-unqualified versions of the object type and of the type 3653 // designated by the pseudo-destructor-name shall be the same type. 3654 if (DestructedTypeInfo) { 3655 QualType DestructedType = DestructedTypeInfo->getType(); 3656 SourceLocation DestructedTypeStart 3657 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(); 3658 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() && 3659 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) { 3660 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch) 3661 << ObjectType << DestructedType << Base->getSourceRange() 3662 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange(); 3663 3664 // Recover by setting the destructed type to the object type. 3665 DestructedType = ObjectType; 3666 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType, 3667 DestructedTypeStart); 3668 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 3669 } 3670 } 3671 3672 // C++ [expr.pseudo]p2: 3673 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the 3674 // form 3675 // 3676 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name 3677 // 3678 // shall designate the same scalar type. 3679 if (ScopeTypeInfo) { 3680 QualType ScopeType = ScopeTypeInfo->getType(); 3681 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() && 3682 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) { 3683 3684 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(), 3685 diag::err_pseudo_dtor_type_mismatch) 3686 << ObjectType << ScopeType << Base->getSourceRange() 3687 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange(); 3688 3689 ScopeType = QualType(); 3690 ScopeTypeInfo = 0; 3691 } 3692 } 3693 3694 Expr *Result 3695 = new (Context) CXXPseudoDestructorExpr(Context, Base, 3696 OpKind == tok::arrow, OpLoc, 3697 SS.getWithLocInContext(Context), 3698 ScopeTypeInfo, 3699 CCLoc, 3700 TildeLoc, 3701 Destructed); 3702 3703 if (HasTrailingLParen) 3704 return Owned(Result); 3705 3706 return DiagnoseDtorReference(Destructed.getLocation(), Result); 3707} 3708 3709ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 3710 SourceLocation OpLoc, 3711 tok::TokenKind OpKind, 3712 CXXScopeSpec &SS, 3713 UnqualifiedId &FirstTypeName, 3714 SourceLocation CCLoc, 3715 SourceLocation TildeLoc, 3716 UnqualifiedId &SecondTypeName, 3717 bool HasTrailingLParen) { 3718 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId || 3719 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) && 3720 "Invalid first type name in pseudo-destructor"); 3721 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId || 3722 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) && 3723 "Invalid second type name in pseudo-destructor"); 3724 3725 // C++ [expr.pseudo]p2: 3726 // The left-hand side of the dot operator shall be of scalar type. The 3727 // left-hand side of the arrow operator shall be of pointer to scalar type. 3728 // This scalar type is the object type. 3729 QualType ObjectType = Base->getType(); 3730 if (OpKind == tok::arrow) { 3731 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) { 3732 ObjectType = Ptr->getPointeeType(); 3733 } else if (!ObjectType->isDependentType()) { 3734 // The user wrote "p->" when she probably meant "p."; fix it. 3735 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 3736 << ObjectType << true 3737 << FixItHint::CreateReplacement(OpLoc, "."); 3738 if (isSFINAEContext()) 3739 return ExprError(); 3740 3741 OpKind = tok::period; 3742 } 3743 } 3744 3745 // Compute the object type that we should use for name lookup purposes. Only 3746 // record types and dependent types matter. 3747 ParsedType ObjectTypePtrForLookup; 3748 if (!SS.isSet()) { 3749 if (ObjectType->isRecordType()) 3750 ObjectTypePtrForLookup = ParsedType::make(ObjectType); 3751 else if (ObjectType->isDependentType()) 3752 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy); 3753 } 3754 3755 // Convert the name of the type being destructed (following the ~) into a 3756 // type (with source-location information). 3757 QualType DestructedType; 3758 TypeSourceInfo *DestructedTypeInfo = 0; 3759 PseudoDestructorTypeStorage Destructed; 3760 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) { 3761 ParsedType T = getTypeName(*SecondTypeName.Identifier, 3762 SecondTypeName.StartLocation, 3763 S, &SS, true, false, ObjectTypePtrForLookup); 3764 if (!T && 3765 ((SS.isSet() && !computeDeclContext(SS, false)) || 3766 (!SS.isSet() && ObjectType->isDependentType()))) { 3767 // The name of the type being destroyed is a dependent name, and we 3768 // couldn't find anything useful in scope. Just store the identifier and 3769 // it's location, and we'll perform (qualified) name lookup again at 3770 // template instantiation time. 3771 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier, 3772 SecondTypeName.StartLocation); 3773 } else if (!T) { 3774 Diag(SecondTypeName.StartLocation, 3775 diag::err_pseudo_dtor_destructor_non_type) 3776 << SecondTypeName.Identifier << ObjectType; 3777 if (isSFINAEContext()) 3778 return ExprError(); 3779 3780 // Recover by assuming we had the right type all along. 3781 DestructedType = ObjectType; 3782 } else 3783 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo); 3784 } else { 3785 // Resolve the template-id to a type. 3786 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId; 3787 ASTTemplateArgsPtr TemplateArgsPtr(*this, 3788 TemplateId->getTemplateArgs(), 3789 TemplateId->NumArgs); 3790 TypeResult T = ActOnTemplateIdType(TemplateId->SS, 3791 TemplateId->Template, 3792 TemplateId->TemplateNameLoc, 3793 TemplateId->LAngleLoc, 3794 TemplateArgsPtr, 3795 TemplateId->RAngleLoc); 3796 if (T.isInvalid() || !T.get()) { 3797 // Recover by assuming we had the right type all along. 3798 DestructedType = ObjectType; 3799 } else 3800 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo); 3801 } 3802 3803 // If we've performed some kind of recovery, (re-)build the type source 3804 // information. 3805 if (!DestructedType.isNull()) { 3806 if (!DestructedTypeInfo) 3807 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType, 3808 SecondTypeName.StartLocation); 3809 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 3810 } 3811 3812 // Convert the name of the scope type (the type prior to '::') into a type. 3813 TypeSourceInfo *ScopeTypeInfo = 0; 3814 QualType ScopeType; 3815 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId || 3816 FirstTypeName.Identifier) { 3817 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) { 3818 ParsedType T = getTypeName(*FirstTypeName.Identifier, 3819 FirstTypeName.StartLocation, 3820 S, &SS, true, false, ObjectTypePtrForLookup); 3821 if (!T) { 3822 Diag(FirstTypeName.StartLocation, 3823 diag::err_pseudo_dtor_destructor_non_type) 3824 << FirstTypeName.Identifier << ObjectType; 3825 3826 if (isSFINAEContext()) 3827 return ExprError(); 3828 3829 // Just drop this type. It's unnecessary anyway. 3830 ScopeType = QualType(); 3831 } else 3832 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo); 3833 } else { 3834 // Resolve the template-id to a type. 3835 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId; 3836 ASTTemplateArgsPtr TemplateArgsPtr(*this, 3837 TemplateId->getTemplateArgs(), 3838 TemplateId->NumArgs); 3839 TypeResult T = ActOnTemplateIdType(TemplateId->SS, 3840 TemplateId->Template, 3841 TemplateId->TemplateNameLoc, 3842 TemplateId->LAngleLoc, 3843 TemplateArgsPtr, 3844 TemplateId->RAngleLoc); 3845 if (T.isInvalid() || !T.get()) { 3846 // Recover by dropping this type. 3847 ScopeType = QualType(); 3848 } else 3849 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo); 3850 } 3851 } 3852 3853 if (!ScopeType.isNull() && !ScopeTypeInfo) 3854 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType, 3855 FirstTypeName.StartLocation); 3856 3857 3858 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS, 3859 ScopeTypeInfo, CCLoc, TildeLoc, 3860 Destructed, HasTrailingLParen); 3861} 3862 3863ExprResult Sema::BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, 3864 CXXMethodDecl *Method) { 3865 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0, 3866 FoundDecl, Method)) 3867 return true; 3868 3869 MemberExpr *ME = 3870 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method, 3871 SourceLocation(), Method->getType(), 3872 VK_RValue, OK_Ordinary); 3873 QualType ResultType = Method->getResultType(); 3874 ExprValueKind VK = Expr::getValueKindForType(ResultType); 3875 ResultType = ResultType.getNonLValueExprType(Context); 3876 3877 MarkDeclarationReferenced(Exp->getLocStart(), Method); 3878 CXXMemberCallExpr *CE = 3879 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK, 3880 Exp->getLocEnd()); 3881 return CE; 3882} 3883 3884ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, 3885 SourceLocation RParen) { 3886 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand, 3887 Operand->CanThrow(Context), 3888 KeyLoc, RParen)); 3889} 3890 3891ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation, 3892 Expr *Operand, SourceLocation RParen) { 3893 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen); 3894} 3895 3896/// Perform the conversions required for an expression used in a 3897/// context that ignores the result. 3898void Sema::IgnoredValueConversions(Expr *&E) { 3899 // C99 6.3.2.1: 3900 // [Except in specific positions,] an lvalue that does not have 3901 // array type is converted to the value stored in the 3902 // designated object (and is no longer an lvalue). 3903 if (E->isRValue()) return; 3904 3905 // We always want to do this on ObjC property references. 3906 if (E->getObjectKind() == OK_ObjCProperty) { 3907 ConvertPropertyForRValue(E); 3908 if (E->isRValue()) return; 3909 } 3910 3911 // Otherwise, this rule does not apply in C++, at least not for the moment. 3912 if (getLangOptions().CPlusPlus) return; 3913 3914 // GCC seems to also exclude expressions of incomplete enum type. 3915 if (const EnumType *T = E->getType()->getAs<EnumType>()) { 3916 if (!T->getDecl()->isComplete()) { 3917 // FIXME: stupid workaround for a codegen bug! 3918 ImpCastExprToType(E, Context.VoidTy, CK_ToVoid); 3919 return; 3920 } 3921 } 3922 3923 DefaultFunctionArrayLvalueConversion(E); 3924 if (!E->getType()->isVoidType()) 3925 RequireCompleteType(E->getExprLoc(), E->getType(), 3926 diag::err_incomplete_type); 3927} 3928 3929ExprResult Sema::ActOnFinishFullExpr(Expr *FullExpr) { 3930 if (!FullExpr) 3931 return ExprError(); 3932 3933 if (DiagnoseUnexpandedParameterPack(FullExpr)) 3934 return ExprError(); 3935 3936 // 13.4.1 ... An overloaded function name shall not be used without arguments 3937 // in contexts other than those listed [i.e list of targets]. 3938 // 3939 // void foo(); void foo(int); 3940 // template<class T> void fooT(); template<class T> void fooT(int); 3941 3942 // Therefore these should error: 3943 // foo; 3944 // fooT<int>; 3945 3946 if (FullExpr->getType() == Context.OverloadTy) { 3947 if (!ResolveSingleFunctionTemplateSpecialization(FullExpr, 3948 /* Complain */ false)) { 3949 OverloadExpr* OvlExpr = OverloadExpr::find(FullExpr).Expression; 3950 Diag(FullExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 3951 << OvlExpr->getName(); 3952 NoteAllOverloadCandidates(OvlExpr); 3953 return ExprError(); 3954 } 3955 } 3956 3957 3958 IgnoredValueConversions(FullExpr); 3959 CheckImplicitConversions(FullExpr); 3960 3961 return MaybeCreateExprWithCleanups(FullExpr); 3962} 3963 3964StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) { 3965 if (!FullStmt) return StmtError(); 3966 3967 return MaybeCreateStmtWithCleanups(FullStmt); 3968} 3969