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