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