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