SemaExprCXX.cpp revision ea1471e0e967548c596a71469702f8846dbaf3c0
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 "Sema.h" 15#include "SemaInit.h" 16#include "Lookup.h" 17#include "clang/AST/ASTContext.h" 18#include "clang/AST/CXXInheritance.h" 19#include "clang/AST/ExprCXX.h" 20#include "clang/AST/TypeLoc.h" 21#include "clang/Basic/PartialDiagnostic.h" 22#include "clang/Basic/TargetInfo.h" 23#include "clang/Lex/Preprocessor.h" 24#include "clang/Parse/DeclSpec.h" 25#include "clang/Parse/Template.h" 26#include "llvm/ADT/STLExtras.h" 27using namespace clang; 28 29Action::TypeTy *Sema::getDestructorName(SourceLocation TildeLoc, 30 IdentifierInfo &II, 31 SourceLocation NameLoc, 32 Scope *S, CXXScopeSpec &SS, 33 TypeTy *ObjectTypePtr, 34 bool EnteringContext) { 35 // Determine where to perform name lookup. 36 37 // FIXME: This area of the standard is very messy, and the current 38 // wording is rather unclear about which scopes we search for the 39 // destructor name; see core issues 399 and 555. Issue 399 in 40 // particular shows where the current description of destructor name 41 // lookup is completely out of line with existing practice, e.g., 42 // this appears to be ill-formed: 43 // 44 // namespace N { 45 // template <typename T> struct S { 46 // ~S(); 47 // }; 48 // } 49 // 50 // void f(N::S<int>* s) { 51 // s->N::S<int>::~S(); 52 // } 53 // 54 // See also PR6358 and PR6359. 55 QualType SearchType; 56 DeclContext *LookupCtx = 0; 57 bool isDependent = false; 58 bool LookInScope = false; 59 60 // If we have an object type, it's because we are in a 61 // pseudo-destructor-expression or a member access expression, and 62 // we know what type we're looking for. 63 if (ObjectTypePtr) 64 SearchType = GetTypeFromParser(ObjectTypePtr); 65 66 if (SS.isSet()) { 67 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep(); 68 69 bool AlreadySearched = false; 70 bool LookAtPrefix = true; 71 if (!getLangOptions().CPlusPlus0x) { 72 // C++ [basic.lookup.qual]p6: 73 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier, 74 // the type-names are looked up as types in the scope designated by the 75 // nested-name-specifier. In a qualified-id of the form: 76 // 77 // ::[opt] nested-name-specifier ̃ class-name 78 // 79 // where the nested-name-specifier designates a namespace scope, and in 80 // a qualified-id of the form: 81 // 82 // ::opt nested-name-specifier class-name :: ̃ class-name 83 // 84 // the class-names are looked up as types in the scope designated by 85 // the nested-name-specifier. 86 // 87 // Here, we check the first case (completely) and determine whether the 88 // code below is permitted to look at the prefix of the 89 // nested-name-specifier (as we do in C++0x). 90 DeclContext *DC = computeDeclContext(SS, EnteringContext); 91 if (DC && DC->isFileContext()) { 92 AlreadySearched = true; 93 LookupCtx = DC; 94 isDependent = false; 95 } else if (DC && isa<CXXRecordDecl>(DC)) 96 LookAtPrefix = false; 97 } 98 99 // C++0x [basic.lookup.qual]p6: 100 // If a pseudo-destructor-name (5.2.4) contains a 101 // nested-name-specifier, the type-names are looked up as types 102 // in the scope designated by the nested-name-specifier. Similarly, in 103 // a qualified-id of the form: 104 // 105 // :: [opt] nested-name-specifier[opt] class-name :: ~class-name 106 // 107 // the second class-name is looked up in the same scope as the first. 108 // 109 // To implement this, we look at the prefix of the 110 // nested-name-specifier we were given, and determine the lookup 111 // context from that. 112 // 113 // We also fold in the second case from the C++03 rules quoted further 114 // above. 115 NestedNameSpecifier *Prefix = 0; 116 if (AlreadySearched) { 117 // Nothing left to do. 118 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) { 119 CXXScopeSpec PrefixSS; 120 PrefixSS.setScopeRep(Prefix); 121 LookupCtx = computeDeclContext(PrefixSS, EnteringContext); 122 isDependent = isDependentScopeSpecifier(PrefixSS); 123 } else if (getLangOptions().CPlusPlus0x && 124 (LookupCtx = computeDeclContext(SS, EnteringContext))) { 125 if (!LookupCtx->isTranslationUnit()) 126 LookupCtx = LookupCtx->getParent(); 127 isDependent = LookupCtx && LookupCtx->isDependentContext(); 128 } else if (ObjectTypePtr) { 129 LookupCtx = computeDeclContext(SearchType); 130 isDependent = SearchType->isDependentType(); 131 } else { 132 LookupCtx = computeDeclContext(SS, EnteringContext); 133 isDependent = LookupCtx && LookupCtx->isDependentContext(); 134 } 135 136 LookInScope = false; 137 } else if (ObjectTypePtr) { 138 // C++ [basic.lookup.classref]p3: 139 // If the unqualified-id is ~type-name, the type-name is looked up 140 // in the context of the entire postfix-expression. If the type T 141 // of the object expression is of a class type C, the type-name is 142 // also looked up in the scope of class C. At least one of the 143 // lookups shall find a name that refers to (possibly 144 // cv-qualified) T. 145 LookupCtx = computeDeclContext(SearchType); 146 isDependent = SearchType->isDependentType(); 147 assert((isDependent || !SearchType->isIncompleteType()) && 148 "Caller should have completed object type"); 149 150 LookInScope = true; 151 } else { 152 // Perform lookup into the current scope (only). 153 LookInScope = true; 154 } 155 156 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName); 157 for (unsigned Step = 0; Step != 2; ++Step) { 158 // Look for the name first in the computed lookup context (if we 159 // have one) and, if that fails to find a match, in the sope (if 160 // we're allowed to look there). 161 Found.clear(); 162 if (Step == 0 && LookupCtx) 163 LookupQualifiedName(Found, LookupCtx); 164 else if (Step == 1 && LookInScope && S) 165 LookupName(Found, S); 166 else 167 continue; 168 169 // FIXME: Should we be suppressing ambiguities here? 170 if (Found.isAmbiguous()) 171 return 0; 172 173 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) { 174 QualType T = Context.getTypeDeclType(Type); 175 176 if (SearchType.isNull() || SearchType->isDependentType() || 177 Context.hasSameUnqualifiedType(T, SearchType)) { 178 // We found our type! 179 180 return T.getAsOpaquePtr(); 181 } 182 } 183 184 // If the name that we found is a class template name, and it is 185 // the same name as the template name in the last part of the 186 // nested-name-specifier (if present) or the object type, then 187 // this is the destructor for that class. 188 // FIXME: This is a workaround until we get real drafting for core 189 // issue 399, for which there isn't even an obvious direction. 190 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) { 191 QualType MemberOfType; 192 if (SS.isSet()) { 193 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) { 194 // Figure out the type of the context, if it has one. 195 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) 196 MemberOfType = Context.getTypeDeclType(Record); 197 } 198 } 199 if (MemberOfType.isNull()) 200 MemberOfType = SearchType; 201 202 if (MemberOfType.isNull()) 203 continue; 204 205 // We're referring into a class template specialization. If the 206 // class template we found is the same as the template being 207 // specialized, we found what we are looking for. 208 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) { 209 if (ClassTemplateSpecializationDecl *Spec 210 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { 211 if (Spec->getSpecializedTemplate()->getCanonicalDecl() == 212 Template->getCanonicalDecl()) 213 return MemberOfType.getAsOpaquePtr(); 214 } 215 216 continue; 217 } 218 219 // We're referring to an unresolved class template 220 // specialization. Determine whether we class template we found 221 // is the same as the template being specialized or, if we don't 222 // know which template is being specialized, that it at least 223 // has the same name. 224 if (const TemplateSpecializationType *SpecType 225 = MemberOfType->getAs<TemplateSpecializationType>()) { 226 TemplateName SpecName = SpecType->getTemplateName(); 227 228 // The class template we found is the same template being 229 // specialized. 230 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) { 231 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl()) 232 return MemberOfType.getAsOpaquePtr(); 233 234 continue; 235 } 236 237 // The class template we found has the same name as the 238 // (dependent) template name being specialized. 239 if (DependentTemplateName *DepTemplate 240 = SpecName.getAsDependentTemplateName()) { 241 if (DepTemplate->isIdentifier() && 242 DepTemplate->getIdentifier() == Template->getIdentifier()) 243 return MemberOfType.getAsOpaquePtr(); 244 245 continue; 246 } 247 } 248 } 249 } 250 251 if (isDependent) { 252 // We didn't find our type, but that's okay: it's dependent 253 // anyway. 254 NestedNameSpecifier *NNS = 0; 255 SourceRange Range; 256 if (SS.isSet()) { 257 NNS = (NestedNameSpecifier *)SS.getScopeRep(); 258 Range = SourceRange(SS.getRange().getBegin(), NameLoc); 259 } else { 260 NNS = NestedNameSpecifier::Create(Context, &II); 261 Range = SourceRange(NameLoc); 262 } 263 264 return CheckTypenameType(ETK_None, NNS, II, SourceLocation(), 265 Range, NameLoc).getAsOpaquePtr(); 266 } 267 268 if (ObjectTypePtr) 269 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type) 270 << &II; 271 else 272 Diag(NameLoc, diag::err_destructor_class_name); 273 274 return 0; 275} 276 277/// \brief Build a C++ typeid expression with a type operand. 278Sema::OwningExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, 279 SourceLocation TypeidLoc, 280 TypeSourceInfo *Operand, 281 SourceLocation RParenLoc) { 282 // C++ [expr.typeid]p4: 283 // The top-level cv-qualifiers of the lvalue expression or the type-id 284 // that is the operand of typeid are always ignored. 285 // If the type of the type-id is a class type or a reference to a class 286 // type, the class shall be completely-defined. 287 QualType T = Operand->getType().getNonReferenceType(); 288 if (T->getAs<RecordType>() && 289 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) 290 return ExprError(); 291 292 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(), 293 Operand, 294 SourceRange(TypeidLoc, RParenLoc))); 295} 296 297/// \brief Build a C++ typeid expression with an expression operand. 298Sema::OwningExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, 299 SourceLocation TypeidLoc, 300 ExprArg Operand, 301 SourceLocation RParenLoc) { 302 bool isUnevaluatedOperand = true; 303 Expr *E = static_cast<Expr *>(Operand.get()); 304 if (E && !E->isTypeDependent()) { 305 QualType T = E->getType(); 306 if (const RecordType *RecordT = T->getAs<RecordType>()) { 307 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl()); 308 // C++ [expr.typeid]p3: 309 // [...] If the type of the expression is a class type, the class 310 // shall be completely-defined. 311 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) 312 return ExprError(); 313 314 // C++ [expr.typeid]p3: 315 // When typeid is applied to an expression other than an lvalue of a 316 // polymorphic class type [...] [the] expression is an unevaluated 317 // operand. [...] 318 if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid) { 319 isUnevaluatedOperand = false; 320 321 // We require a vtable to query the type at run time. 322 MarkVTableUsed(TypeidLoc, RecordD); 323 } 324 } 325 326 // C++ [expr.typeid]p4: 327 // [...] If the type of the type-id is a reference to a possibly 328 // cv-qualified type, the result of the typeid expression refers to a 329 // std::type_info object representing the cv-unqualified referenced 330 // type. 331 if (T.hasQualifiers()) { 332 ImpCastExprToType(E, T.getUnqualifiedType(), CastExpr::CK_NoOp, 333 E->isLvalue(Context)); 334 Operand.release(); 335 Operand = Owned(E); 336 } 337 } 338 339 // If this is an unevaluated operand, clear out the set of 340 // declaration references we have been computing and eliminate any 341 // temporaries introduced in its computation. 342 if (isUnevaluatedOperand) 343 ExprEvalContexts.back().Context = Unevaluated; 344 345 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(), 346 Operand.takeAs<Expr>(), 347 SourceRange(TypeidLoc, RParenLoc))); 348} 349 350/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression); 351Action::OwningExprResult 352Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, 353 bool isType, void *TyOrExpr, SourceLocation RParenLoc) { 354 // Find the std::type_info type. 355 if (!StdNamespace) 356 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); 357 358 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info"); 359 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName); 360 LookupQualifiedName(R, StdNamespace); 361 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>(); 362 if (!TypeInfoRecordDecl) 363 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); 364 365 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl); 366 367 if (isType) { 368 // The operand is a type; handle it as such. 369 TypeSourceInfo *TInfo = 0; 370 QualType T = GetTypeFromParser(TyOrExpr, &TInfo); 371 if (T.isNull()) 372 return ExprError(); 373 374 if (!TInfo) 375 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); 376 377 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc); 378 } 379 380 // The operand is an expression. 381 return BuildCXXTypeId(TypeInfoType, OpLoc, Owned((Expr*)TyOrExpr), RParenLoc); 382} 383 384/// ActOnCXXBoolLiteral - Parse {true,false} literals. 385Action::OwningExprResult 386Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 387 assert((Kind == tok::kw_true || Kind == tok::kw_false) && 388 "Unknown C++ Boolean value!"); 389 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true, 390 Context.BoolTy, OpLoc)); 391} 392 393/// ActOnCXXNullPtrLiteral - Parse 'nullptr'. 394Action::OwningExprResult 395Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) { 396 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc)); 397} 398 399/// ActOnCXXThrow - Parse throw expressions. 400Action::OwningExprResult 401Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) { 402 Expr *Ex = E.takeAs<Expr>(); 403 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex)) 404 return ExprError(); 405 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc)); 406} 407 408/// CheckCXXThrowOperand - Validate the operand of a throw. 409bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) { 410 // C++ [except.throw]p3: 411 // A throw-expression initializes a temporary object, called the exception 412 // object, the type of which is determined by removing any top-level 413 // cv-qualifiers from the static type of the operand of throw and adjusting 414 // the type from "array of T" or "function returning T" to "pointer to T" 415 // or "pointer to function returning T", [...] 416 if (E->getType().hasQualifiers()) 417 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp, 418 E->isLvalue(Context) == Expr::LV_Valid); 419 420 DefaultFunctionArrayConversion(E); 421 422 // If the type of the exception would be an incomplete type or a pointer 423 // to an incomplete type other than (cv) void the program is ill-formed. 424 QualType Ty = E->getType(); 425 bool isPointer = false; 426 if (const PointerType* Ptr = Ty->getAs<PointerType>()) { 427 Ty = Ptr->getPointeeType(); 428 isPointer = true; 429 } 430 if (!isPointer || !Ty->isVoidType()) { 431 if (RequireCompleteType(ThrowLoc, Ty, 432 PDiag(isPointer ? diag::err_throw_incomplete_ptr 433 : diag::err_throw_incomplete) 434 << E->getSourceRange())) 435 return true; 436 437 if (RequireNonAbstractType(ThrowLoc, E->getType(), 438 PDiag(diag::err_throw_abstract_type) 439 << E->getSourceRange())) 440 return true; 441 } 442 443 // Initialize the exception result. This implicitly weeds out 444 // abstract types or types with inaccessible copy constructors. 445 // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p34. 446 InitializedEntity Entity = 447 InitializedEntity::InitializeException(ThrowLoc, E->getType(), 448 /*NRVO=*/false); 449 OwningExprResult Res = PerformCopyInitialization(Entity, 450 SourceLocation(), 451 Owned(E)); 452 if (Res.isInvalid()) 453 return true; 454 E = Res.takeAs<Expr>(); 455 456 // If we are throwing a polymorphic class type or pointer thereof, 457 // exception handling will make use of the vtable. 458 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) 459 MarkVTableUsed(ThrowLoc, cast<CXXRecordDecl>(RecordTy->getDecl())); 460 461 return false; 462} 463 464Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) { 465 /// C++ 9.3.2: In the body of a non-static member function, the keyword this 466 /// is a non-lvalue expression whose value is the address of the object for 467 /// which the function is called. 468 469 DeclContext *DC = getFunctionLevelDeclContext(); 470 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) 471 if (MD->isInstance()) 472 return Owned(new (Context) CXXThisExpr(ThisLoc, 473 MD->getThisType(Context), 474 /*isImplicit=*/false)); 475 476 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use)); 477} 478 479/// ActOnCXXTypeConstructExpr - Parse construction of a specified type. 480/// Can be interpreted either as function-style casting ("int(x)") 481/// or class type construction ("ClassType(x,y,z)") 482/// or creation of a value-initialized type ("int()"). 483Action::OwningExprResult 484Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep, 485 SourceLocation LParenLoc, 486 MultiExprArg exprs, 487 SourceLocation *CommaLocs, 488 SourceLocation RParenLoc) { 489 if (!TypeRep) 490 return ExprError(); 491 492 TypeSourceInfo *TInfo; 493 QualType Ty = GetTypeFromParser(TypeRep, &TInfo); 494 if (!TInfo) 495 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation()); 496 unsigned NumExprs = exprs.size(); 497 Expr **Exprs = (Expr**)exprs.get(); 498 SourceLocation TyBeginLoc = TypeRange.getBegin(); 499 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc); 500 501 if (Ty->isDependentType() || 502 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) { 503 exprs.release(); 504 505 return Owned(CXXUnresolvedConstructExpr::Create(Context, 506 TypeRange.getBegin(), Ty, 507 LParenLoc, 508 Exprs, NumExprs, 509 RParenLoc)); 510 } 511 512 if (Ty->isArrayType()) 513 return ExprError(Diag(TyBeginLoc, 514 diag::err_value_init_for_array_type) << FullRange); 515 if (!Ty->isVoidType() && 516 RequireCompleteType(TyBeginLoc, Ty, 517 PDiag(diag::err_invalid_incomplete_type_use) 518 << FullRange)) 519 return ExprError(); 520 521 if (RequireNonAbstractType(TyBeginLoc, Ty, 522 diag::err_allocation_of_abstract_type)) 523 return ExprError(); 524 525 526 // C++ [expr.type.conv]p1: 527 // If the expression list is a single expression, the type conversion 528 // expression is equivalent (in definedness, and if defined in meaning) to the 529 // corresponding cast expression. 530 // 531 if (NumExprs == 1) { 532 CastExpr::CastKind Kind = CastExpr::CK_Unknown; 533 CXXBaseSpecifierArray BasePath; 534 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, BasePath, 535 /*FunctionalStyle=*/true)) 536 return ExprError(); 537 538 exprs.release(); 539 540 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(), 541 TInfo, TyBeginLoc, Kind, 542 Exprs[0], BasePath, 543 RParenLoc)); 544 } 545 546 if (const RecordType *RT = Ty->getAs<RecordType>()) { 547 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl()); 548 549 if (NumExprs > 1 || !Record->hasTrivialConstructor() || 550 !Record->hasTrivialDestructor()) { 551 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 552 InitializationKind Kind 553 = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(), 554 LParenLoc, RParenLoc) 555 : InitializationKind::CreateValue(TypeRange.getBegin(), 556 LParenLoc, RParenLoc); 557 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs); 558 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, 559 move(exprs)); 560 561 // FIXME: Improve AST representation? 562 return move(Result); 563 } 564 565 // Fall through to value-initialize an object of class type that 566 // doesn't have a user-declared default constructor. 567 } 568 569 // C++ [expr.type.conv]p1: 570 // If the expression list specifies more than a single value, the type shall 571 // be a class with a suitably declared constructor. 572 // 573 if (NumExprs > 1) 574 return ExprError(Diag(CommaLocs[0], 575 diag::err_builtin_func_cast_more_than_one_arg) 576 << FullRange); 577 578 assert(NumExprs == 0 && "Expected 0 expressions"); 579 // C++ [expr.type.conv]p2: 580 // The expression T(), where T is a simple-type-specifier for a non-array 581 // complete object type or the (possibly cv-qualified) void type, creates an 582 // rvalue of the specified type, which is value-initialized. 583 // 584 exprs.release(); 585 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc)); 586} 587 588 589/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.: 590/// @code new (memory) int[size][4] @endcode 591/// or 592/// @code ::new Foo(23, "hello") @endcode 593/// For the interpretation of this heap of arguments, consult the base version. 594Action::OwningExprResult 595Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 596 SourceLocation PlacementLParen, MultiExprArg PlacementArgs, 597 SourceLocation PlacementRParen, bool ParenTypeId, 598 Declarator &D, SourceLocation ConstructorLParen, 599 MultiExprArg ConstructorArgs, 600 SourceLocation ConstructorRParen) { 601 Expr *ArraySize = 0; 602 // If the specified type is an array, unwrap it and save the expression. 603 if (D.getNumTypeObjects() > 0 && 604 D.getTypeObject(0).Kind == DeclaratorChunk::Array) { 605 DeclaratorChunk &Chunk = D.getTypeObject(0); 606 if (Chunk.Arr.hasStatic) 607 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new) 608 << D.getSourceRange()); 609 if (!Chunk.Arr.NumElts) 610 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size) 611 << D.getSourceRange()); 612 613 if (ParenTypeId) { 614 // Can't have dynamic array size when the type-id is in parentheses. 615 Expr *NumElts = (Expr *)Chunk.Arr.NumElts; 616 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() && 617 !NumElts->isIntegerConstantExpr(Context)) { 618 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst) 619 << NumElts->getSourceRange(); 620 return ExprError(); 621 } 622 } 623 624 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts); 625 D.DropFirstTypeObject(); 626 } 627 628 // Every dimension shall be of constant size. 629 if (ArraySize) { 630 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) { 631 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array) 632 break; 633 634 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr; 635 if (Expr *NumElts = (Expr *)Array.NumElts) { 636 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() && 637 !NumElts->isIntegerConstantExpr(Context)) { 638 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst) 639 << NumElts->getSourceRange(); 640 return ExprError(); 641 } 642 } 643 } 644 } 645 646 //FIXME: Store TypeSourceInfo in CXXNew expression. 647 TypeSourceInfo *TInfo = 0; 648 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo); 649 if (D.isInvalidType()) 650 return ExprError(); 651 652 return BuildCXXNew(StartLoc, UseGlobal, 653 PlacementLParen, 654 move(PlacementArgs), 655 PlacementRParen, 656 ParenTypeId, 657 AllocType, 658 D.getSourceRange().getBegin(), 659 D.getSourceRange(), 660 Owned(ArraySize), 661 ConstructorLParen, 662 move(ConstructorArgs), 663 ConstructorRParen); 664} 665 666Sema::OwningExprResult 667Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal, 668 SourceLocation PlacementLParen, 669 MultiExprArg PlacementArgs, 670 SourceLocation PlacementRParen, 671 bool ParenTypeId, 672 QualType AllocType, 673 SourceLocation TypeLoc, 674 SourceRange TypeRange, 675 ExprArg ArraySizeE, 676 SourceLocation ConstructorLParen, 677 MultiExprArg ConstructorArgs, 678 SourceLocation ConstructorRParen) { 679 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange)) 680 return ExprError(); 681 682 // Per C++0x [expr.new]p5, the type being constructed may be a 683 // typedef of an array type. 684 if (!ArraySizeE.get()) { 685 if (const ConstantArrayType *Array 686 = Context.getAsConstantArrayType(AllocType)) { 687 ArraySizeE = Owned(new (Context) IntegerLiteral(Array->getSize(), 688 Context.getSizeType(), 689 TypeRange.getEnd())); 690 AllocType = Array->getElementType(); 691 } 692 } 693 694 QualType ResultType = Context.getPointerType(AllocType); 695 696 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral 697 // or enumeration type with a non-negative value." 698 Expr *ArraySize = (Expr *)ArraySizeE.get(); 699 if (ArraySize && !ArraySize->isTypeDependent()) { 700 QualType SizeType = ArraySize->getType(); 701 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType()) 702 return ExprError(Diag(ArraySize->getSourceRange().getBegin(), 703 diag::err_array_size_not_integral) 704 << SizeType << ArraySize->getSourceRange()); 705 // Let's see if this is a constant < 0. If so, we reject it out of hand. 706 // We don't care about special rules, so we tell the machinery it's not 707 // evaluated - it gives us a result in more cases. 708 if (!ArraySize->isValueDependent()) { 709 llvm::APSInt Value; 710 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) { 711 if (Value < llvm::APSInt( 712 llvm::APInt::getNullValue(Value.getBitWidth()), 713 Value.isUnsigned())) 714 return ExprError(Diag(ArraySize->getSourceRange().getBegin(), 715 diag::err_typecheck_negative_array_size) 716 << ArraySize->getSourceRange()); 717 } 718 } 719 720 ImpCastExprToType(ArraySize, Context.getSizeType(), 721 CastExpr::CK_IntegralCast); 722 } 723 724 FunctionDecl *OperatorNew = 0; 725 FunctionDecl *OperatorDelete = 0; 726 Expr **PlaceArgs = (Expr**)PlacementArgs.get(); 727 unsigned NumPlaceArgs = PlacementArgs.size(); 728 729 if (!AllocType->isDependentType() && 730 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) && 731 FindAllocationFunctions(StartLoc, 732 SourceRange(PlacementLParen, PlacementRParen), 733 UseGlobal, AllocType, ArraySize, PlaceArgs, 734 NumPlaceArgs, OperatorNew, OperatorDelete)) 735 return ExprError(); 736 llvm::SmallVector<Expr *, 8> AllPlaceArgs; 737 if (OperatorNew) { 738 // Add default arguments, if any. 739 const FunctionProtoType *Proto = 740 OperatorNew->getType()->getAs<FunctionProtoType>(); 741 VariadicCallType CallType = 742 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply; 743 744 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, 745 Proto, 1, PlaceArgs, NumPlaceArgs, 746 AllPlaceArgs, CallType)) 747 return ExprError(); 748 749 NumPlaceArgs = AllPlaceArgs.size(); 750 if (NumPlaceArgs > 0) 751 PlaceArgs = &AllPlaceArgs[0]; 752 } 753 754 bool Init = ConstructorLParen.isValid(); 755 // --- Choosing a constructor --- 756 CXXConstructorDecl *Constructor = 0; 757 Expr **ConsArgs = (Expr**)ConstructorArgs.get(); 758 unsigned NumConsArgs = ConstructorArgs.size(); 759 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this); 760 761 // Array 'new' can't have any initializers. 762 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) { 763 SourceRange InitRange(ConsArgs[0]->getLocStart(), 764 ConsArgs[NumConsArgs - 1]->getLocEnd()); 765 766 Diag(StartLoc, diag::err_new_array_init_args) << InitRange; 767 return ExprError(); 768 } 769 770 if (!AllocType->isDependentType() && 771 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) { 772 // C++0x [expr.new]p15: 773 // A new-expression that creates an object of type T initializes that 774 // object as follows: 775 InitializationKind Kind 776 // - If the new-initializer is omitted, the object is default- 777 // initialized (8.5); if no initialization is performed, 778 // the object has indeterminate value 779 = !Init? InitializationKind::CreateDefault(TypeLoc) 780 // - Otherwise, the new-initializer is interpreted according to the 781 // initialization rules of 8.5 for direct-initialization. 782 : InitializationKind::CreateDirect(TypeLoc, 783 ConstructorLParen, 784 ConstructorRParen); 785 786 InitializedEntity Entity 787 = InitializedEntity::InitializeNew(StartLoc, AllocType); 788 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs); 789 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, 790 move(ConstructorArgs)); 791 if (FullInit.isInvalid()) 792 return ExprError(); 793 794 // FullInit is our initializer; walk through it to determine if it's a 795 // constructor call, which CXXNewExpr handles directly. 796 if (Expr *FullInitExpr = (Expr *)FullInit.get()) { 797 if (CXXBindTemporaryExpr *Binder 798 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr)) 799 FullInitExpr = Binder->getSubExpr(); 800 if (CXXConstructExpr *Construct 801 = dyn_cast<CXXConstructExpr>(FullInitExpr)) { 802 Constructor = Construct->getConstructor(); 803 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(), 804 AEnd = Construct->arg_end(); 805 A != AEnd; ++A) 806 ConvertedConstructorArgs.push_back(A->Retain()); 807 } else { 808 // Take the converted initializer. 809 ConvertedConstructorArgs.push_back(FullInit.release()); 810 } 811 } else { 812 // No initialization required. 813 } 814 815 // Take the converted arguments and use them for the new expression. 816 NumConsArgs = ConvertedConstructorArgs.size(); 817 ConsArgs = (Expr **)ConvertedConstructorArgs.take(); 818 } 819 820 // Mark the new and delete operators as referenced. 821 if (OperatorNew) 822 MarkDeclarationReferenced(StartLoc, OperatorNew); 823 if (OperatorDelete) 824 MarkDeclarationReferenced(StartLoc, OperatorDelete); 825 826 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16) 827 828 PlacementArgs.release(); 829 ConstructorArgs.release(); 830 ArraySizeE.release(); 831 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew, 832 PlaceArgs, NumPlaceArgs, ParenTypeId, 833 ArraySize, Constructor, Init, 834 ConsArgs, NumConsArgs, OperatorDelete, 835 ResultType, StartLoc, 836 Init ? ConstructorRParen : 837 SourceLocation())); 838} 839 840/// CheckAllocatedType - Checks that a type is suitable as the allocated type 841/// in a new-expression. 842/// dimension off and stores the size expression in ArraySize. 843bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc, 844 SourceRange R) { 845 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an 846 // abstract class type or array thereof. 847 if (AllocType->isFunctionType()) 848 return Diag(Loc, diag::err_bad_new_type) 849 << AllocType << 0 << R; 850 else if (AllocType->isReferenceType()) 851 return Diag(Loc, diag::err_bad_new_type) 852 << AllocType << 1 << R; 853 else if (!AllocType->isDependentType() && 854 RequireCompleteType(Loc, AllocType, 855 PDiag(diag::err_new_incomplete_type) 856 << R)) 857 return true; 858 else if (RequireNonAbstractType(Loc, AllocType, 859 diag::err_allocation_of_abstract_type)) 860 return true; 861 862 return false; 863} 864 865/// \brief Determine whether the given function is a non-placement 866/// deallocation function. 867static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) { 868 if (FD->isInvalidDecl()) 869 return false; 870 871 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD)) 872 return Method->isUsualDeallocationFunction(); 873 874 return ((FD->getOverloadedOperator() == OO_Delete || 875 FD->getOverloadedOperator() == OO_Array_Delete) && 876 FD->getNumParams() == 1); 877} 878 879/// FindAllocationFunctions - Finds the overloads of operator new and delete 880/// that are appropriate for the allocation. 881bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 882 bool UseGlobal, QualType AllocType, 883 bool IsArray, Expr **PlaceArgs, 884 unsigned NumPlaceArgs, 885 FunctionDecl *&OperatorNew, 886 FunctionDecl *&OperatorDelete) { 887 // --- Choosing an allocation function --- 888 // C++ 5.3.4p8 - 14 & 18 889 // 1) If UseGlobal is true, only look in the global scope. Else, also look 890 // in the scope of the allocated class. 891 // 2) If an array size is given, look for operator new[], else look for 892 // operator new. 893 // 3) The first argument is always size_t. Append the arguments from the 894 // placement form. 895 896 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs); 897 // We don't care about the actual value of this argument. 898 // FIXME: Should the Sema create the expression and embed it in the syntax 899 // tree? Or should the consumer just recalculate the value? 900 IntegerLiteral Size(llvm::APInt::getNullValue( 901 Context.Target.getPointerWidth(0)), 902 Context.getSizeType(), 903 SourceLocation()); 904 AllocArgs[0] = &Size; 905 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1); 906 907 // C++ [expr.new]p8: 908 // If the allocated type is a non-array type, the allocation 909 // function’s name is operator new and the deallocation function’s 910 // name is operator delete. If the allocated type is an array 911 // type, the allocation function’s name is operator new[] and the 912 // deallocation function’s name is operator delete[]. 913 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName( 914 IsArray ? OO_Array_New : OO_New); 915 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( 916 IsArray ? OO_Array_Delete : OO_Delete); 917 918 if (AllocType->isRecordType() && !UseGlobal) { 919 CXXRecordDecl *Record 920 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl()); 921 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0], 922 AllocArgs.size(), Record, /*AllowMissing=*/true, 923 OperatorNew)) 924 return true; 925 } 926 if (!OperatorNew) { 927 // Didn't find a member overload. Look for a global one. 928 DeclareGlobalNewDelete(); 929 DeclContext *TUDecl = Context.getTranslationUnitDecl(); 930 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0], 931 AllocArgs.size(), TUDecl, /*AllowMissing=*/false, 932 OperatorNew)) 933 return true; 934 } 935 936 // We don't need an operator delete if we're running under 937 // -fno-exceptions. 938 if (!getLangOptions().Exceptions) { 939 OperatorDelete = 0; 940 return false; 941 } 942 943 // FindAllocationOverload can change the passed in arguments, so we need to 944 // copy them back. 945 if (NumPlaceArgs > 0) 946 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs); 947 948 // C++ [expr.new]p19: 949 // 950 // If the new-expression begins with a unary :: operator, the 951 // deallocation function’s name is looked up in the global 952 // scope. Otherwise, if the allocated type is a class type T or an 953 // array thereof, the deallocation function’s name is looked up in 954 // the scope of T. If this lookup fails to find the name, or if 955 // the allocated type is not a class type or array thereof, the 956 // deallocation function’s name is looked up in the global scope. 957 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName); 958 if (AllocType->isRecordType() && !UseGlobal) { 959 CXXRecordDecl *RD 960 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl()); 961 LookupQualifiedName(FoundDelete, RD); 962 } 963 if (FoundDelete.isAmbiguous()) 964 return true; // FIXME: clean up expressions? 965 966 if (FoundDelete.empty()) { 967 DeclareGlobalNewDelete(); 968 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl()); 969 } 970 971 FoundDelete.suppressDiagnostics(); 972 973 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches; 974 975 if (NumPlaceArgs > 0) { 976 // C++ [expr.new]p20: 977 // A declaration of a placement deallocation function matches the 978 // declaration of a placement allocation function if it has the 979 // same number of parameters and, after parameter transformations 980 // (8.3.5), all parameter types except the first are 981 // identical. [...] 982 // 983 // To perform this comparison, we compute the function type that 984 // the deallocation function should have, and use that type both 985 // for template argument deduction and for comparison purposes. 986 QualType ExpectedFunctionType; 987 { 988 const FunctionProtoType *Proto 989 = OperatorNew->getType()->getAs<FunctionProtoType>(); 990 llvm::SmallVector<QualType, 4> ArgTypes; 991 ArgTypes.push_back(Context.VoidPtrTy); 992 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I) 993 ArgTypes.push_back(Proto->getArgType(I)); 994 995 ExpectedFunctionType 996 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(), 997 ArgTypes.size(), 998 Proto->isVariadic(), 999 0, false, false, 0, 0, 1000 FunctionType::ExtInfo()); 1001 } 1002 1003 for (LookupResult::iterator D = FoundDelete.begin(), 1004 DEnd = FoundDelete.end(); 1005 D != DEnd; ++D) { 1006 FunctionDecl *Fn = 0; 1007 if (FunctionTemplateDecl *FnTmpl 1008 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) { 1009 // Perform template argument deduction to try to match the 1010 // expected function type. 1011 TemplateDeductionInfo Info(Context, StartLoc); 1012 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info)) 1013 continue; 1014 } else 1015 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl()); 1016 1017 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType)) 1018 Matches.push_back(std::make_pair(D.getPair(), Fn)); 1019 } 1020 } else { 1021 // C++ [expr.new]p20: 1022 // [...] Any non-placement deallocation function matches a 1023 // non-placement allocation function. [...] 1024 for (LookupResult::iterator D = FoundDelete.begin(), 1025 DEnd = FoundDelete.end(); 1026 D != DEnd; ++D) { 1027 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl())) 1028 if (isNonPlacementDeallocationFunction(Fn)) 1029 Matches.push_back(std::make_pair(D.getPair(), Fn)); 1030 } 1031 } 1032 1033 // C++ [expr.new]p20: 1034 // [...] If the lookup finds a single matching deallocation 1035 // function, that function will be called; otherwise, no 1036 // deallocation function will be called. 1037 if (Matches.size() == 1) { 1038 OperatorDelete = Matches[0].second; 1039 1040 // C++0x [expr.new]p20: 1041 // If the lookup finds the two-parameter form of a usual 1042 // deallocation function (3.7.4.2) and that function, considered 1043 // as a placement deallocation function, would have been 1044 // selected as a match for the allocation function, the program 1045 // is ill-formed. 1046 if (NumPlaceArgs && getLangOptions().CPlusPlus0x && 1047 isNonPlacementDeallocationFunction(OperatorDelete)) { 1048 Diag(StartLoc, diag::err_placement_new_non_placement_delete) 1049 << SourceRange(PlaceArgs[0]->getLocStart(), 1050 PlaceArgs[NumPlaceArgs - 1]->getLocEnd()); 1051 Diag(OperatorDelete->getLocation(), diag::note_previous_decl) 1052 << DeleteName; 1053 } else { 1054 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(), 1055 Matches[0].first); 1056 } 1057 } 1058 1059 return false; 1060} 1061 1062/// FindAllocationOverload - Find an fitting overload for the allocation 1063/// function in the specified scope. 1064bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range, 1065 DeclarationName Name, Expr** Args, 1066 unsigned NumArgs, DeclContext *Ctx, 1067 bool AllowMissing, FunctionDecl *&Operator) { 1068 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName); 1069 LookupQualifiedName(R, Ctx); 1070 if (R.empty()) { 1071 if (AllowMissing) 1072 return false; 1073 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) 1074 << Name << Range; 1075 } 1076 1077 if (R.isAmbiguous()) 1078 return true; 1079 1080 R.suppressDiagnostics(); 1081 1082 OverloadCandidateSet Candidates(StartLoc); 1083 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end(); 1084 Alloc != AllocEnd; ++Alloc) { 1085 // Even member operator new/delete are implicitly treated as 1086 // static, so don't use AddMemberCandidate. 1087 NamedDecl *D = (*Alloc)->getUnderlyingDecl(); 1088 1089 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) { 1090 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(), 1091 /*ExplicitTemplateArgs=*/0, Args, NumArgs, 1092 Candidates, 1093 /*SuppressUserConversions=*/false); 1094 continue; 1095 } 1096 1097 FunctionDecl *Fn = cast<FunctionDecl>(D); 1098 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates, 1099 /*SuppressUserConversions=*/false); 1100 } 1101 1102 // Do the resolution. 1103 OverloadCandidateSet::iterator Best; 1104 switch(BestViableFunction(Candidates, StartLoc, Best)) { 1105 case OR_Success: { 1106 // Got one! 1107 FunctionDecl *FnDecl = Best->Function; 1108 // The first argument is size_t, and the first parameter must be size_t, 1109 // too. This is checked on declaration and can be assumed. (It can't be 1110 // asserted on, though, since invalid decls are left in there.) 1111 // Watch out for variadic allocator function. 1112 unsigned NumArgsInFnDecl = FnDecl->getNumParams(); 1113 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) { 1114 OwningExprResult Result 1115 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 1116 FnDecl->getParamDecl(i)), 1117 SourceLocation(), 1118 Owned(Args[i]->Retain())); 1119 if (Result.isInvalid()) 1120 return true; 1121 1122 Args[i] = Result.takeAs<Expr>(); 1123 } 1124 Operator = FnDecl; 1125 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl); 1126 return false; 1127 } 1128 1129 case OR_No_Viable_Function: 1130 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) 1131 << Name << Range; 1132 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs); 1133 return true; 1134 1135 case OR_Ambiguous: 1136 Diag(StartLoc, diag::err_ovl_ambiguous_call) 1137 << Name << Range; 1138 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs); 1139 return true; 1140 1141 case OR_Deleted: 1142 Diag(StartLoc, diag::err_ovl_deleted_call) 1143 << Best->Function->isDeleted() 1144 << Name << Range; 1145 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs); 1146 return true; 1147 } 1148 assert(false && "Unreachable, bad result from BestViableFunction"); 1149 return true; 1150} 1151 1152 1153/// DeclareGlobalNewDelete - Declare the global forms of operator new and 1154/// delete. These are: 1155/// @code 1156/// void* operator new(std::size_t) throw(std::bad_alloc); 1157/// void* operator new[](std::size_t) throw(std::bad_alloc); 1158/// void operator delete(void *) throw(); 1159/// void operator delete[](void *) throw(); 1160/// @endcode 1161/// Note that the placement and nothrow forms of new are *not* implicitly 1162/// declared. Their use requires including \<new\>. 1163void Sema::DeclareGlobalNewDelete() { 1164 if (GlobalNewDeleteDeclared) 1165 return; 1166 1167 // C++ [basic.std.dynamic]p2: 1168 // [...] The following allocation and deallocation functions (18.4) are 1169 // implicitly declared in global scope in each translation unit of a 1170 // program 1171 // 1172 // void* operator new(std::size_t) throw(std::bad_alloc); 1173 // void* operator new[](std::size_t) throw(std::bad_alloc); 1174 // void operator delete(void*) throw(); 1175 // void operator delete[](void*) throw(); 1176 // 1177 // These implicit declarations introduce only the function names operator 1178 // new, operator new[], operator delete, operator delete[]. 1179 // 1180 // Here, we need to refer to std::bad_alloc, so we will implicitly declare 1181 // "std" or "bad_alloc" as necessary to form the exception specification. 1182 // However, we do not make these implicit declarations visible to name 1183 // lookup. 1184 if (!StdNamespace) { 1185 // The "std" namespace has not yet been defined, so build one implicitly. 1186 StdNamespace = NamespaceDecl::Create(Context, 1187 Context.getTranslationUnitDecl(), 1188 SourceLocation(), 1189 &PP.getIdentifierTable().get("std")); 1190 StdNamespace->setImplicit(true); 1191 } 1192 1193 if (!StdBadAlloc) { 1194 // The "std::bad_alloc" class has not yet been declared, so build it 1195 // implicitly. 1196 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class, 1197 StdNamespace, 1198 SourceLocation(), 1199 &PP.getIdentifierTable().get("bad_alloc"), 1200 SourceLocation(), 0); 1201 StdBadAlloc->setImplicit(true); 1202 } 1203 1204 GlobalNewDeleteDeclared = true; 1205 1206 QualType VoidPtr = Context.getPointerType(Context.VoidTy); 1207 QualType SizeT = Context.getSizeType(); 1208 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew; 1209 1210 DeclareGlobalAllocationFunction( 1211 Context.DeclarationNames.getCXXOperatorName(OO_New), 1212 VoidPtr, SizeT, AssumeSaneOperatorNew); 1213 DeclareGlobalAllocationFunction( 1214 Context.DeclarationNames.getCXXOperatorName(OO_Array_New), 1215 VoidPtr, SizeT, AssumeSaneOperatorNew); 1216 DeclareGlobalAllocationFunction( 1217 Context.DeclarationNames.getCXXOperatorName(OO_Delete), 1218 Context.VoidTy, VoidPtr); 1219 DeclareGlobalAllocationFunction( 1220 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete), 1221 Context.VoidTy, VoidPtr); 1222} 1223 1224/// DeclareGlobalAllocationFunction - Declares a single implicit global 1225/// allocation function if it doesn't already exist. 1226void Sema::DeclareGlobalAllocationFunction(DeclarationName Name, 1227 QualType Return, QualType Argument, 1228 bool AddMallocAttr) { 1229 DeclContext *GlobalCtx = Context.getTranslationUnitDecl(); 1230 1231 // Check if this function is already declared. 1232 { 1233 DeclContext::lookup_iterator Alloc, AllocEnd; 1234 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name); 1235 Alloc != AllocEnd; ++Alloc) { 1236 // Only look at non-template functions, as it is the predefined, 1237 // non-templated allocation function we are trying to declare here. 1238 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) { 1239 QualType InitialParamType = 1240 Context.getCanonicalType( 1241 Func->getParamDecl(0)->getType().getUnqualifiedType()); 1242 // FIXME: Do we need to check for default arguments here? 1243 if (Func->getNumParams() == 1 && InitialParamType == Argument) 1244 return; 1245 } 1246 } 1247 } 1248 1249 QualType BadAllocType; 1250 bool HasBadAllocExceptionSpec 1251 = (Name.getCXXOverloadedOperator() == OO_New || 1252 Name.getCXXOverloadedOperator() == OO_Array_New); 1253 if (HasBadAllocExceptionSpec) { 1254 assert(StdBadAlloc && "Must have std::bad_alloc declared"); 1255 BadAllocType = Context.getTypeDeclType(StdBadAlloc); 1256 } 1257 1258 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0, 1259 true, false, 1260 HasBadAllocExceptionSpec? 1 : 0, 1261 &BadAllocType, 1262 FunctionType::ExtInfo()); 1263 FunctionDecl *Alloc = 1264 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name, 1265 FnType, /*TInfo=*/0, FunctionDecl::None, 1266 FunctionDecl::None, false, true); 1267 Alloc->setImplicit(); 1268 1269 if (AddMallocAttr) 1270 Alloc->addAttr(::new (Context) MallocAttr()); 1271 1272 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(), 1273 0, Argument, /*TInfo=*/0, 1274 VarDecl::None, 1275 VarDecl::None, 0); 1276 Alloc->setParams(&Param, 1); 1277 1278 // FIXME: Also add this declaration to the IdentifierResolver, but 1279 // make sure it is at the end of the chain to coincide with the 1280 // global scope. 1281 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc); 1282} 1283 1284bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, 1285 DeclarationName Name, 1286 FunctionDecl* &Operator) { 1287 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName); 1288 // Try to find operator delete/operator delete[] in class scope. 1289 LookupQualifiedName(Found, RD); 1290 1291 if (Found.isAmbiguous()) 1292 return true; 1293 1294 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end(); 1295 F != FEnd; ++F) { 1296 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F)) 1297 if (Delete->isUsualDeallocationFunction()) { 1298 Operator = Delete; 1299 return false; 1300 } 1301 } 1302 1303 // We did find operator delete/operator delete[] declarations, but 1304 // none of them were suitable. 1305 if (!Found.empty()) { 1306 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found) 1307 << Name << RD; 1308 1309 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end(); 1310 F != FEnd; ++F) { 1311 Diag((*F)->getLocation(), diag::note_member_declared_here) 1312 << Name; 1313 } 1314 1315 return true; 1316 } 1317 1318 // Look for a global declaration. 1319 DeclareGlobalNewDelete(); 1320 DeclContext *TUDecl = Context.getTranslationUnitDecl(); 1321 1322 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation()); 1323 Expr* DeallocArgs[1]; 1324 DeallocArgs[0] = &Null; 1325 if (FindAllocationOverload(StartLoc, SourceRange(), Name, 1326 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false, 1327 Operator)) 1328 return true; 1329 1330 assert(Operator && "Did not find a deallocation function!"); 1331 return false; 1332} 1333 1334/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in: 1335/// @code ::delete ptr; @endcode 1336/// or 1337/// @code delete [] ptr; @endcode 1338Action::OwningExprResult 1339Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, 1340 bool ArrayForm, ExprArg Operand) { 1341 // C++ [expr.delete]p1: 1342 // The operand shall have a pointer type, or a class type having a single 1343 // conversion function to a pointer type. The result has type void. 1344 // 1345 // DR599 amends "pointer type" to "pointer to object type" in both cases. 1346 1347 FunctionDecl *OperatorDelete = 0; 1348 1349 Expr *Ex = (Expr *)Operand.get(); 1350 if (!Ex->isTypeDependent()) { 1351 QualType Type = Ex->getType(); 1352 1353 if (const RecordType *Record = Type->getAs<RecordType>()) { 1354 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions; 1355 1356 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1357 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions(); 1358 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 1359 E = Conversions->end(); I != E; ++I) { 1360 NamedDecl *D = I.getDecl(); 1361 if (isa<UsingShadowDecl>(D)) 1362 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 1363 1364 // Skip over templated conversion functions; they aren't considered. 1365 if (isa<FunctionTemplateDecl>(D)) 1366 continue; 1367 1368 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 1369 1370 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 1371 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 1372 if (ConvPtrType->getPointeeType()->isObjectType()) 1373 ObjectPtrConversions.push_back(Conv); 1374 } 1375 if (ObjectPtrConversions.size() == 1) { 1376 // We have a single conversion to a pointer-to-object type. Perform 1377 // that conversion. 1378 // TODO: don't redo the conversion calculation. 1379 Operand.release(); 1380 if (!PerformImplicitConversion(Ex, 1381 ObjectPtrConversions.front()->getConversionType(), 1382 AA_Converting)) { 1383 Operand = Owned(Ex); 1384 Type = Ex->getType(); 1385 } 1386 } 1387 else if (ObjectPtrConversions.size() > 1) { 1388 Diag(StartLoc, diag::err_ambiguous_delete_operand) 1389 << Type << Ex->getSourceRange(); 1390 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) 1391 NoteOverloadCandidate(ObjectPtrConversions[i]); 1392 return ExprError(); 1393 } 1394 } 1395 1396 if (!Type->isPointerType()) 1397 return ExprError(Diag(StartLoc, diag::err_delete_operand) 1398 << Type << Ex->getSourceRange()); 1399 1400 QualType Pointee = Type->getAs<PointerType>()->getPointeeType(); 1401 if (Pointee->isFunctionType() || Pointee->isVoidType()) 1402 return ExprError(Diag(StartLoc, diag::err_delete_operand) 1403 << Type << Ex->getSourceRange()); 1404 else if (!Pointee->isDependentType() && 1405 RequireCompleteType(StartLoc, Pointee, 1406 PDiag(diag::warn_delete_incomplete) 1407 << Ex->getSourceRange())) 1408 return ExprError(); 1409 1410 // C++ [expr.delete]p2: 1411 // [Note: a pointer to a const type can be the operand of a 1412 // delete-expression; it is not necessary to cast away the constness 1413 // (5.2.11) of the pointer expression before it is used as the operand 1414 // of the delete-expression. ] 1415 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy), 1416 CastExpr::CK_NoOp); 1417 1418 // Update the operand. 1419 Operand.take(); 1420 Operand = ExprArg(*this, Ex); 1421 1422 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( 1423 ArrayForm ? OO_Array_Delete : OO_Delete); 1424 1425 if (const RecordType *RT = Pointee->getAs<RecordType>()) { 1426 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 1427 1428 if (!UseGlobal && 1429 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete)) 1430 return ExprError(); 1431 1432 if (!RD->hasTrivialDestructor()) 1433 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context)) 1434 MarkDeclarationReferenced(StartLoc, 1435 const_cast<CXXDestructorDecl*>(Dtor)); 1436 } 1437 1438 if (!OperatorDelete) { 1439 // Look for a global declaration. 1440 DeclareGlobalNewDelete(); 1441 DeclContext *TUDecl = Context.getTranslationUnitDecl(); 1442 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName, 1443 &Ex, 1, TUDecl, /*AllowMissing=*/false, 1444 OperatorDelete)) 1445 return ExprError(); 1446 } 1447 1448 MarkDeclarationReferenced(StartLoc, OperatorDelete); 1449 1450 // FIXME: Check access and ambiguity of operator delete and destructor. 1451 } 1452 1453 Operand.release(); 1454 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm, 1455 OperatorDelete, Ex, StartLoc)); 1456} 1457 1458/// \brief Check the use of the given variable as a C++ condition in an if, 1459/// while, do-while, or switch statement. 1460Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar, 1461 SourceLocation StmtLoc, 1462 bool ConvertToBoolean) { 1463 QualType T = ConditionVar->getType(); 1464 1465 // C++ [stmt.select]p2: 1466 // The declarator shall not specify a function or an array. 1467 if (T->isFunctionType()) 1468 return ExprError(Diag(ConditionVar->getLocation(), 1469 diag::err_invalid_use_of_function_type) 1470 << ConditionVar->getSourceRange()); 1471 else if (T->isArrayType()) 1472 return ExprError(Diag(ConditionVar->getLocation(), 1473 diag::err_invalid_use_of_array_type) 1474 << ConditionVar->getSourceRange()); 1475 1476 Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar, 1477 ConditionVar->getLocation(), 1478 ConditionVar->getType().getNonReferenceType()); 1479 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc)) { 1480 Condition->Destroy(Context); 1481 return ExprError(); 1482 } 1483 1484 return Owned(Condition); 1485} 1486 1487/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid. 1488bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) { 1489 // C++ 6.4p4: 1490 // The value of a condition that is an initialized declaration in a statement 1491 // other than a switch statement is the value of the declared variable 1492 // implicitly converted to type bool. If that conversion is ill-formed, the 1493 // program is ill-formed. 1494 // The value of a condition that is an expression is the value of the 1495 // expression, implicitly converted to bool. 1496 // 1497 return PerformContextuallyConvertToBool(CondExpr); 1498} 1499 1500/// Helper function to determine whether this is the (deprecated) C++ 1501/// conversion from a string literal to a pointer to non-const char or 1502/// non-const wchar_t (for narrow and wide string literals, 1503/// respectively). 1504bool 1505Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) { 1506 // Look inside the implicit cast, if it exists. 1507 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From)) 1508 From = Cast->getSubExpr(); 1509 1510 // A string literal (2.13.4) that is not a wide string literal can 1511 // be converted to an rvalue of type "pointer to char"; a wide 1512 // string literal can be converted to an rvalue of type "pointer 1513 // to wchar_t" (C++ 4.2p2). 1514 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From)) 1515 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) 1516 if (const BuiltinType *ToPointeeType 1517 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) { 1518 // This conversion is considered only when there is an 1519 // explicit appropriate pointer target type (C++ 4.2p2). 1520 if (!ToPtrType->getPointeeType().hasQualifiers() && 1521 ((StrLit->isWide() && ToPointeeType->isWideCharType()) || 1522 (!StrLit->isWide() && 1523 (ToPointeeType->getKind() == BuiltinType::Char_U || 1524 ToPointeeType->getKind() == BuiltinType::Char_S)))) 1525 return true; 1526 } 1527 1528 return false; 1529} 1530 1531static Sema::OwningExprResult BuildCXXCastArgument(Sema &S, 1532 SourceLocation CastLoc, 1533 QualType Ty, 1534 CastExpr::CastKind Kind, 1535 CXXMethodDecl *Method, 1536 Sema::ExprArg Arg) { 1537 Expr *From = Arg.takeAs<Expr>(); 1538 1539 switch (Kind) { 1540 default: assert(0 && "Unhandled cast kind!"); 1541 case CastExpr::CK_ConstructorConversion: { 1542 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S); 1543 1544 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method), 1545 Sema::MultiExprArg(S, (void **)&From, 1), 1546 CastLoc, ConstructorArgs)) 1547 return S.ExprError(); 1548 1549 Sema::OwningExprResult Result = 1550 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method), 1551 move_arg(ConstructorArgs)); 1552 if (Result.isInvalid()) 1553 return S.ExprError(); 1554 1555 return S.MaybeBindToTemporary(Result.takeAs<Expr>()); 1556 } 1557 1558 case CastExpr::CK_UserDefinedConversion: { 1559 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!"); 1560 1561 // Create an implicit call expr that calls it. 1562 // FIXME: pass the FoundDecl for the user-defined conversion here 1563 CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method); 1564 return S.MaybeBindToTemporary(CE); 1565 } 1566 } 1567} 1568 1569/// PerformImplicitConversion - Perform an implicit conversion of the 1570/// expression From to the type ToType using the pre-computed implicit 1571/// conversion sequence ICS. Returns true if there was an error, false 1572/// otherwise. The expression From is replaced with the converted 1573/// expression. Action is the kind of conversion we're performing, 1574/// used in the error message. 1575bool 1576Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 1577 const ImplicitConversionSequence &ICS, 1578 AssignmentAction Action, bool IgnoreBaseAccess) { 1579 switch (ICS.getKind()) { 1580 case ImplicitConversionSequence::StandardConversion: 1581 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action, 1582 IgnoreBaseAccess)) 1583 return true; 1584 break; 1585 1586 case ImplicitConversionSequence::UserDefinedConversion: { 1587 1588 FunctionDecl *FD = ICS.UserDefined.ConversionFunction; 1589 CastExpr::CastKind CastKind = CastExpr::CK_Unknown; 1590 QualType BeforeToType; 1591 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) { 1592 CastKind = CastExpr::CK_UserDefinedConversion; 1593 1594 // If the user-defined conversion is specified by a conversion function, 1595 // the initial standard conversion sequence converts the source type to 1596 // the implicit object parameter of the conversion function. 1597 BeforeToType = Context.getTagDeclType(Conv->getParent()); 1598 } else if (const CXXConstructorDecl *Ctor = 1599 dyn_cast<CXXConstructorDecl>(FD)) { 1600 CastKind = CastExpr::CK_ConstructorConversion; 1601 // Do no conversion if dealing with ... for the first conversion. 1602 if (!ICS.UserDefined.EllipsisConversion) { 1603 // If the user-defined conversion is specified by a constructor, the 1604 // initial standard conversion sequence converts the source type to the 1605 // type required by the argument of the constructor 1606 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType(); 1607 } 1608 } 1609 else 1610 assert(0 && "Unknown conversion function kind!"); 1611 // Whatch out for elipsis conversion. 1612 if (!ICS.UserDefined.EllipsisConversion) { 1613 if (PerformImplicitConversion(From, BeforeToType, 1614 ICS.UserDefined.Before, AA_Converting, 1615 IgnoreBaseAccess)) 1616 return true; 1617 } 1618 1619 OwningExprResult CastArg 1620 = BuildCXXCastArgument(*this, 1621 From->getLocStart(), 1622 ToType.getNonReferenceType(), 1623 CastKind, cast<CXXMethodDecl>(FD), 1624 Owned(From)); 1625 1626 if (CastArg.isInvalid()) 1627 return true; 1628 1629 From = CastArg.takeAs<Expr>(); 1630 1631 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After, 1632 AA_Converting, IgnoreBaseAccess); 1633 } 1634 1635 case ImplicitConversionSequence::AmbiguousConversion: 1636 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(), 1637 PDiag(diag::err_typecheck_ambiguous_condition) 1638 << From->getSourceRange()); 1639 return true; 1640 1641 case ImplicitConversionSequence::EllipsisConversion: 1642 assert(false && "Cannot perform an ellipsis conversion"); 1643 return false; 1644 1645 case ImplicitConversionSequence::BadConversion: 1646 return true; 1647 } 1648 1649 // Everything went well. 1650 return false; 1651} 1652 1653/// PerformImplicitConversion - Perform an implicit conversion of the 1654/// expression From to the type ToType by following the standard 1655/// conversion sequence SCS. Returns true if there was an error, false 1656/// otherwise. The expression From is replaced with the converted 1657/// expression. Flavor is the context in which we're performing this 1658/// conversion, for use in error messages. 1659bool 1660Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 1661 const StandardConversionSequence& SCS, 1662 AssignmentAction Action, bool IgnoreBaseAccess) { 1663 // Overall FIXME: we are recomputing too many types here and doing far too 1664 // much extra work. What this means is that we need to keep track of more 1665 // information that is computed when we try the implicit conversion initially, 1666 // so that we don't need to recompute anything here. 1667 QualType FromType = From->getType(); 1668 1669 if (SCS.CopyConstructor) { 1670 // FIXME: When can ToType be a reference type? 1671 assert(!ToType->isReferenceType()); 1672 if (SCS.Second == ICK_Derived_To_Base) { 1673 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this); 1674 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor), 1675 MultiExprArg(*this, (void **)&From, 1), 1676 /*FIXME:ConstructLoc*/SourceLocation(), 1677 ConstructorArgs)) 1678 return true; 1679 OwningExprResult FromResult = 1680 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(), 1681 ToType, SCS.CopyConstructor, 1682 move_arg(ConstructorArgs)); 1683 if (FromResult.isInvalid()) 1684 return true; 1685 From = FromResult.takeAs<Expr>(); 1686 return false; 1687 } 1688 OwningExprResult FromResult = 1689 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(), 1690 ToType, SCS.CopyConstructor, 1691 MultiExprArg(*this, (void**)&From, 1)); 1692 1693 if (FromResult.isInvalid()) 1694 return true; 1695 1696 From = FromResult.takeAs<Expr>(); 1697 return false; 1698 } 1699 1700 // Resolve overloaded function references. 1701 if (Context.hasSameType(FromType, Context.OverloadTy)) { 1702 DeclAccessPair Found; 1703 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, 1704 true, Found); 1705 if (!Fn) 1706 return true; 1707 1708 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin())) 1709 return true; 1710 1711 From = FixOverloadedFunctionReference(From, Found, Fn); 1712 FromType = From->getType(); 1713 } 1714 1715 // Perform the first implicit conversion. 1716 switch (SCS.First) { 1717 case ICK_Identity: 1718 case ICK_Lvalue_To_Rvalue: 1719 // Nothing to do. 1720 break; 1721 1722 case ICK_Array_To_Pointer: 1723 FromType = Context.getArrayDecayedType(FromType); 1724 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay); 1725 break; 1726 1727 case ICK_Function_To_Pointer: 1728 FromType = Context.getPointerType(FromType); 1729 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay); 1730 break; 1731 1732 default: 1733 assert(false && "Improper first standard conversion"); 1734 break; 1735 } 1736 1737 // Perform the second implicit conversion 1738 switch (SCS.Second) { 1739 case ICK_Identity: 1740 // If both sides are functions (or pointers/references to them), there could 1741 // be incompatible exception declarations. 1742 if (CheckExceptionSpecCompatibility(From, ToType)) 1743 return true; 1744 // Nothing else to do. 1745 break; 1746 1747 case ICK_NoReturn_Adjustment: 1748 // If both sides are functions (or pointers/references to them), there could 1749 // be incompatible exception declarations. 1750 if (CheckExceptionSpecCompatibility(From, ToType)) 1751 return true; 1752 1753 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false), 1754 CastExpr::CK_NoOp); 1755 break; 1756 1757 case ICK_Integral_Promotion: 1758 case ICK_Integral_Conversion: 1759 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast); 1760 break; 1761 1762 case ICK_Floating_Promotion: 1763 case ICK_Floating_Conversion: 1764 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast); 1765 break; 1766 1767 case ICK_Complex_Promotion: 1768 case ICK_Complex_Conversion: 1769 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown); 1770 break; 1771 1772 case ICK_Floating_Integral: 1773 if (ToType->isFloatingType()) 1774 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating); 1775 else 1776 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral); 1777 break; 1778 1779 case ICK_Compatible_Conversion: 1780 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp); 1781 break; 1782 1783 case ICK_Pointer_Conversion: { 1784 if (SCS.IncompatibleObjC) { 1785 // Diagnose incompatible Objective-C conversions 1786 Diag(From->getSourceRange().getBegin(), 1787 diag::ext_typecheck_convert_incompatible_pointer) 1788 << From->getType() << ToType << Action 1789 << From->getSourceRange(); 1790 } 1791 1792 1793 CastExpr::CastKind Kind = CastExpr::CK_Unknown; 1794 CXXBaseSpecifierArray BasePath; 1795 if (CheckPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess)) 1796 return true; 1797 ImpCastExprToType(From, ToType, Kind, /*isLvalue=*/false, BasePath); 1798 break; 1799 } 1800 1801 case ICK_Pointer_Member: { 1802 CastExpr::CastKind Kind = CastExpr::CK_Unknown; 1803 CXXBaseSpecifierArray BasePath; 1804 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, 1805 IgnoreBaseAccess)) 1806 return true; 1807 if (CheckExceptionSpecCompatibility(From, ToType)) 1808 return true; 1809 ImpCastExprToType(From, ToType, Kind, /*isLvalue=*/false, BasePath); 1810 break; 1811 } 1812 case ICK_Boolean_Conversion: { 1813 CastExpr::CastKind Kind = CastExpr::CK_Unknown; 1814 if (FromType->isMemberPointerType()) 1815 Kind = CastExpr::CK_MemberPointerToBoolean; 1816 1817 ImpCastExprToType(From, Context.BoolTy, Kind); 1818 break; 1819 } 1820 1821 case ICK_Derived_To_Base: { 1822 CXXBaseSpecifierArray BasePath; 1823 if (CheckDerivedToBaseConversion(From->getType(), 1824 ToType.getNonReferenceType(), 1825 From->getLocStart(), 1826 From->getSourceRange(), 1827 &BasePath, 1828 IgnoreBaseAccess)) 1829 return true; 1830 1831 ImpCastExprToType(From, ToType.getNonReferenceType(), 1832 CastExpr::CK_DerivedToBase, 1833 /*isLvalue=*/(From->getType()->isRecordType() && 1834 From->isLvalue(Context) == Expr::LV_Valid), 1835 BasePath); 1836 break; 1837 } 1838 1839 case ICK_Vector_Conversion: 1840 ImpCastExprToType(From, ToType, CastExpr::CK_BitCast); 1841 break; 1842 1843 case ICK_Vector_Splat: 1844 ImpCastExprToType(From, ToType, CastExpr::CK_VectorSplat); 1845 break; 1846 1847 case ICK_Complex_Real: 1848 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown); 1849 break; 1850 1851 case ICK_Lvalue_To_Rvalue: 1852 case ICK_Array_To_Pointer: 1853 case ICK_Function_To_Pointer: 1854 case ICK_Qualification: 1855 case ICK_Num_Conversion_Kinds: 1856 assert(false && "Improper second standard conversion"); 1857 break; 1858 } 1859 1860 switch (SCS.Third) { 1861 case ICK_Identity: 1862 // Nothing to do. 1863 break; 1864 1865 case ICK_Qualification: 1866 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue 1867 // references. 1868 ImpCastExprToType(From, ToType.getNonReferenceType(), 1869 CastExpr::CK_NoOp, ToType->isLValueReferenceType()); 1870 1871 if (SCS.DeprecatedStringLiteralToCharPtr) 1872 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion) 1873 << ToType.getNonReferenceType(); 1874 1875 break; 1876 1877 default: 1878 assert(false && "Improper third standard conversion"); 1879 break; 1880 } 1881 1882 return false; 1883} 1884 1885Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT, 1886 SourceLocation KWLoc, 1887 SourceLocation LParen, 1888 TypeTy *Ty, 1889 SourceLocation RParen) { 1890 QualType T = GetTypeFromParser(Ty); 1891 1892 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html 1893 // all traits except __is_class, __is_enum and __is_union require a the type 1894 // to be complete. 1895 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) { 1896 if (RequireCompleteType(KWLoc, T, 1897 diag::err_incomplete_type_used_in_type_trait_expr)) 1898 return ExprError(); 1899 } 1900 1901 // There is no point in eagerly computing the value. The traits are designed 1902 // to be used from type trait templates, so Ty will be a template parameter 1903 // 99% of the time. 1904 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T, 1905 RParen, Context.BoolTy)); 1906} 1907 1908QualType Sema::CheckPointerToMemberOperands( 1909 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) { 1910 const char *OpSpelling = isIndirect ? "->*" : ".*"; 1911 // C++ 5.5p2 1912 // The binary operator .* [p3: ->*] binds its second operand, which shall 1913 // be of type "pointer to member of T" (where T is a completely-defined 1914 // class type) [...] 1915 QualType RType = rex->getType(); 1916 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>(); 1917 if (!MemPtr) { 1918 Diag(Loc, diag::err_bad_memptr_rhs) 1919 << OpSpelling << RType << rex->getSourceRange(); 1920 return QualType(); 1921 } 1922 1923 QualType Class(MemPtr->getClass(), 0); 1924 1925 if (RequireCompleteType(Loc, Class, diag::err_memptr_rhs_to_incomplete)) 1926 return QualType(); 1927 1928 // C++ 5.5p2 1929 // [...] to its first operand, which shall be of class T or of a class of 1930 // which T is an unambiguous and accessible base class. [p3: a pointer to 1931 // such a class] 1932 QualType LType = lex->getType(); 1933 if (isIndirect) { 1934 if (const PointerType *Ptr = LType->getAs<PointerType>()) 1935 LType = Ptr->getPointeeType().getNonReferenceType(); 1936 else { 1937 Diag(Loc, diag::err_bad_memptr_lhs) 1938 << OpSpelling << 1 << LType 1939 << FixItHint::CreateReplacement(SourceRange(Loc), ".*"); 1940 return QualType(); 1941 } 1942 } 1943 1944 if (!Context.hasSameUnqualifiedType(Class, LType)) { 1945 // If we want to check the hierarchy, we need a complete type. 1946 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs) 1947 << OpSpelling << (int)isIndirect)) { 1948 return QualType(); 1949 } 1950 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1951 /*DetectVirtual=*/false); 1952 // FIXME: Would it be useful to print full ambiguity paths, or is that 1953 // overkill? 1954 if (!IsDerivedFrom(LType, Class, Paths) || 1955 Paths.isAmbiguous(Context.getCanonicalType(Class))) { 1956 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling 1957 << (int)isIndirect << lex->getType(); 1958 return QualType(); 1959 } 1960 // Cast LHS to type of use. 1961 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class; 1962 bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid; 1963 1964 CXXBaseSpecifierArray BasePath; 1965 BuildBasePathArray(Paths, BasePath); 1966 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue, 1967 BasePath); 1968 } 1969 1970 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) { 1971 // Diagnose use of pointer-to-member type which when used as 1972 // the functional cast in a pointer-to-member expression. 1973 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect; 1974 return QualType(); 1975 } 1976 // C++ 5.5p2 1977 // The result is an object or a function of the type specified by the 1978 // second operand. 1979 // The cv qualifiers are the union of those in the pointer and the left side, 1980 // in accordance with 5.5p5 and 5.2.5. 1981 // FIXME: This returns a dereferenced member function pointer as a normal 1982 // function type. However, the only operation valid on such functions is 1983 // calling them. There's also a GCC extension to get a function pointer to the 1984 // thing, which is another complication, because this type - unlike the type 1985 // that is the result of this expression - takes the class as the first 1986 // argument. 1987 // We probably need a "MemberFunctionClosureType" or something like that. 1988 QualType Result = MemPtr->getPointeeType(); 1989 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers()); 1990 return Result; 1991} 1992 1993/// \brief Try to convert a type to another according to C++0x 5.16p3. 1994/// 1995/// This is part of the parameter validation for the ? operator. If either 1996/// value operand is a class type, the two operands are attempted to be 1997/// converted to each other. This function does the conversion in one direction. 1998/// It returns true if the program is ill-formed and has already been diagnosed 1999/// as such. 2000static bool TryClassUnification(Sema &Self, Expr *From, Expr *To, 2001 SourceLocation QuestionLoc, 2002 bool &HaveConversion, 2003 QualType &ToType) { 2004 HaveConversion = false; 2005 ToType = To->getType(); 2006 2007 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(), 2008 SourceLocation()); 2009 // C++0x 5.16p3 2010 // The process for determining whether an operand expression E1 of type T1 2011 // can be converted to match an operand expression E2 of type T2 is defined 2012 // as follows: 2013 // -- If E2 is an lvalue: 2014 bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid); 2015 if (ToIsLvalue) { 2016 // E1 can be converted to match E2 if E1 can be implicitly converted to 2017 // type "lvalue reference to T2", subject to the constraint that in the 2018 // conversion the reference must bind directly to E1. 2019 QualType T = Self.Context.getLValueReferenceType(ToType); 2020 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); 2021 2022 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1); 2023 if (InitSeq.isDirectReferenceBinding()) { 2024 ToType = T; 2025 HaveConversion = true; 2026 return false; 2027 } 2028 2029 if (InitSeq.isAmbiguous()) 2030 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1); 2031 } 2032 2033 // -- If E2 is an rvalue, or if the conversion above cannot be done: 2034 // -- if E1 and E2 have class type, and the underlying class types are 2035 // the same or one is a base class of the other: 2036 QualType FTy = From->getType(); 2037 QualType TTy = To->getType(); 2038 const RecordType *FRec = FTy->getAs<RecordType>(); 2039 const RecordType *TRec = TTy->getAs<RecordType>(); 2040 bool FDerivedFromT = FRec && TRec && FRec != TRec && 2041 Self.IsDerivedFrom(FTy, TTy); 2042 if (FRec && TRec && 2043 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) { 2044 // E1 can be converted to match E2 if the class of T2 is the 2045 // same type as, or a base class of, the class of T1, and 2046 // [cv2 > cv1]. 2047 if (FRec == TRec || FDerivedFromT) { 2048 if (TTy.isAtLeastAsQualifiedAs(FTy)) { 2049 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); 2050 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1); 2051 if (InitSeq.getKind() != InitializationSequence::FailedSequence) { 2052 HaveConversion = true; 2053 return false; 2054 } 2055 2056 if (InitSeq.isAmbiguous()) 2057 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1); 2058 } 2059 } 2060 2061 return false; 2062 } 2063 2064 // -- Otherwise: E1 can be converted to match E2 if E1 can be 2065 // implicitly converted to the type that expression E2 would have 2066 // if E2 were converted to an rvalue (or the type it has, if E2 is 2067 // an rvalue). 2068 // 2069 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not 2070 // to the array-to-pointer or function-to-pointer conversions. 2071 if (!TTy->getAs<TagType>()) 2072 TTy = TTy.getUnqualifiedType(); 2073 2074 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); 2075 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1); 2076 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence; 2077 ToType = TTy; 2078 if (InitSeq.isAmbiguous()) 2079 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1); 2080 2081 return false; 2082} 2083 2084/// \brief Try to find a common type for two according to C++0x 5.16p5. 2085/// 2086/// This is part of the parameter validation for the ? operator. If either 2087/// value operand is a class type, overload resolution is used to find a 2088/// conversion to a common type. 2089static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS, 2090 SourceLocation Loc) { 2091 Expr *Args[2] = { LHS, RHS }; 2092 OverloadCandidateSet CandidateSet(Loc); 2093 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet); 2094 2095 OverloadCandidateSet::iterator Best; 2096 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) { 2097 case OR_Success: 2098 // We found a match. Perform the conversions on the arguments and move on. 2099 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0], 2100 Best->Conversions[0], Sema::AA_Converting) || 2101 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1], 2102 Best->Conversions[1], Sema::AA_Converting)) 2103 break; 2104 return false; 2105 2106 case OR_No_Viable_Function: 2107 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 2108 << LHS->getType() << RHS->getType() 2109 << LHS->getSourceRange() << RHS->getSourceRange(); 2110 return true; 2111 2112 case OR_Ambiguous: 2113 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl) 2114 << LHS->getType() << RHS->getType() 2115 << LHS->getSourceRange() << RHS->getSourceRange(); 2116 // FIXME: Print the possible common types by printing the return types of 2117 // the viable candidates. 2118 break; 2119 2120 case OR_Deleted: 2121 assert(false && "Conditional operator has only built-in overloads"); 2122 break; 2123 } 2124 return true; 2125} 2126 2127/// \brief Perform an "extended" implicit conversion as returned by 2128/// TryClassUnification. 2129static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) { 2130 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); 2131 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(), 2132 SourceLocation()); 2133 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1); 2134 Sema::OwningExprResult Result = InitSeq.Perform(Self, Entity, Kind, 2135 Sema::MultiExprArg(Self, (void **)&E, 1)); 2136 if (Result.isInvalid()) 2137 return true; 2138 2139 E = Result.takeAs<Expr>(); 2140 return false; 2141} 2142 2143/// \brief Check the operands of ?: under C++ semantics. 2144/// 2145/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y 2146/// extension. In this case, LHS == Cond. (But they're not aliases.) 2147QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS, 2148 SourceLocation QuestionLoc) { 2149 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++ 2150 // interface pointers. 2151 2152 // C++0x 5.16p1 2153 // The first expression is contextually converted to bool. 2154 if (!Cond->isTypeDependent()) { 2155 if (CheckCXXBooleanCondition(Cond)) 2156 return QualType(); 2157 } 2158 2159 // Either of the arguments dependent? 2160 if (LHS->isTypeDependent() || RHS->isTypeDependent()) 2161 return Context.DependentTy; 2162 2163 // C++0x 5.16p2 2164 // If either the second or the third operand has type (cv) void, ... 2165 QualType LTy = LHS->getType(); 2166 QualType RTy = RHS->getType(); 2167 bool LVoid = LTy->isVoidType(); 2168 bool RVoid = RTy->isVoidType(); 2169 if (LVoid || RVoid) { 2170 // ... then the [l2r] conversions are performed on the second and third 2171 // operands ... 2172 DefaultFunctionArrayLvalueConversion(LHS); 2173 DefaultFunctionArrayLvalueConversion(RHS); 2174 LTy = LHS->getType(); 2175 RTy = RHS->getType(); 2176 2177 // ... and one of the following shall hold: 2178 // -- The second or the third operand (but not both) is a throw- 2179 // expression; the result is of the type of the other and is an rvalue. 2180 bool LThrow = isa<CXXThrowExpr>(LHS); 2181 bool RThrow = isa<CXXThrowExpr>(RHS); 2182 if (LThrow && !RThrow) 2183 return RTy; 2184 if (RThrow && !LThrow) 2185 return LTy; 2186 2187 // -- Both the second and third operands have type void; the result is of 2188 // type void and is an rvalue. 2189 if (LVoid && RVoid) 2190 return Context.VoidTy; 2191 2192 // Neither holds, error. 2193 Diag(QuestionLoc, diag::err_conditional_void_nonvoid) 2194 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1) 2195 << LHS->getSourceRange() << RHS->getSourceRange(); 2196 return QualType(); 2197 } 2198 2199 // Neither is void. 2200 2201 // C++0x 5.16p3 2202 // Otherwise, if the second and third operand have different types, and 2203 // either has (cv) class type, and attempt is made to convert each of those 2204 // operands to the other. 2205 if (!Context.hasSameType(LTy, RTy) && 2206 (LTy->isRecordType() || RTy->isRecordType())) { 2207 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft; 2208 // These return true if a single direction is already ambiguous. 2209 QualType L2RType, R2LType; 2210 bool HaveL2R, HaveR2L; 2211 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType)) 2212 return QualType(); 2213 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType)) 2214 return QualType(); 2215 2216 // If both can be converted, [...] the program is ill-formed. 2217 if (HaveL2R && HaveR2L) { 2218 Diag(QuestionLoc, diag::err_conditional_ambiguous) 2219 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange(); 2220 return QualType(); 2221 } 2222 2223 // If exactly one conversion is possible, that conversion is applied to 2224 // the chosen operand and the converted operands are used in place of the 2225 // original operands for the remainder of this section. 2226 if (HaveL2R) { 2227 if (ConvertForConditional(*this, LHS, L2RType)) 2228 return QualType(); 2229 LTy = LHS->getType(); 2230 } else if (HaveR2L) { 2231 if (ConvertForConditional(*this, RHS, R2LType)) 2232 return QualType(); 2233 RTy = RHS->getType(); 2234 } 2235 } 2236 2237 // C++0x 5.16p4 2238 // If the second and third operands are lvalues and have the same type, 2239 // the result is of that type [...] 2240 bool Same = Context.hasSameType(LTy, RTy); 2241 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid && 2242 RHS->isLvalue(Context) == Expr::LV_Valid) 2243 return LTy; 2244 2245 // C++0x 5.16p5 2246 // Otherwise, the result is an rvalue. If the second and third operands 2247 // do not have the same type, and either has (cv) class type, ... 2248 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) { 2249 // ... overload resolution is used to determine the conversions (if any) 2250 // to be applied to the operands. If the overload resolution fails, the 2251 // program is ill-formed. 2252 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc)) 2253 return QualType(); 2254 } 2255 2256 // C++0x 5.16p6 2257 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard 2258 // conversions are performed on the second and third operands. 2259 DefaultFunctionArrayLvalueConversion(LHS); 2260 DefaultFunctionArrayLvalueConversion(RHS); 2261 LTy = LHS->getType(); 2262 RTy = RHS->getType(); 2263 2264 // After those conversions, one of the following shall hold: 2265 // -- The second and third operands have the same type; the result 2266 // is of that type. If the operands have class type, the result 2267 // is a prvalue temporary of the result type, which is 2268 // copy-initialized from either the second operand or the third 2269 // operand depending on the value of the first operand. 2270 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) { 2271 if (LTy->isRecordType()) { 2272 // The operands have class type. Make a temporary copy. 2273 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy); 2274 OwningExprResult LHSCopy = PerformCopyInitialization(Entity, 2275 SourceLocation(), 2276 Owned(LHS)); 2277 if (LHSCopy.isInvalid()) 2278 return QualType(); 2279 2280 OwningExprResult RHSCopy = PerformCopyInitialization(Entity, 2281 SourceLocation(), 2282 Owned(RHS)); 2283 if (RHSCopy.isInvalid()) 2284 return QualType(); 2285 2286 LHS = LHSCopy.takeAs<Expr>(); 2287 RHS = RHSCopy.takeAs<Expr>(); 2288 } 2289 2290 return LTy; 2291 } 2292 2293 // Extension: conditional operator involving vector types. 2294 if (LTy->isVectorType() || RTy->isVectorType()) 2295 return CheckVectorOperands(QuestionLoc, LHS, RHS); 2296 2297 // -- The second and third operands have arithmetic or enumeration type; 2298 // the usual arithmetic conversions are performed to bring them to a 2299 // common type, and the result is of that type. 2300 if (LTy->isArithmeticType() && RTy->isArithmeticType()) { 2301 UsualArithmeticConversions(LHS, RHS); 2302 return LHS->getType(); 2303 } 2304 2305 // -- The second and third operands have pointer type, or one has pointer 2306 // type and the other is a null pointer constant; pointer conversions 2307 // and qualification conversions are performed to bring them to their 2308 // composite pointer type. The result is of the composite pointer type. 2309 // -- The second and third operands have pointer to member type, or one has 2310 // pointer to member type and the other is a null pointer constant; 2311 // pointer to member conversions and qualification conversions are 2312 // performed to bring them to a common type, whose cv-qualification 2313 // shall match the cv-qualification of either the second or the third 2314 // operand. The result is of the common type. 2315 bool NonStandardCompositeType = false; 2316 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS, 2317 isSFINAEContext()? 0 : &NonStandardCompositeType); 2318 if (!Composite.isNull()) { 2319 if (NonStandardCompositeType) 2320 Diag(QuestionLoc, 2321 diag::ext_typecheck_cond_incompatible_operands_nonstandard) 2322 << LTy << RTy << Composite 2323 << LHS->getSourceRange() << RHS->getSourceRange(); 2324 2325 return Composite; 2326 } 2327 2328 // Similarly, attempt to find composite type of two objective-c pointers. 2329 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc); 2330 if (!Composite.isNull()) 2331 return Composite; 2332 2333 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 2334 << LHS->getType() << RHS->getType() 2335 << LHS->getSourceRange() << RHS->getSourceRange(); 2336 return QualType(); 2337} 2338 2339/// \brief Find a merged pointer type and convert the two expressions to it. 2340/// 2341/// This finds the composite pointer type (or member pointer type) for @p E1 2342/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this 2343/// type and returns it. 2344/// It does not emit diagnostics. 2345/// 2346/// \param Loc The location of the operator requiring these two expressions to 2347/// be converted to the composite pointer type. 2348/// 2349/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find 2350/// a non-standard (but still sane) composite type to which both expressions 2351/// can be converted. When such a type is chosen, \c *NonStandardCompositeType 2352/// will be set true. 2353QualType Sema::FindCompositePointerType(SourceLocation Loc, 2354 Expr *&E1, Expr *&E2, 2355 bool *NonStandardCompositeType) { 2356 if (NonStandardCompositeType) 2357 *NonStandardCompositeType = false; 2358 2359 assert(getLangOptions().CPlusPlus && "This function assumes C++"); 2360 QualType T1 = E1->getType(), T2 = E2->getType(); 2361 2362 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() && 2363 !T2->isAnyPointerType() && !T2->isMemberPointerType()) 2364 return QualType(); 2365 2366 // C++0x 5.9p2 2367 // Pointer conversions and qualification conversions are performed on 2368 // pointer operands to bring them to their composite pointer type. If 2369 // one operand is a null pointer constant, the composite pointer type is 2370 // the type of the other operand. 2371 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 2372 if (T2->isMemberPointerType()) 2373 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer); 2374 else 2375 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer); 2376 return T2; 2377 } 2378 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 2379 if (T1->isMemberPointerType()) 2380 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer); 2381 else 2382 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer); 2383 return T1; 2384 } 2385 2386 // Now both have to be pointers or member pointers. 2387 if ((!T1->isPointerType() && !T1->isMemberPointerType()) || 2388 (!T2->isPointerType() && !T2->isMemberPointerType())) 2389 return QualType(); 2390 2391 // Otherwise, of one of the operands has type "pointer to cv1 void," then 2392 // the other has type "pointer to cv2 T" and the composite pointer type is 2393 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2. 2394 // Otherwise, the composite pointer type is a pointer type similar to the 2395 // type of one of the operands, with a cv-qualification signature that is 2396 // the union of the cv-qualification signatures of the operand types. 2397 // In practice, the first part here is redundant; it's subsumed by the second. 2398 // What we do here is, we build the two possible composite types, and try the 2399 // conversions in both directions. If only one works, or if the two composite 2400 // types are the same, we have succeeded. 2401 // FIXME: extended qualifiers? 2402 typedef llvm::SmallVector<unsigned, 4> QualifierVector; 2403 QualifierVector QualifierUnion; 2404 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4> 2405 ContainingClassVector; 2406 ContainingClassVector MemberOfClass; 2407 QualType Composite1 = Context.getCanonicalType(T1), 2408 Composite2 = Context.getCanonicalType(T2); 2409 unsigned NeedConstBefore = 0; 2410 do { 2411 const PointerType *Ptr1, *Ptr2; 2412 if ((Ptr1 = Composite1->getAs<PointerType>()) && 2413 (Ptr2 = Composite2->getAs<PointerType>())) { 2414 Composite1 = Ptr1->getPointeeType(); 2415 Composite2 = Ptr2->getPointeeType(); 2416 2417 // If we're allowed to create a non-standard composite type, keep track 2418 // of where we need to fill in additional 'const' qualifiers. 2419 if (NonStandardCompositeType && 2420 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers()) 2421 NeedConstBefore = QualifierUnion.size(); 2422 2423 QualifierUnion.push_back( 2424 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); 2425 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0)); 2426 continue; 2427 } 2428 2429 const MemberPointerType *MemPtr1, *MemPtr2; 2430 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) && 2431 (MemPtr2 = Composite2->getAs<MemberPointerType>())) { 2432 Composite1 = MemPtr1->getPointeeType(); 2433 Composite2 = MemPtr2->getPointeeType(); 2434 2435 // If we're allowed to create a non-standard composite type, keep track 2436 // of where we need to fill in additional 'const' qualifiers. 2437 if (NonStandardCompositeType && 2438 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers()) 2439 NeedConstBefore = QualifierUnion.size(); 2440 2441 QualifierUnion.push_back( 2442 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); 2443 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(), 2444 MemPtr2->getClass())); 2445 continue; 2446 } 2447 2448 // FIXME: block pointer types? 2449 2450 // Cannot unwrap any more types. 2451 break; 2452 } while (true); 2453 2454 if (NeedConstBefore && NonStandardCompositeType) { 2455 // Extension: Add 'const' to qualifiers that come before the first qualifier 2456 // mismatch, so that our (non-standard!) composite type meets the 2457 // requirements of C++ [conv.qual]p4 bullet 3. 2458 for (unsigned I = 0; I != NeedConstBefore; ++I) { 2459 if ((QualifierUnion[I] & Qualifiers::Const) == 0) { 2460 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const; 2461 *NonStandardCompositeType = true; 2462 } 2463 } 2464 } 2465 2466 // Rewrap the composites as pointers or member pointers with the union CVRs. 2467 ContainingClassVector::reverse_iterator MOC 2468 = MemberOfClass.rbegin(); 2469 for (QualifierVector::reverse_iterator 2470 I = QualifierUnion.rbegin(), 2471 E = QualifierUnion.rend(); 2472 I != E; (void)++I, ++MOC) { 2473 Qualifiers Quals = Qualifiers::fromCVRMask(*I); 2474 if (MOC->first && MOC->second) { 2475 // Rebuild member pointer type 2476 Composite1 = Context.getMemberPointerType( 2477 Context.getQualifiedType(Composite1, Quals), 2478 MOC->first); 2479 Composite2 = Context.getMemberPointerType( 2480 Context.getQualifiedType(Composite2, Quals), 2481 MOC->second); 2482 } else { 2483 // Rebuild pointer type 2484 Composite1 2485 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals)); 2486 Composite2 2487 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals)); 2488 } 2489 } 2490 2491 // Try to convert to the first composite pointer type. 2492 InitializedEntity Entity1 2493 = InitializedEntity::InitializeTemporary(Composite1); 2494 InitializationKind Kind 2495 = InitializationKind::CreateCopy(Loc, SourceLocation()); 2496 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1); 2497 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1); 2498 2499 if (E1ToC1 && E2ToC1) { 2500 // Conversion to Composite1 is viable. 2501 if (!Context.hasSameType(Composite1, Composite2)) { 2502 // Composite2 is a different type from Composite1. Check whether 2503 // Composite2 is also viable. 2504 InitializedEntity Entity2 2505 = InitializedEntity::InitializeTemporary(Composite2); 2506 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1); 2507 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1); 2508 if (E1ToC2 && E2ToC2) { 2509 // Both Composite1 and Composite2 are viable and are different; 2510 // this is an ambiguity. 2511 return QualType(); 2512 } 2513 } 2514 2515 // Convert E1 to Composite1 2516 OwningExprResult E1Result 2517 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E1,1)); 2518 if (E1Result.isInvalid()) 2519 return QualType(); 2520 E1 = E1Result.takeAs<Expr>(); 2521 2522 // Convert E2 to Composite1 2523 OwningExprResult E2Result 2524 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E2,1)); 2525 if (E2Result.isInvalid()) 2526 return QualType(); 2527 E2 = E2Result.takeAs<Expr>(); 2528 2529 return Composite1; 2530 } 2531 2532 // Check whether Composite2 is viable. 2533 InitializedEntity Entity2 2534 = InitializedEntity::InitializeTemporary(Composite2); 2535 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1); 2536 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1); 2537 if (!E1ToC2 || !E2ToC2) 2538 return QualType(); 2539 2540 // Convert E1 to Composite2 2541 OwningExprResult E1Result 2542 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E1, 1)); 2543 if (E1Result.isInvalid()) 2544 return QualType(); 2545 E1 = E1Result.takeAs<Expr>(); 2546 2547 // Convert E2 to Composite2 2548 OwningExprResult E2Result 2549 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E2, 1)); 2550 if (E2Result.isInvalid()) 2551 return QualType(); 2552 E2 = E2Result.takeAs<Expr>(); 2553 2554 return Composite2; 2555} 2556 2557Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) { 2558 if (!Context.getLangOptions().CPlusPlus) 2559 return Owned(E); 2560 2561 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?"); 2562 2563 const RecordType *RT = E->getType()->getAs<RecordType>(); 2564 if (!RT) 2565 return Owned(E); 2566 2567 // If this is the result of a call expression, our source might 2568 // actually be a reference, in which case we shouldn't bind. 2569 if (CallExpr *CE = dyn_cast<CallExpr>(E)) { 2570 QualType Ty = CE->getCallee()->getType(); 2571 if (const PointerType *PT = Ty->getAs<PointerType>()) 2572 Ty = PT->getPointeeType(); 2573 else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>()) 2574 Ty = BPT->getPointeeType(); 2575 2576 const FunctionType *FTy = Ty->getAs<FunctionType>(); 2577 if (FTy->getResultType()->isReferenceType()) 2578 return Owned(E); 2579 } 2580 2581 // That should be enough to guarantee that this type is complete. 2582 // If it has a trivial destructor, we can avoid the extra copy. 2583 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 2584 if (RD->hasTrivialDestructor()) 2585 return Owned(E); 2586 2587 CXXTemporary *Temp = CXXTemporary::Create(Context, 2588 RD->getDestructor(Context)); 2589 ExprTemporaries.push_back(Temp); 2590 if (CXXDestructorDecl *Destructor = 2591 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context))) { 2592 MarkDeclarationReferenced(E->getExprLoc(), Destructor); 2593 CheckDestructorAccess(E->getExprLoc(), Destructor, 2594 PDiag(diag::err_access_dtor_temp) 2595 << E->getType()); 2596 } 2597 // FIXME: Add the temporary to the temporaries vector. 2598 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E)); 2599} 2600 2601Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) { 2602 assert(SubExpr && "sub expression can't be null!"); 2603 2604 // Check any implicit conversions within the expression. 2605 CheckImplicitConversions(SubExpr); 2606 2607 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries; 2608 assert(ExprTemporaries.size() >= FirstTemporary); 2609 if (ExprTemporaries.size() == FirstTemporary) 2610 return SubExpr; 2611 2612 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr, 2613 &ExprTemporaries[FirstTemporary], 2614 ExprTemporaries.size() - FirstTemporary); 2615 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary, 2616 ExprTemporaries.end()); 2617 2618 return E; 2619} 2620 2621Sema::OwningExprResult 2622Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) { 2623 if (SubExpr.isInvalid()) 2624 return ExprError(); 2625 2626 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>())); 2627} 2628 2629FullExpr Sema::CreateFullExpr(Expr *SubExpr) { 2630 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries; 2631 assert(ExprTemporaries.size() >= FirstTemporary); 2632 2633 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary; 2634 CXXTemporary **Temporaries = 2635 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary]; 2636 2637 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries); 2638 2639 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary, 2640 ExprTemporaries.end()); 2641 2642 return E; 2643} 2644 2645Sema::OwningExprResult 2646Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc, 2647 tok::TokenKind OpKind, TypeTy *&ObjectType, 2648 bool &MayBePseudoDestructor) { 2649 // Since this might be a postfix expression, get rid of ParenListExprs. 2650 Base = MaybeConvertParenListExprToParenExpr(S, move(Base)); 2651 2652 Expr *BaseExpr = (Expr*)Base.get(); 2653 assert(BaseExpr && "no record expansion"); 2654 2655 QualType BaseType = BaseExpr->getType(); 2656 MayBePseudoDestructor = false; 2657 if (BaseType->isDependentType()) { 2658 // If we have a pointer to a dependent type and are using the -> operator, 2659 // the object type is the type that the pointer points to. We might still 2660 // have enough information about that type to do something useful. 2661 if (OpKind == tok::arrow) 2662 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) 2663 BaseType = Ptr->getPointeeType(); 2664 2665 ObjectType = BaseType.getAsOpaquePtr(); 2666 MayBePseudoDestructor = true; 2667 return move(Base); 2668 } 2669 2670 // C++ [over.match.oper]p8: 2671 // [...] When operator->returns, the operator-> is applied to the value 2672 // returned, with the original second operand. 2673 if (OpKind == tok::arrow) { 2674 // The set of types we've considered so far. 2675 llvm::SmallPtrSet<CanQualType,8> CTypes; 2676 llvm::SmallVector<SourceLocation, 8> Locations; 2677 CTypes.insert(Context.getCanonicalType(BaseType)); 2678 2679 while (BaseType->isRecordType()) { 2680 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc); 2681 BaseExpr = (Expr*)Base.get(); 2682 if (BaseExpr == NULL) 2683 return ExprError(); 2684 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr)) 2685 Locations.push_back(OpCall->getDirectCallee()->getLocation()); 2686 BaseType = BaseExpr->getType(); 2687 CanQualType CBaseType = Context.getCanonicalType(BaseType); 2688 if (!CTypes.insert(CBaseType)) { 2689 Diag(OpLoc, diag::err_operator_arrow_circular); 2690 for (unsigned i = 0; i < Locations.size(); i++) 2691 Diag(Locations[i], diag::note_declared_at); 2692 return ExprError(); 2693 } 2694 } 2695 2696 if (BaseType->isPointerType()) 2697 BaseType = BaseType->getPointeeType(); 2698 } 2699 2700 // We could end up with various non-record types here, such as extended 2701 // vector types or Objective-C interfaces. Just return early and let 2702 // ActOnMemberReferenceExpr do the work. 2703 if (!BaseType->isRecordType()) { 2704 // C++ [basic.lookup.classref]p2: 2705 // [...] If the type of the object expression is of pointer to scalar 2706 // type, the unqualified-id is looked up in the context of the complete 2707 // postfix-expression. 2708 // 2709 // This also indicates that we should be parsing a 2710 // pseudo-destructor-name. 2711 ObjectType = 0; 2712 MayBePseudoDestructor = true; 2713 return move(Base); 2714 } 2715 2716 // The object type must be complete (or dependent). 2717 if (!BaseType->isDependentType() && 2718 RequireCompleteType(OpLoc, BaseType, 2719 PDiag(diag::err_incomplete_member_access))) 2720 return ExprError(); 2721 2722 // C++ [basic.lookup.classref]p2: 2723 // If the id-expression in a class member access (5.2.5) is an 2724 // unqualified-id, and the type of the object expression is of a class 2725 // type C (or of pointer to a class type C), the unqualified-id is looked 2726 // up in the scope of class C. [...] 2727 ObjectType = BaseType.getAsOpaquePtr(); 2728 return move(Base); 2729} 2730 2731Sema::OwningExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc, 2732 ExprArg MemExpr) { 2733 Expr *E = (Expr *) MemExpr.get(); 2734 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc); 2735 Diag(E->getLocStart(), diag::err_dtor_expr_without_call) 2736 << isa<CXXPseudoDestructorExpr>(E) 2737 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()"); 2738 2739 return ActOnCallExpr(/*Scope*/ 0, 2740 move(MemExpr), 2741 /*LPLoc*/ ExpectedLParenLoc, 2742 Sema::MultiExprArg(*this, 0, 0), 2743 /*CommaLocs*/ 0, 2744 /*RPLoc*/ ExpectedLParenLoc); 2745} 2746 2747Sema::OwningExprResult Sema::BuildPseudoDestructorExpr(ExprArg Base, 2748 SourceLocation OpLoc, 2749 tok::TokenKind OpKind, 2750 const CXXScopeSpec &SS, 2751 TypeSourceInfo *ScopeTypeInfo, 2752 SourceLocation CCLoc, 2753 SourceLocation TildeLoc, 2754 PseudoDestructorTypeStorage Destructed, 2755 bool HasTrailingLParen) { 2756 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo(); 2757 2758 // C++ [expr.pseudo]p2: 2759 // The left-hand side of the dot operator shall be of scalar type. The 2760 // left-hand side of the arrow operator shall be of pointer to scalar type. 2761 // This scalar type is the object type. 2762 Expr *BaseE = (Expr *)Base.get(); 2763 QualType ObjectType = BaseE->getType(); 2764 if (OpKind == tok::arrow) { 2765 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) { 2766 ObjectType = Ptr->getPointeeType(); 2767 } else if (!BaseE->isTypeDependent()) { 2768 // The user wrote "p->" when she probably meant "p."; fix it. 2769 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 2770 << ObjectType << true 2771 << FixItHint::CreateReplacement(OpLoc, "."); 2772 if (isSFINAEContext()) 2773 return ExprError(); 2774 2775 OpKind = tok::period; 2776 } 2777 } 2778 2779 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) { 2780 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar) 2781 << ObjectType << BaseE->getSourceRange(); 2782 return ExprError(); 2783 } 2784 2785 // C++ [expr.pseudo]p2: 2786 // [...] The cv-unqualified versions of the object type and of the type 2787 // designated by the pseudo-destructor-name shall be the same type. 2788 if (DestructedTypeInfo) { 2789 QualType DestructedType = DestructedTypeInfo->getType(); 2790 SourceLocation DestructedTypeStart 2791 = DestructedTypeInfo->getTypeLoc().getSourceRange().getBegin(); 2792 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() && 2793 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) { 2794 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch) 2795 << ObjectType << DestructedType << BaseE->getSourceRange() 2796 << DestructedTypeInfo->getTypeLoc().getSourceRange(); 2797 2798 // Recover by setting the destructed type to the object type. 2799 DestructedType = ObjectType; 2800 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType, 2801 DestructedTypeStart); 2802 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 2803 } 2804 } 2805 2806 // C++ [expr.pseudo]p2: 2807 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the 2808 // form 2809 // 2810 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name 2811 // 2812 // shall designate the same scalar type. 2813 if (ScopeTypeInfo) { 2814 QualType ScopeType = ScopeTypeInfo->getType(); 2815 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() && 2816 !Context.hasSameType(ScopeType, ObjectType)) { 2817 2818 Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(), 2819 diag::err_pseudo_dtor_type_mismatch) 2820 << ObjectType << ScopeType << BaseE->getSourceRange() 2821 << ScopeTypeInfo->getTypeLoc().getSourceRange(); 2822 2823 ScopeType = QualType(); 2824 ScopeTypeInfo = 0; 2825 } 2826 } 2827 2828 OwningExprResult Result 2829 = Owned(new (Context) CXXPseudoDestructorExpr(Context, 2830 Base.takeAs<Expr>(), 2831 OpKind == tok::arrow, 2832 OpLoc, 2833 (NestedNameSpecifier *) SS.getScopeRep(), 2834 SS.getRange(), 2835 ScopeTypeInfo, 2836 CCLoc, 2837 TildeLoc, 2838 Destructed)); 2839 2840 if (HasTrailingLParen) 2841 return move(Result); 2842 2843 return DiagnoseDtorReference(Destructed.getLocation(), move(Result)); 2844} 2845 2846Sema::OwningExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, ExprArg Base, 2847 SourceLocation OpLoc, 2848 tok::TokenKind OpKind, 2849 CXXScopeSpec &SS, 2850 UnqualifiedId &FirstTypeName, 2851 SourceLocation CCLoc, 2852 SourceLocation TildeLoc, 2853 UnqualifiedId &SecondTypeName, 2854 bool HasTrailingLParen) { 2855 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId || 2856 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) && 2857 "Invalid first type name in pseudo-destructor"); 2858 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId || 2859 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) && 2860 "Invalid second type name in pseudo-destructor"); 2861 2862 Expr *BaseE = (Expr *)Base.get(); 2863 2864 // C++ [expr.pseudo]p2: 2865 // The left-hand side of the dot operator shall be of scalar type. The 2866 // left-hand side of the arrow operator shall be of pointer to scalar type. 2867 // This scalar type is the object type. 2868 QualType ObjectType = BaseE->getType(); 2869 if (OpKind == tok::arrow) { 2870 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) { 2871 ObjectType = Ptr->getPointeeType(); 2872 } else if (!ObjectType->isDependentType()) { 2873 // The user wrote "p->" when she probably meant "p."; fix it. 2874 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 2875 << ObjectType << true 2876 << FixItHint::CreateReplacement(OpLoc, "."); 2877 if (isSFINAEContext()) 2878 return ExprError(); 2879 2880 OpKind = tok::period; 2881 } 2882 } 2883 2884 // Compute the object type that we should use for name lookup purposes. Only 2885 // record types and dependent types matter. 2886 void *ObjectTypePtrForLookup = 0; 2887 if (!SS.isSet()) { 2888 ObjectTypePtrForLookup = (void *)ObjectType->getAs<RecordType>(); 2889 if (!ObjectTypePtrForLookup && ObjectType->isDependentType()) 2890 ObjectTypePtrForLookup = Context.DependentTy.getAsOpaquePtr(); 2891 } 2892 2893 // Convert the name of the type being destructed (following the ~) into a 2894 // type (with source-location information). 2895 QualType DestructedType; 2896 TypeSourceInfo *DestructedTypeInfo = 0; 2897 PseudoDestructorTypeStorage Destructed; 2898 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) { 2899 TypeTy *T = getTypeName(*SecondTypeName.Identifier, 2900 SecondTypeName.StartLocation, 2901 S, &SS, true, ObjectTypePtrForLookup); 2902 if (!T && 2903 ((SS.isSet() && !computeDeclContext(SS, false)) || 2904 (!SS.isSet() && ObjectType->isDependentType()))) { 2905 // The name of the type being destroyed is a dependent name, and we 2906 // couldn't find anything useful in scope. Just store the identifier and 2907 // it's location, and we'll perform (qualified) name lookup again at 2908 // template instantiation time. 2909 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier, 2910 SecondTypeName.StartLocation); 2911 } else if (!T) { 2912 Diag(SecondTypeName.StartLocation, 2913 diag::err_pseudo_dtor_destructor_non_type) 2914 << SecondTypeName.Identifier << ObjectType; 2915 if (isSFINAEContext()) 2916 return ExprError(); 2917 2918 // Recover by assuming we had the right type all along. 2919 DestructedType = ObjectType; 2920 } else 2921 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo); 2922 } else { 2923 // Resolve the template-id to a type. 2924 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId; 2925 ASTTemplateArgsPtr TemplateArgsPtr(*this, 2926 TemplateId->getTemplateArgs(), 2927 TemplateId->NumArgs); 2928 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template), 2929 TemplateId->TemplateNameLoc, 2930 TemplateId->LAngleLoc, 2931 TemplateArgsPtr, 2932 TemplateId->RAngleLoc); 2933 if (T.isInvalid() || !T.get()) { 2934 // Recover by assuming we had the right type all along. 2935 DestructedType = ObjectType; 2936 } else 2937 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo); 2938 } 2939 2940 // If we've performed some kind of recovery, (re-)build the type source 2941 // information. 2942 if (!DestructedType.isNull()) { 2943 if (!DestructedTypeInfo) 2944 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType, 2945 SecondTypeName.StartLocation); 2946 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 2947 } 2948 2949 // Convert the name of the scope type (the type prior to '::') into a type. 2950 TypeSourceInfo *ScopeTypeInfo = 0; 2951 QualType ScopeType; 2952 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId || 2953 FirstTypeName.Identifier) { 2954 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) { 2955 TypeTy *T = getTypeName(*FirstTypeName.Identifier, 2956 FirstTypeName.StartLocation, 2957 S, &SS, false, ObjectTypePtrForLookup); 2958 if (!T) { 2959 Diag(FirstTypeName.StartLocation, 2960 diag::err_pseudo_dtor_destructor_non_type) 2961 << FirstTypeName.Identifier << ObjectType; 2962 2963 if (isSFINAEContext()) 2964 return ExprError(); 2965 2966 // Just drop this type. It's unnecessary anyway. 2967 ScopeType = QualType(); 2968 } else 2969 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo); 2970 } else { 2971 // Resolve the template-id to a type. 2972 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId; 2973 ASTTemplateArgsPtr TemplateArgsPtr(*this, 2974 TemplateId->getTemplateArgs(), 2975 TemplateId->NumArgs); 2976 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template), 2977 TemplateId->TemplateNameLoc, 2978 TemplateId->LAngleLoc, 2979 TemplateArgsPtr, 2980 TemplateId->RAngleLoc); 2981 if (T.isInvalid() || !T.get()) { 2982 // Recover by dropping this type. 2983 ScopeType = QualType(); 2984 } else 2985 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo); 2986 } 2987 } 2988 2989 if (!ScopeType.isNull() && !ScopeTypeInfo) 2990 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType, 2991 FirstTypeName.StartLocation); 2992 2993 2994 return BuildPseudoDestructorExpr(move(Base), OpLoc, OpKind, SS, 2995 ScopeTypeInfo, CCLoc, TildeLoc, 2996 Destructed, HasTrailingLParen); 2997} 2998 2999CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp, 3000 NamedDecl *FoundDecl, 3001 CXXMethodDecl *Method) { 3002 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0, 3003 FoundDecl, Method)) 3004 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?"); 3005 3006 MemberExpr *ME = 3007 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method, 3008 SourceLocation(), Method->getType()); 3009 QualType ResultType = Method->getResultType().getNonReferenceType(); 3010 MarkDeclarationReferenced(Exp->getLocStart(), Method); 3011 CXXMemberCallExpr *CE = 3012 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, 3013 Exp->getLocEnd()); 3014 return CE; 3015} 3016 3017Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) { 3018 Expr *FullExpr = Arg.takeAs<Expr>(); 3019 if (FullExpr) 3020 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr); 3021 else 3022 return ExprError(); 3023 3024 return Owned(FullExpr); 3025} 3026