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