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