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