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