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