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