SemaExprCXX.cpp revision d1b47bf17fde73fac67d8664bd65273742c00ecd
1//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements semantic analysis for C++ expressions. 11// 12//===----------------------------------------------------------------------===// 13 14#include "Sema.h" 15#include "SemaInit.h" 16#include "Lookup.h" 17#include "clang/AST/ASTContext.h" 18#include "clang/AST/CXXInheritance.h" 19#include "clang/AST/ExprCXX.h" 20#include "clang/AST/TypeLoc.h" 21#include "clang/Basic/PartialDiagnostic.h" 22#include "clang/Basic/TargetInfo.h" 23#include "clang/Lex/Preprocessor.h" 24#include "clang/Parse/DeclSpec.h" 25#include "clang/Parse/Template.h" 26#include "llvm/ADT/STLExtras.h" 27using namespace clang; 28 29Action::TypeTy *Sema::getDestructorName(SourceLocation TildeLoc, 30 IdentifierInfo &II, 31 SourceLocation NameLoc, 32 Scope *S, const CXXScopeSpec &SS, 33 TypeTy *ObjectTypePtr, 34 bool EnteringContext) { 35 // Determine where to perform name lookup. 36 37 // FIXME: This area of the standard is very messy, and the current 38 // wording is rather unclear about which scopes we search for the 39 // destructor name; see core issues 399 and 555. Issue 399 in 40 // particular shows where the current description of destructor name 41 // lookup is completely out of line with existing practice, e.g., 42 // this appears to be ill-formed: 43 // 44 // namespace N { 45 // template <typename T> struct S { 46 // ~S(); 47 // }; 48 // } 49 // 50 // void f(N::S<int>* s) { 51 // s->N::S<int>::~S(); 52 // } 53 // 54 // See also PR6358 and PR6359. 55 QualType SearchType; 56 DeclContext *LookupCtx = 0; 57 bool isDependent = false; 58 bool LookInScope = false; 59 60 // If we have an object type, it's because we are in a 61 // pseudo-destructor-expression or a member access expression, and 62 // we know what type we're looking for. 63 if (ObjectTypePtr) 64 SearchType = GetTypeFromParser(ObjectTypePtr); 65 66 if (SS.isSet()) { 67 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep(); 68 69 bool AlreadySearched = false; 70 bool LookAtPrefix = true; 71 if (!getLangOptions().CPlusPlus0x) { 72 // C++ [basic.lookup.qual]p6: 73 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier, 74 // the type-names are looked up as types in the scope designated by the 75 // nested-name-specifier. In a qualified-id of the form: 76 // 77 // ::[opt] nested-name-specifier ̃ class-name 78 // 79 // where the nested-name-specifier designates a namespace scope, and in 80 // a qualified-id of the form: 81 // 82 // ::opt nested-name-specifier class-name :: ̃ class-name 83 // 84 // the class-names are looked up as types in the scope designated by 85 // the nested-name-specifier. 86 // 87 // Here, we check the first case (completely) and determine whether the 88 // code below is permitted to look at the prefix of the 89 // nested-name-specifier (as we do in C++0x). 90 DeclContext *DC = computeDeclContext(SS, EnteringContext); 91 if (DC && DC->isFileContext()) { 92 AlreadySearched = true; 93 LookupCtx = DC; 94 isDependent = false; 95 } else if (DC && isa<CXXRecordDecl>(DC)) 96 LookAtPrefix = false; 97 } 98 99 // C++0x [basic.lookup.qual]p6: 100 // If a pseudo-destructor-name (5.2.4) contains a 101 // nested-name-specifier, the type-names are looked up as types 102 // in the scope designated by the nested-name-specifier. Similarly, in 103 // a qualified-id of the form: 104 // 105 // :: [opt] nested-name-specifier[opt] class-name :: ~class-name 106 // 107 // the second class-name is looked up in the same scope as the first. 108 // 109 // To implement this, we look at the prefix of the 110 // nested-name-specifier we were given, and determine the lookup 111 // context from that. 112 // 113 // We also fold in the second case from the C++03 rules quoted further 114 // above. 115 NestedNameSpecifier *Prefix = 0; 116 if (AlreadySearched) { 117 // Nothing left to do. 118 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) { 119 CXXScopeSpec PrefixSS; 120 PrefixSS.setScopeRep(Prefix); 121 LookupCtx = computeDeclContext(PrefixSS, EnteringContext); 122 isDependent = isDependentScopeSpecifier(PrefixSS); 123 } else if (getLangOptions().CPlusPlus0x && 124 (LookupCtx = computeDeclContext(SS, EnteringContext))) { 125 if (!LookupCtx->isTranslationUnit()) 126 LookupCtx = LookupCtx->getParent(); 127 isDependent = LookupCtx && LookupCtx->isDependentContext(); 128 } else if (ObjectTypePtr) { 129 LookupCtx = computeDeclContext(SearchType); 130 isDependent = SearchType->isDependentType(); 131 } else { 132 LookupCtx = computeDeclContext(SS, EnteringContext); 133 isDependent = LookupCtx && LookupCtx->isDependentContext(); 134 } 135 136 LookInScope = false; 137 } else if (ObjectTypePtr) { 138 // C++ [basic.lookup.classref]p3: 139 // If the unqualified-id is ~type-name, the type-name is looked up 140 // in the context of the entire postfix-expression. If the type T 141 // of the object expression is of a class type C, the type-name is 142 // also looked up in the scope of class C. At least one of the 143 // lookups shall find a name that refers to (possibly 144 // cv-qualified) T. 145 LookupCtx = computeDeclContext(SearchType); 146 isDependent = SearchType->isDependentType(); 147 assert((isDependent || !SearchType->isIncompleteType()) && 148 "Caller should have completed object type"); 149 150 LookInScope = true; 151 } else { 152 // Perform lookup into the current scope (only). 153 LookInScope = true; 154 } 155 156 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName); 157 for (unsigned Step = 0; Step != 2; ++Step) { 158 // Look for the name first in the computed lookup context (if we 159 // have one) and, if that fails to find a match, in the sope (if 160 // we're allowed to look there). 161 Found.clear(); 162 if (Step == 0 && LookupCtx) 163 LookupQualifiedName(Found, LookupCtx); 164 else if (Step == 1 && LookInScope && S) 165 LookupName(Found, S); 166 else 167 continue; 168 169 // FIXME: Should we be suppressing ambiguities here? 170 if (Found.isAmbiguous()) 171 return 0; 172 173 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) { 174 QualType T = Context.getTypeDeclType(Type); 175 176 if (SearchType.isNull() || SearchType->isDependentType() || 177 Context.hasSameUnqualifiedType(T, SearchType)) { 178 // We found our type! 179 180 return T.getAsOpaquePtr(); 181 } 182 } 183 184 // If the name that we found is a class template name, and it is 185 // the same name as the template name in the last part of the 186 // nested-name-specifier (if present) or the object type, then 187 // this is the destructor for that class. 188 // FIXME: This is a workaround until we get real drafting for core 189 // issue 399, for which there isn't even an obvious direction. 190 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) { 191 QualType MemberOfType; 192 if (SS.isSet()) { 193 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) { 194 // Figure out the type of the context, if it has one. 195 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) 196 MemberOfType = Context.getTypeDeclType(Record); 197 } 198 } 199 if (MemberOfType.isNull()) 200 MemberOfType = SearchType; 201 202 if (MemberOfType.isNull()) 203 continue; 204 205 // We're referring into a class template specialization. If the 206 // class template we found is the same as the template being 207 // specialized, we found what we are looking for. 208 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) { 209 if (ClassTemplateSpecializationDecl *Spec 210 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { 211 if (Spec->getSpecializedTemplate()->getCanonicalDecl() == 212 Template->getCanonicalDecl()) 213 return MemberOfType.getAsOpaquePtr(); 214 } 215 216 continue; 217 } 218 219 // We're referring to an unresolved class template 220 // specialization. Determine whether we class template we found 221 // is the same as the template being specialized or, if we don't 222 // know which template is being specialized, that it at least 223 // has the same name. 224 if (const TemplateSpecializationType *SpecType 225 = MemberOfType->getAs<TemplateSpecializationType>()) { 226 TemplateName SpecName = SpecType->getTemplateName(); 227 228 // The class template we found is the same template being 229 // specialized. 230 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) { 231 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl()) 232 return MemberOfType.getAsOpaquePtr(); 233 234 continue; 235 } 236 237 // The class template we found has the same name as the 238 // (dependent) template name being specialized. 239 if (DependentTemplateName *DepTemplate 240 = SpecName.getAsDependentTemplateName()) { 241 if (DepTemplate->isIdentifier() && 242 DepTemplate->getIdentifier() == Template->getIdentifier()) 243 return MemberOfType.getAsOpaquePtr(); 244 245 continue; 246 } 247 } 248 } 249 } 250 251 if (isDependent) { 252 // We didn't find our type, but that's okay: it's dependent 253 // anyway. 254 NestedNameSpecifier *NNS = 0; 255 SourceRange Range; 256 if (SS.isSet()) { 257 NNS = (NestedNameSpecifier *)SS.getScopeRep(); 258 Range = SourceRange(SS.getRange().getBegin(), NameLoc); 259 } else { 260 NNS = NestedNameSpecifier::Create(Context, &II); 261 Range = SourceRange(NameLoc); 262 } 263 264 return CheckTypenameType(NNS, II, Range).getAsOpaquePtr(); 265 } 266 267 if (ObjectTypePtr) 268 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type) 269 << &II; 270 else 271 Diag(NameLoc, diag::err_destructor_class_name); 272 273 return 0; 274} 275 276/// ActOnCXXTypeidOfType - Parse typeid( type-id ). 277Action::OwningExprResult 278Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, 279 bool isType, void *TyOrExpr, SourceLocation RParenLoc) { 280 if (!StdNamespace) 281 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); 282 283 if (isType) { 284 // C++ [expr.typeid]p4: 285 // The top-level cv-qualifiers of the lvalue expression or the type-id 286 // that is the operand of typeid are always ignored. 287 // FIXME: Preserve type source info. 288 // FIXME: Preserve the type before we stripped the cv-qualifiers? 289 QualType T = GetTypeFromParser(TyOrExpr); 290 if (T.isNull()) 291 return ExprError(); 292 293 // C++ [expr.typeid]p4: 294 // If the type of the type-id is a class type or a reference to a class 295 // type, the class shall be completely-defined. 296 QualType CheckT = T; 297 if (const ReferenceType *RefType = CheckT->getAs<ReferenceType>()) 298 CheckT = RefType->getPointeeType(); 299 300 if (CheckT->getAs<RecordType>() && 301 RequireCompleteType(OpLoc, CheckT, diag::err_incomplete_typeid)) 302 return ExprError(); 303 304 TyOrExpr = T.getUnqualifiedType().getAsOpaquePtr(); 305 } 306 307 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info"); 308 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName); 309 LookupQualifiedName(R, StdNamespace); 310 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>(); 311 if (!TypeInfoRecordDecl) 312 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); 313 314 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl); 315 316 if (!isType) { 317 bool isUnevaluatedOperand = true; 318 Expr *E = static_cast<Expr *>(TyOrExpr); 319 if (E && !E->isTypeDependent()) { 320 QualType T = E->getType(); 321 if (const RecordType *RecordT = T->getAs<RecordType>()) { 322 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl()); 323 // C++ [expr.typeid]p3: 324 // [...] If the type of the expression is a class type, the class 325 // shall be completely-defined. 326 if (RequireCompleteType(OpLoc, T, diag::err_incomplete_typeid)) 327 return ExprError(); 328 329 // C++ [expr.typeid]p3: 330 // When typeid is applied to an expression other than an lvalue of a 331 // polymorphic class type [...] [the] expression is an unevaluated 332 // operand. [...] 333 if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid) 334 isUnevaluatedOperand = false; 335 } 336 337 // C++ [expr.typeid]p4: 338 // [...] If the type of the type-id is a reference to a possibly 339 // cv-qualified type, the result of the typeid expression refers to a 340 // std::type_info object representing the cv-unqualified referenced 341 // type. 342 if (T.hasQualifiers()) { 343 ImpCastExprToType(E, T.getUnqualifiedType(), CastExpr::CK_NoOp, 344 E->isLvalue(Context)); 345 TyOrExpr = E; 346 } 347 } 348 349 // If this is an unevaluated operand, clear out the set of 350 // declaration references we have been computing and eliminate any 351 // temporaries introduced in its computation. 352 if (isUnevaluatedOperand) 353 ExprEvalContexts.back().Context = Unevaluated; 354 } 355 356 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr, 357 TypeInfoType.withConst(), 358 SourceRange(OpLoc, RParenLoc))); 359} 360 361/// ActOnCXXBoolLiteral - Parse {true,false} literals. 362Action::OwningExprResult 363Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 364 assert((Kind == tok::kw_true || Kind == tok::kw_false) && 365 "Unknown C++ Boolean value!"); 366 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true, 367 Context.BoolTy, OpLoc)); 368} 369 370/// ActOnCXXNullPtrLiteral - Parse 'nullptr'. 371Action::OwningExprResult 372Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) { 373 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc)); 374} 375 376/// ActOnCXXThrow - Parse throw expressions. 377Action::OwningExprResult 378Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) { 379 Expr *Ex = E.takeAs<Expr>(); 380 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex)) 381 return ExprError(); 382 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc)); 383} 384 385/// CheckCXXThrowOperand - Validate the operand of a throw. 386bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) { 387 // C++ [except.throw]p3: 388 // A throw-expression initializes a temporary object, called the exception 389 // object, the type of which is determined by removing any top-level 390 // cv-qualifiers from the static type of the operand of throw and adjusting 391 // the type from "array of T" or "function returning T" to "pointer to T" 392 // or "pointer to function returning T", [...] 393 if (E->getType().hasQualifiers()) 394 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp, 395 E->isLvalue(Context) == Expr::LV_Valid); 396 397 DefaultFunctionArrayConversion(E); 398 399 // If the type of the exception would be an incomplete type or a pointer 400 // to an incomplete type other than (cv) void the program is ill-formed. 401 QualType Ty = E->getType(); 402 int isPointer = 0; 403 if (const PointerType* Ptr = Ty->getAs<PointerType>()) { 404 Ty = Ptr->getPointeeType(); 405 isPointer = 1; 406 } 407 if (!isPointer || !Ty->isVoidType()) { 408 if (RequireCompleteType(ThrowLoc, Ty, 409 PDiag(isPointer ? diag::err_throw_incomplete_ptr 410 : diag::err_throw_incomplete) 411 << E->getSourceRange())) 412 return true; 413 414 // FIXME: This is just a hack to mark the copy constructor referenced. 415 // This should go away when the next FIXME is fixed. 416 const RecordType *RT = Ty->getAs<RecordType>(); 417 if (!RT) 418 return false; 419 420 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 421 if (RD->hasTrivialCopyConstructor()) 422 return false; 423 CXXConstructorDecl *CopyCtor = RD->getCopyConstructor(Context, 0); 424 MarkDeclarationReferenced(ThrowLoc, CopyCtor); 425 } 426 427 // FIXME: Construct a temporary here. 428 return false; 429} 430 431Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) { 432 /// C++ 9.3.2: In the body of a non-static member function, the keyword this 433 /// is a non-lvalue expression whose value is the address of the object for 434 /// which the function is called. 435 436 if (!isa<FunctionDecl>(CurContext)) 437 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use)); 438 439 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) 440 if (MD->isInstance()) 441 return Owned(new (Context) CXXThisExpr(ThisLoc, 442 MD->getThisType(Context), 443 /*isImplicit=*/false)); 444 445 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use)); 446} 447 448/// ActOnCXXTypeConstructExpr - Parse construction of a specified type. 449/// Can be interpreted either as function-style casting ("int(x)") 450/// or class type construction ("ClassType(x,y,z)") 451/// or creation of a value-initialized type ("int()"). 452Action::OwningExprResult 453Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep, 454 SourceLocation LParenLoc, 455 MultiExprArg exprs, 456 SourceLocation *CommaLocs, 457 SourceLocation RParenLoc) { 458 if (!TypeRep) 459 return ExprError(); 460 461 TypeSourceInfo *TInfo; 462 QualType Ty = GetTypeFromParser(TypeRep, &TInfo); 463 if (!TInfo) 464 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation()); 465 unsigned NumExprs = exprs.size(); 466 Expr **Exprs = (Expr**)exprs.get(); 467 SourceLocation TyBeginLoc = TypeRange.getBegin(); 468 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc); 469 470 if (Ty->isDependentType() || 471 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) { 472 exprs.release(); 473 474 return Owned(CXXUnresolvedConstructExpr::Create(Context, 475 TypeRange.getBegin(), Ty, 476 LParenLoc, 477 Exprs, NumExprs, 478 RParenLoc)); 479 } 480 481 if (Ty->isArrayType()) 482 return ExprError(Diag(TyBeginLoc, 483 diag::err_value_init_for_array_type) << FullRange); 484 if (!Ty->isVoidType() && 485 RequireCompleteType(TyBeginLoc, Ty, 486 PDiag(diag::err_invalid_incomplete_type_use) 487 << FullRange)) 488 return ExprError(); 489 490 if (RequireNonAbstractType(TyBeginLoc, Ty, 491 diag::err_allocation_of_abstract_type)) 492 return ExprError(); 493 494 495 // C++ [expr.type.conv]p1: 496 // If the expression list is a single expression, the type conversion 497 // expression is equivalent (in definedness, and if defined in meaning) to the 498 // corresponding cast expression. 499 // 500 if (NumExprs == 1) { 501 CastExpr::CastKind Kind = CastExpr::CK_Unknown; 502 CXXMethodDecl *Method = 0; 503 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method, 504 /*FunctionalStyle=*/true)) 505 return ExprError(); 506 507 exprs.release(); 508 if (Method) { 509 OwningExprResult CastArg 510 = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(), 511 Kind, Method, Owned(Exprs[0])); 512 if (CastArg.isInvalid()) 513 return ExprError(); 514 515 Exprs[0] = CastArg.takeAs<Expr>(); 516 } 517 518 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(), 519 TInfo, TyBeginLoc, Kind, 520 Exprs[0], RParenLoc)); 521 } 522 523 if (const RecordType *RT = Ty->getAs<RecordType>()) { 524 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl()); 525 526 if (NumExprs > 1 || !Record->hasTrivialConstructor() || 527 !Record->hasTrivialDestructor()) { 528 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 529 InitializationKind Kind 530 = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(), 531 LParenLoc, RParenLoc) 532 : InitializationKind::CreateValue(TypeRange.getBegin(), 533 LParenLoc, RParenLoc); 534 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs); 535 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, 536 move(exprs)); 537 538 // FIXME: Improve AST representation? 539 return move(Result); 540 } 541 542 // Fall through to value-initialize an object of class type that 543 // doesn't have a user-declared default constructor. 544 } 545 546 // C++ [expr.type.conv]p1: 547 // If the expression list specifies more than a single value, the type shall 548 // be a class with a suitably declared constructor. 549 // 550 if (NumExprs > 1) 551 return ExprError(Diag(CommaLocs[0], 552 diag::err_builtin_func_cast_more_than_one_arg) 553 << FullRange); 554 555 assert(NumExprs == 0 && "Expected 0 expressions"); 556 // C++ [expr.type.conv]p2: 557 // The expression T(), where T is a simple-type-specifier for a non-array 558 // complete object type or the (possibly cv-qualified) void type, creates an 559 // rvalue of the specified type, which is value-initialized. 560 // 561 exprs.release(); 562 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc)); 563} 564 565 566/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.: 567/// @code new (memory) int[size][4] @endcode 568/// or 569/// @code ::new Foo(23, "hello") @endcode 570/// For the interpretation of this heap of arguments, consult the base version. 571Action::OwningExprResult 572Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 573 SourceLocation PlacementLParen, MultiExprArg PlacementArgs, 574 SourceLocation PlacementRParen, bool ParenTypeId, 575 Declarator &D, SourceLocation ConstructorLParen, 576 MultiExprArg ConstructorArgs, 577 SourceLocation ConstructorRParen) { 578 Expr *ArraySize = 0; 579 // If the specified type is an array, unwrap it and save the expression. 580 if (D.getNumTypeObjects() > 0 && 581 D.getTypeObject(0).Kind == DeclaratorChunk::Array) { 582 DeclaratorChunk &Chunk = D.getTypeObject(0); 583 if (Chunk.Arr.hasStatic) 584 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new) 585 << D.getSourceRange()); 586 if (!Chunk.Arr.NumElts) 587 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size) 588 << D.getSourceRange()); 589 590 if (ParenTypeId) { 591 // Can't have dynamic array size when the type-id is in parentheses. 592 Expr *NumElts = (Expr *)Chunk.Arr.NumElts; 593 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() && 594 !NumElts->isIntegerConstantExpr(Context)) { 595 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst) 596 << NumElts->getSourceRange(); 597 return ExprError(); 598 } 599 } 600 601 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts); 602 D.DropFirstTypeObject(); 603 } 604 605 // Every dimension shall be of constant size. 606 if (ArraySize) { 607 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) { 608 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array) 609 break; 610 611 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr; 612 if (Expr *NumElts = (Expr *)Array.NumElts) { 613 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() && 614 !NumElts->isIntegerConstantExpr(Context)) { 615 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst) 616 << NumElts->getSourceRange(); 617 return ExprError(); 618 } 619 } 620 } 621 } 622 623 //FIXME: Store TypeSourceInfo in CXXNew expression. 624 TypeSourceInfo *TInfo = 0; 625 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo); 626 if (D.isInvalidType()) 627 return ExprError(); 628 629 return BuildCXXNew(StartLoc, UseGlobal, 630 PlacementLParen, 631 move(PlacementArgs), 632 PlacementRParen, 633 ParenTypeId, 634 AllocType, 635 D.getSourceRange().getBegin(), 636 D.getSourceRange(), 637 Owned(ArraySize), 638 ConstructorLParen, 639 move(ConstructorArgs), 640 ConstructorRParen); 641} 642 643Sema::OwningExprResult 644Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal, 645 SourceLocation PlacementLParen, 646 MultiExprArg PlacementArgs, 647 SourceLocation PlacementRParen, 648 bool ParenTypeId, 649 QualType AllocType, 650 SourceLocation TypeLoc, 651 SourceRange TypeRange, 652 ExprArg ArraySizeE, 653 SourceLocation ConstructorLParen, 654 MultiExprArg ConstructorArgs, 655 SourceLocation ConstructorRParen) { 656 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange)) 657 return ExprError(); 658 659 QualType ResultType = Context.getPointerType(AllocType); 660 661 // That every array dimension except the first is constant was already 662 // checked by the type check above. 663 664 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral 665 // or enumeration type with a non-negative value." 666 Expr *ArraySize = (Expr *)ArraySizeE.get(); 667 if (ArraySize && !ArraySize->isTypeDependent()) { 668 QualType SizeType = ArraySize->getType(); 669 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType()) 670 return ExprError(Diag(ArraySize->getSourceRange().getBegin(), 671 diag::err_array_size_not_integral) 672 << SizeType << ArraySize->getSourceRange()); 673 // Let's see if this is a constant < 0. If so, we reject it out of hand. 674 // We don't care about special rules, so we tell the machinery it's not 675 // evaluated - it gives us a result in more cases. 676 if (!ArraySize->isValueDependent()) { 677 llvm::APSInt Value; 678 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) { 679 if (Value < llvm::APSInt( 680 llvm::APInt::getNullValue(Value.getBitWidth()), 681 Value.isUnsigned())) 682 return ExprError(Diag(ArraySize->getSourceRange().getBegin(), 683 diag::err_typecheck_negative_array_size) 684 << ArraySize->getSourceRange()); 685 } 686 } 687 688 ImpCastExprToType(ArraySize, Context.getSizeType(), 689 CastExpr::CK_IntegralCast); 690 } 691 692 FunctionDecl *OperatorNew = 0; 693 FunctionDecl *OperatorDelete = 0; 694 Expr **PlaceArgs = (Expr**)PlacementArgs.get(); 695 unsigned NumPlaceArgs = PlacementArgs.size(); 696 697 if (!AllocType->isDependentType() && 698 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) && 699 FindAllocationFunctions(StartLoc, 700 SourceRange(PlacementLParen, PlacementRParen), 701 UseGlobal, AllocType, ArraySize, PlaceArgs, 702 NumPlaceArgs, OperatorNew, OperatorDelete)) 703 return ExprError(); 704 llvm::SmallVector<Expr *, 8> AllPlaceArgs; 705 if (OperatorNew) { 706 // Add default arguments, if any. 707 const FunctionProtoType *Proto = 708 OperatorNew->getType()->getAs<FunctionProtoType>(); 709 VariadicCallType CallType = 710 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply; 711 bool Invalid = GatherArgumentsForCall(PlacementLParen, OperatorNew, 712 Proto, 1, PlaceArgs, NumPlaceArgs, 713 AllPlaceArgs, CallType); 714 if (Invalid) 715 return ExprError(); 716 717 NumPlaceArgs = AllPlaceArgs.size(); 718 if (NumPlaceArgs > 0) 719 PlaceArgs = &AllPlaceArgs[0]; 720 } 721 722 bool Init = ConstructorLParen.isValid(); 723 // --- Choosing a constructor --- 724 CXXConstructorDecl *Constructor = 0; 725 Expr **ConsArgs = (Expr**)ConstructorArgs.get(); 726 unsigned NumConsArgs = ConstructorArgs.size(); 727 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this); 728 729 if (!AllocType->isDependentType() && 730 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) { 731 // C++0x [expr.new]p15: 732 // A new-expression that creates an object of type T initializes that 733 // object as follows: 734 InitializationKind Kind 735 // - If the new-initializer is omitted, the object is default- 736 // initialized (8.5); if no initialization is performed, 737 // the object has indeterminate value 738 = !Init? InitializationKind::CreateDefault(TypeLoc) 739 // - Otherwise, the new-initializer is interpreted according to the 740 // initialization rules of 8.5 for direct-initialization. 741 : InitializationKind::CreateDirect(TypeLoc, 742 ConstructorLParen, 743 ConstructorRParen); 744 745 InitializedEntity Entity 746 = InitializedEntity::InitializeNew(StartLoc, AllocType); 747 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs); 748 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, 749 move(ConstructorArgs)); 750 if (FullInit.isInvalid()) 751 return ExprError(); 752 753 // FullInit is our initializer; walk through it to determine if it's a 754 // constructor call, which CXXNewExpr handles directly. 755 if (Expr *FullInitExpr = (Expr *)FullInit.get()) { 756 if (CXXBindTemporaryExpr *Binder 757 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr)) 758 FullInitExpr = Binder->getSubExpr(); 759 if (CXXConstructExpr *Construct 760 = dyn_cast<CXXConstructExpr>(FullInitExpr)) { 761 Constructor = Construct->getConstructor(); 762 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(), 763 AEnd = Construct->arg_end(); 764 A != AEnd; ++A) 765 ConvertedConstructorArgs.push_back(A->Retain()); 766 } else { 767 // Take the converted initializer. 768 ConvertedConstructorArgs.push_back(FullInit.release()); 769 } 770 } else { 771 // No initialization required. 772 } 773 774 // Take the converted arguments and use them for the new expression. 775 NumConsArgs = ConvertedConstructorArgs.size(); 776 ConsArgs = (Expr **)ConvertedConstructorArgs.take(); 777 } 778 779 // Mark the new and delete operators as referenced. 780 if (OperatorNew) 781 MarkDeclarationReferenced(StartLoc, OperatorNew); 782 if (OperatorDelete) 783 MarkDeclarationReferenced(StartLoc, OperatorDelete); 784 785 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16) 786 787 PlacementArgs.release(); 788 ConstructorArgs.release(); 789 ArraySizeE.release(); 790 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew, 791 PlaceArgs, NumPlaceArgs, ParenTypeId, 792 ArraySize, Constructor, Init, 793 ConsArgs, NumConsArgs, OperatorDelete, 794 ResultType, StartLoc, 795 Init ? ConstructorRParen : 796 SourceLocation())); 797} 798 799/// CheckAllocatedType - Checks that a type is suitable as the allocated type 800/// in a new-expression. 801/// dimension off and stores the size expression in ArraySize. 802bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc, 803 SourceRange R) { 804 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an 805 // abstract class type or array thereof. 806 if (AllocType->isFunctionType()) 807 return Diag(Loc, diag::err_bad_new_type) 808 << AllocType << 0 << R; 809 else if (AllocType->isReferenceType()) 810 return Diag(Loc, diag::err_bad_new_type) 811 << AllocType << 1 << R; 812 else if (!AllocType->isDependentType() && 813 RequireCompleteType(Loc, AllocType, 814 PDiag(diag::err_new_incomplete_type) 815 << R)) 816 return true; 817 else if (RequireNonAbstractType(Loc, AllocType, 818 diag::err_allocation_of_abstract_type)) 819 return true; 820 821 return false; 822} 823 824/// \brief Determine whether the given function is a non-placement 825/// deallocation function. 826static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) { 827 if (FD->isInvalidDecl()) 828 return false; 829 830 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD)) 831 return Method->isUsualDeallocationFunction(); 832 833 return ((FD->getOverloadedOperator() == OO_Delete || 834 FD->getOverloadedOperator() == OO_Array_Delete) && 835 FD->getNumParams() == 1); 836} 837 838/// FindAllocationFunctions - Finds the overloads of operator new and delete 839/// that are appropriate for the allocation. 840bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 841 bool UseGlobal, QualType AllocType, 842 bool IsArray, Expr **PlaceArgs, 843 unsigned NumPlaceArgs, 844 FunctionDecl *&OperatorNew, 845 FunctionDecl *&OperatorDelete) { 846 // --- Choosing an allocation function --- 847 // C++ 5.3.4p8 - 14 & 18 848 // 1) If UseGlobal is true, only look in the global scope. Else, also look 849 // in the scope of the allocated class. 850 // 2) If an array size is given, look for operator new[], else look for 851 // operator new. 852 // 3) The first argument is always size_t. Append the arguments from the 853 // placement form. 854 855 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs); 856 // We don't care about the actual value of this argument. 857 // FIXME: Should the Sema create the expression and embed it in the syntax 858 // tree? Or should the consumer just recalculate the value? 859 IntegerLiteral Size(llvm::APInt::getNullValue( 860 Context.Target.getPointerWidth(0)), 861 Context.getSizeType(), 862 SourceLocation()); 863 AllocArgs[0] = &Size; 864 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1); 865 866 // C++ [expr.new]p8: 867 // If the allocated type is a non-array type, the allocation 868 // function’s name is operator new and the deallocation function’s 869 // name is operator delete. If the allocated type is an array 870 // type, the allocation function’s name is operator new[] and the 871 // deallocation function’s name is operator delete[]. 872 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName( 873 IsArray ? OO_Array_New : OO_New); 874 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( 875 IsArray ? OO_Array_Delete : OO_Delete); 876 877 if (AllocType->isRecordType() && !UseGlobal) { 878 CXXRecordDecl *Record 879 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl()); 880 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0], 881 AllocArgs.size(), Record, /*AllowMissing=*/true, 882 OperatorNew)) 883 return true; 884 } 885 if (!OperatorNew) { 886 // Didn't find a member overload. Look for a global one. 887 DeclareGlobalNewDelete(); 888 DeclContext *TUDecl = Context.getTranslationUnitDecl(); 889 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0], 890 AllocArgs.size(), TUDecl, /*AllowMissing=*/false, 891 OperatorNew)) 892 return true; 893 } 894 895 // FindAllocationOverload can change the passed in arguments, so we need to 896 // copy them back. 897 if (NumPlaceArgs > 0) 898 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs); 899 900 // C++ [expr.new]p19: 901 // 902 // If the new-expression begins with a unary :: operator, the 903 // deallocation function’s name is looked up in the global 904 // scope. Otherwise, if the allocated type is a class type T or an 905 // array thereof, the deallocation function’s name is looked up in 906 // the scope of T. If this lookup fails to find the name, or if 907 // the allocated type is not a class type or array thereof, the 908 // deallocation function’s name is looked up in the global scope. 909 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName); 910 if (AllocType->isRecordType() && !UseGlobal) { 911 CXXRecordDecl *RD 912 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl()); 913 LookupQualifiedName(FoundDelete, RD); 914 } 915 916 if (FoundDelete.empty()) { 917 DeclareGlobalNewDelete(); 918 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl()); 919 } 920 921 FoundDelete.suppressDiagnostics(); 922 llvm::SmallVector<NamedDecl *, 4> Matches; 923 if (NumPlaceArgs > 1) { 924 // C++ [expr.new]p20: 925 // A declaration of a placement deallocation function matches the 926 // declaration of a placement allocation function if it has the 927 // same number of parameters and, after parameter transformations 928 // (8.3.5), all parameter types except the first are 929 // identical. [...] 930 // 931 // To perform this comparison, we compute the function type that 932 // the deallocation function should have, and use that type both 933 // for template argument deduction and for comparison purposes. 934 QualType ExpectedFunctionType; 935 { 936 const FunctionProtoType *Proto 937 = OperatorNew->getType()->getAs<FunctionProtoType>(); 938 llvm::SmallVector<QualType, 4> ArgTypes; 939 ArgTypes.push_back(Context.VoidPtrTy); 940 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I) 941 ArgTypes.push_back(Proto->getArgType(I)); 942 943 ExpectedFunctionType 944 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(), 945 ArgTypes.size(), 946 Proto->isVariadic(), 947 0, false, false, 0, 0, false, CC_Default); 948 } 949 950 for (LookupResult::iterator D = FoundDelete.begin(), 951 DEnd = FoundDelete.end(); 952 D != DEnd; ++D) { 953 FunctionDecl *Fn = 0; 954 if (FunctionTemplateDecl *FnTmpl 955 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) { 956 // Perform template argument deduction to try to match the 957 // expected function type. 958 TemplateDeductionInfo Info(Context, StartLoc); 959 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info)) 960 continue; 961 } else 962 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl()); 963 964 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType)) 965 Matches.push_back(Fn); 966 } 967 } else { 968 // C++ [expr.new]p20: 969 // [...] Any non-placement deallocation function matches a 970 // non-placement allocation function. [...] 971 for (LookupResult::iterator D = FoundDelete.begin(), 972 DEnd = FoundDelete.end(); 973 D != DEnd; ++D) { 974 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl())) 975 if (isNonPlacementDeallocationFunction(Fn)) 976 Matches.push_back(*D); 977 } 978 } 979 980 // C++ [expr.new]p20: 981 // [...] If the lookup finds a single matching deallocation 982 // function, that function will be called; otherwise, no 983 // deallocation function will be called. 984 if (Matches.size() == 1) { 985 // FIXME: Drops access, using-declaration info! 986 OperatorDelete = cast<FunctionDecl>(Matches[0]->getUnderlyingDecl()); 987 988 // C++0x [expr.new]p20: 989 // If the lookup finds the two-parameter form of a usual 990 // deallocation function (3.7.4.2) and that function, considered 991 // as a placement deallocation function, would have been 992 // selected as a match for the allocation function, the program 993 // is ill-formed. 994 if (NumPlaceArgs && getLangOptions().CPlusPlus0x && 995 isNonPlacementDeallocationFunction(OperatorDelete)) { 996 Diag(StartLoc, diag::err_placement_new_non_placement_delete) 997 << SourceRange(PlaceArgs[0]->getLocStart(), 998 PlaceArgs[NumPlaceArgs - 1]->getLocEnd()); 999 Diag(OperatorDelete->getLocation(), diag::note_previous_decl) 1000 << DeleteName; 1001 } 1002 } 1003 1004 return false; 1005} 1006 1007/// FindAllocationOverload - Find an fitting overload for the allocation 1008/// function in the specified scope. 1009bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range, 1010 DeclarationName Name, Expr** Args, 1011 unsigned NumArgs, DeclContext *Ctx, 1012 bool AllowMissing, FunctionDecl *&Operator) { 1013 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName); 1014 LookupQualifiedName(R, Ctx); 1015 if (R.empty()) { 1016 if (AllowMissing) 1017 return false; 1018 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) 1019 << Name << Range; 1020 } 1021 1022 // FIXME: handle ambiguity 1023 1024 OverloadCandidateSet Candidates(StartLoc); 1025 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end(); 1026 Alloc != AllocEnd; ++Alloc) { 1027 // Even member operator new/delete are implicitly treated as 1028 // static, so don't use AddMemberCandidate. 1029 1030 if (FunctionTemplateDecl *FnTemplate = 1031 dyn_cast<FunctionTemplateDecl>((*Alloc)->getUnderlyingDecl())) { 1032 AddTemplateOverloadCandidate(FnTemplate, Alloc.getAccess(), 1033 /*ExplicitTemplateArgs=*/0, Args, NumArgs, 1034 Candidates, 1035 /*SuppressUserConversions=*/false); 1036 continue; 1037 } 1038 1039 FunctionDecl *Fn = cast<FunctionDecl>((*Alloc)->getUnderlyingDecl()); 1040 AddOverloadCandidate(Fn, Alloc.getAccess(), Args, NumArgs, Candidates, 1041 /*SuppressUserConversions=*/false); 1042 } 1043 1044 // Do the resolution. 1045 OverloadCandidateSet::iterator Best; 1046 switch(BestViableFunction(Candidates, StartLoc, Best)) { 1047 case OR_Success: { 1048 // Got one! 1049 FunctionDecl *FnDecl = Best->Function; 1050 // The first argument is size_t, and the first parameter must be size_t, 1051 // too. This is checked on declaration and can be assumed. (It can't be 1052 // asserted on, though, since invalid decls are left in there.) 1053 // Whatch out for variadic allocator function. 1054 unsigned NumArgsInFnDecl = FnDecl->getNumParams(); 1055 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) { 1056 if (PerformCopyInitialization(Args[i], 1057 FnDecl->getParamDecl(i)->getType(), 1058 AA_Passing)) 1059 return true; 1060 } 1061 Operator = FnDecl; 1062 return false; 1063 } 1064 1065 case OR_No_Viable_Function: 1066 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) 1067 << Name << Range; 1068 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs); 1069 return true; 1070 1071 case OR_Ambiguous: 1072 Diag(StartLoc, diag::err_ovl_ambiguous_call) 1073 << Name << Range; 1074 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs); 1075 return true; 1076 1077 case OR_Deleted: 1078 Diag(StartLoc, diag::err_ovl_deleted_call) 1079 << Best->Function->isDeleted() 1080 << Name << Range; 1081 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs); 1082 return true; 1083 } 1084 assert(false && "Unreachable, bad result from BestViableFunction"); 1085 return true; 1086} 1087 1088 1089/// DeclareGlobalNewDelete - Declare the global forms of operator new and 1090/// delete. These are: 1091/// @code 1092/// void* operator new(std::size_t) throw(std::bad_alloc); 1093/// void* operator new[](std::size_t) throw(std::bad_alloc); 1094/// void operator delete(void *) throw(); 1095/// void operator delete[](void *) throw(); 1096/// @endcode 1097/// Note that the placement and nothrow forms of new are *not* implicitly 1098/// declared. Their use requires including \<new\>. 1099void Sema::DeclareGlobalNewDelete() { 1100 if (GlobalNewDeleteDeclared) 1101 return; 1102 1103 // C++ [basic.std.dynamic]p2: 1104 // [...] The following allocation and deallocation functions (18.4) are 1105 // implicitly declared in global scope in each translation unit of a 1106 // program 1107 // 1108 // void* operator new(std::size_t) throw(std::bad_alloc); 1109 // void* operator new[](std::size_t) throw(std::bad_alloc); 1110 // void operator delete(void*) throw(); 1111 // void operator delete[](void*) throw(); 1112 // 1113 // These implicit declarations introduce only the function names operator 1114 // new, operator new[], operator delete, operator delete[]. 1115 // 1116 // Here, we need to refer to std::bad_alloc, so we will implicitly declare 1117 // "std" or "bad_alloc" as necessary to form the exception specification. 1118 // However, we do not make these implicit declarations visible to name 1119 // lookup. 1120 if (!StdNamespace) { 1121 // The "std" namespace has not yet been defined, so build one implicitly. 1122 StdNamespace = NamespaceDecl::Create(Context, 1123 Context.getTranslationUnitDecl(), 1124 SourceLocation(), 1125 &PP.getIdentifierTable().get("std")); 1126 StdNamespace->setImplicit(true); 1127 } 1128 1129 if (!StdBadAlloc) { 1130 // The "std::bad_alloc" class has not yet been declared, so build it 1131 // implicitly. 1132 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class, 1133 StdNamespace, 1134 SourceLocation(), 1135 &PP.getIdentifierTable().get("bad_alloc"), 1136 SourceLocation(), 0); 1137 StdBadAlloc->setImplicit(true); 1138 } 1139 1140 GlobalNewDeleteDeclared = true; 1141 1142 QualType VoidPtr = Context.getPointerType(Context.VoidTy); 1143 QualType SizeT = Context.getSizeType(); 1144 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew; 1145 1146 DeclareGlobalAllocationFunction( 1147 Context.DeclarationNames.getCXXOperatorName(OO_New), 1148 VoidPtr, SizeT, AssumeSaneOperatorNew); 1149 DeclareGlobalAllocationFunction( 1150 Context.DeclarationNames.getCXXOperatorName(OO_Array_New), 1151 VoidPtr, SizeT, AssumeSaneOperatorNew); 1152 DeclareGlobalAllocationFunction( 1153 Context.DeclarationNames.getCXXOperatorName(OO_Delete), 1154 Context.VoidTy, VoidPtr); 1155 DeclareGlobalAllocationFunction( 1156 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete), 1157 Context.VoidTy, VoidPtr); 1158} 1159 1160/// DeclareGlobalAllocationFunction - Declares a single implicit global 1161/// allocation function if it doesn't already exist. 1162void Sema::DeclareGlobalAllocationFunction(DeclarationName Name, 1163 QualType Return, QualType Argument, 1164 bool AddMallocAttr) { 1165 DeclContext *GlobalCtx = Context.getTranslationUnitDecl(); 1166 1167 // Check if this function is already declared. 1168 { 1169 DeclContext::lookup_iterator Alloc, AllocEnd; 1170 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name); 1171 Alloc != AllocEnd; ++Alloc) { 1172 // Only look at non-template functions, as it is the predefined, 1173 // non-templated allocation function we are trying to declare here. 1174 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) { 1175 QualType InitialParamType = 1176 Context.getCanonicalType( 1177 Func->getParamDecl(0)->getType().getUnqualifiedType()); 1178 // FIXME: Do we need to check for default arguments here? 1179 if (Func->getNumParams() == 1 && InitialParamType == Argument) 1180 return; 1181 } 1182 } 1183 } 1184 1185 QualType BadAllocType; 1186 bool HasBadAllocExceptionSpec 1187 = (Name.getCXXOverloadedOperator() == OO_New || 1188 Name.getCXXOverloadedOperator() == OO_Array_New); 1189 if (HasBadAllocExceptionSpec) { 1190 assert(StdBadAlloc && "Must have std::bad_alloc declared"); 1191 BadAllocType = Context.getTypeDeclType(StdBadAlloc); 1192 } 1193 1194 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0, 1195 true, false, 1196 HasBadAllocExceptionSpec? 1 : 0, 1197 &BadAllocType, false, CC_Default); 1198 FunctionDecl *Alloc = 1199 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name, 1200 FnType, /*TInfo=*/0, FunctionDecl::None, false, true); 1201 Alloc->setImplicit(); 1202 1203 if (AddMallocAttr) 1204 Alloc->addAttr(::new (Context) MallocAttr()); 1205 1206 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(), 1207 0, Argument, /*TInfo=*/0, 1208 VarDecl::None, 0); 1209 Alloc->setParams(&Param, 1); 1210 1211 // FIXME: Also add this declaration to the IdentifierResolver, but 1212 // make sure it is at the end of the chain to coincide with the 1213 // global scope. 1214 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc); 1215} 1216 1217bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, 1218 DeclarationName Name, 1219 FunctionDecl* &Operator) { 1220 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName); 1221 // Try to find operator delete/operator delete[] in class scope. 1222 LookupQualifiedName(Found, RD); 1223 1224 if (Found.isAmbiguous()) 1225 return true; 1226 1227 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end(); 1228 F != FEnd; ++F) { 1229 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F)) 1230 if (Delete->isUsualDeallocationFunction()) { 1231 Operator = Delete; 1232 return false; 1233 } 1234 } 1235 1236 // We did find operator delete/operator delete[] declarations, but 1237 // none of them were suitable. 1238 if (!Found.empty()) { 1239 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found) 1240 << Name << RD; 1241 1242 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end(); 1243 F != FEnd; ++F) { 1244 Diag((*F)->getLocation(), 1245 diag::note_delete_member_function_declared_here) 1246 << Name; 1247 } 1248 1249 return true; 1250 } 1251 1252 // Look for a global declaration. 1253 DeclareGlobalNewDelete(); 1254 DeclContext *TUDecl = Context.getTranslationUnitDecl(); 1255 1256 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation()); 1257 Expr* DeallocArgs[1]; 1258 DeallocArgs[0] = &Null; 1259 if (FindAllocationOverload(StartLoc, SourceRange(), Name, 1260 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false, 1261 Operator)) 1262 return true; 1263 1264 assert(Operator && "Did not find a deallocation function!"); 1265 return false; 1266} 1267 1268/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in: 1269/// @code ::delete ptr; @endcode 1270/// or 1271/// @code delete [] ptr; @endcode 1272Action::OwningExprResult 1273Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, 1274 bool ArrayForm, ExprArg Operand) { 1275 // C++ [expr.delete]p1: 1276 // The operand shall have a pointer type, or a class type having a single 1277 // conversion function to a pointer type. The result has type void. 1278 // 1279 // DR599 amends "pointer type" to "pointer to object type" in both cases. 1280 1281 FunctionDecl *OperatorDelete = 0; 1282 1283 Expr *Ex = (Expr *)Operand.get(); 1284 if (!Ex->isTypeDependent()) { 1285 QualType Type = Ex->getType(); 1286 1287 if (const RecordType *Record = Type->getAs<RecordType>()) { 1288 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions; 1289 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1290 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions(); 1291 1292 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 1293 E = Conversions->end(); I != E; ++I) { 1294 // Skip over templated conversion functions; they aren't considered. 1295 if (isa<FunctionTemplateDecl>(*I)) 1296 continue; 1297 1298 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I); 1299 1300 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 1301 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 1302 if (ConvPtrType->getPointeeType()->isObjectType()) 1303 ObjectPtrConversions.push_back(Conv); 1304 } 1305 if (ObjectPtrConversions.size() == 1) { 1306 // We have a single conversion to a pointer-to-object type. Perform 1307 // that conversion. 1308 Operand.release(); 1309 if (!PerformImplicitConversion(Ex, 1310 ObjectPtrConversions.front()->getConversionType(), 1311 AA_Converting)) { 1312 Operand = Owned(Ex); 1313 Type = Ex->getType(); 1314 } 1315 } 1316 else if (ObjectPtrConversions.size() > 1) { 1317 Diag(StartLoc, diag::err_ambiguous_delete_operand) 1318 << Type << Ex->getSourceRange(); 1319 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) { 1320 CXXConversionDecl *Conv = ObjectPtrConversions[i]; 1321 NoteOverloadCandidate(Conv); 1322 } 1323 return ExprError(); 1324 } 1325 } 1326 1327 if (!Type->isPointerType()) 1328 return ExprError(Diag(StartLoc, diag::err_delete_operand) 1329 << Type << Ex->getSourceRange()); 1330 1331 QualType Pointee = Type->getAs<PointerType>()->getPointeeType(); 1332 if (Pointee->isFunctionType() || Pointee->isVoidType()) 1333 return ExprError(Diag(StartLoc, diag::err_delete_operand) 1334 << Type << Ex->getSourceRange()); 1335 else if (!Pointee->isDependentType() && 1336 RequireCompleteType(StartLoc, Pointee, 1337 PDiag(diag::warn_delete_incomplete) 1338 << Ex->getSourceRange())) 1339 return ExprError(); 1340 1341 // C++ [expr.delete]p2: 1342 // [Note: a pointer to a const type can be the operand of a 1343 // delete-expression; it is not necessary to cast away the constness 1344 // (5.2.11) of the pointer expression before it is used as the operand 1345 // of the delete-expression. ] 1346 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy), 1347 CastExpr::CK_NoOp); 1348 1349 // Update the operand. 1350 Operand.take(); 1351 Operand = ExprArg(*this, Ex); 1352 1353 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( 1354 ArrayForm ? OO_Array_Delete : OO_Delete); 1355 1356 if (const RecordType *RT = Pointee->getAs<RecordType>()) { 1357 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 1358 1359 if (!UseGlobal && 1360 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete)) 1361 return ExprError(); 1362 1363 if (!RD->hasTrivialDestructor()) 1364 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context)) 1365 MarkDeclarationReferenced(StartLoc, 1366 const_cast<CXXDestructorDecl*>(Dtor)); 1367 } 1368 1369 if (!OperatorDelete) { 1370 // Look for a global declaration. 1371 DeclareGlobalNewDelete(); 1372 DeclContext *TUDecl = Context.getTranslationUnitDecl(); 1373 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName, 1374 &Ex, 1, TUDecl, /*AllowMissing=*/false, 1375 OperatorDelete)) 1376 return ExprError(); 1377 } 1378 1379 // FIXME: Check access and ambiguity of operator delete and destructor. 1380 } 1381 1382 Operand.release(); 1383 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm, 1384 OperatorDelete, Ex, StartLoc)); 1385} 1386 1387/// \brief Check the use of the given variable as a C++ condition in an if, 1388/// while, do-while, or switch statement. 1389Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar) { 1390 QualType T = ConditionVar->getType(); 1391 1392 // C++ [stmt.select]p2: 1393 // The declarator shall not specify a function or an array. 1394 if (T->isFunctionType()) 1395 return ExprError(Diag(ConditionVar->getLocation(), 1396 diag::err_invalid_use_of_function_type) 1397 << ConditionVar->getSourceRange()); 1398 else if (T->isArrayType()) 1399 return ExprError(Diag(ConditionVar->getLocation(), 1400 diag::err_invalid_use_of_array_type) 1401 << ConditionVar->getSourceRange()); 1402 1403 return Owned(DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar, 1404 ConditionVar->getLocation(), 1405 ConditionVar->getType().getNonReferenceType())); 1406} 1407 1408/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid. 1409bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) { 1410 // C++ 6.4p4: 1411 // The value of a condition that is an initialized declaration in a statement 1412 // other than a switch statement is the value of the declared variable 1413 // implicitly converted to type bool. If that conversion is ill-formed, the 1414 // program is ill-formed. 1415 // The value of a condition that is an expression is the value of the 1416 // expression, implicitly converted to bool. 1417 // 1418 return PerformContextuallyConvertToBool(CondExpr); 1419} 1420 1421/// Helper function to determine whether this is the (deprecated) C++ 1422/// conversion from a string literal to a pointer to non-const char or 1423/// non-const wchar_t (for narrow and wide string literals, 1424/// respectively). 1425bool 1426Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) { 1427 // Look inside the implicit cast, if it exists. 1428 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From)) 1429 From = Cast->getSubExpr(); 1430 1431 // A string literal (2.13.4) that is not a wide string literal can 1432 // be converted to an rvalue of type "pointer to char"; a wide 1433 // string literal can be converted to an rvalue of type "pointer 1434 // to wchar_t" (C++ 4.2p2). 1435 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From)) 1436 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) 1437 if (const BuiltinType *ToPointeeType 1438 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) { 1439 // This conversion is considered only when there is an 1440 // explicit appropriate pointer target type (C++ 4.2p2). 1441 if (!ToPtrType->getPointeeType().hasQualifiers() && 1442 ((StrLit->isWide() && ToPointeeType->isWideCharType()) || 1443 (!StrLit->isWide() && 1444 (ToPointeeType->getKind() == BuiltinType::Char_U || 1445 ToPointeeType->getKind() == BuiltinType::Char_S)))) 1446 return true; 1447 } 1448 1449 return false; 1450} 1451 1452/// PerformImplicitConversion - Perform an implicit conversion of the 1453/// expression From to the type ToType. Returns true if there was an 1454/// error, false otherwise. The expression From is replaced with the 1455/// converted expression. Flavor is the kind of conversion we're 1456/// performing, used in the error message. If @p AllowExplicit, 1457/// explicit user-defined conversions are permitted. @p Elidable should be true 1458/// when called for copies which may be elided (C++ 12.8p15). C++0x overload 1459/// resolution works differently in that case. 1460bool 1461Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 1462 AssignmentAction Action, bool AllowExplicit, 1463 bool Elidable) { 1464 ImplicitConversionSequence ICS; 1465 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, 1466 Elidable, ICS); 1467} 1468 1469bool 1470Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 1471 AssignmentAction Action, bool AllowExplicit, 1472 bool Elidable, 1473 ImplicitConversionSequence& ICS) { 1474 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1475 if (Elidable && getLangOptions().CPlusPlus0x) { 1476 ICS = TryImplicitConversion(From, ToType, 1477 /*SuppressUserConversions=*/false, 1478 AllowExplicit, 1479 /*ForceRValue=*/true, 1480 /*InOverloadResolution=*/false); 1481 } 1482 if (ICS.isBad()) { 1483 ICS = TryImplicitConversion(From, ToType, 1484 /*SuppressUserConversions=*/false, 1485 AllowExplicit, 1486 /*ForceRValue=*/false, 1487 /*InOverloadResolution=*/false); 1488 } 1489 return PerformImplicitConversion(From, ToType, ICS, Action); 1490} 1491 1492/// PerformImplicitConversion - Perform an implicit conversion of the 1493/// expression From to the type ToType using the pre-computed implicit 1494/// conversion sequence ICS. Returns true if there was an error, false 1495/// otherwise. The expression From is replaced with the converted 1496/// expression. Action is the kind of conversion we're performing, 1497/// used in the error message. 1498bool 1499Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 1500 const ImplicitConversionSequence &ICS, 1501 AssignmentAction Action, bool IgnoreBaseAccess) { 1502 switch (ICS.getKind()) { 1503 case ImplicitConversionSequence::StandardConversion: 1504 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action, 1505 IgnoreBaseAccess)) 1506 return true; 1507 break; 1508 1509 case ImplicitConversionSequence::UserDefinedConversion: { 1510 1511 FunctionDecl *FD = ICS.UserDefined.ConversionFunction; 1512 CastExpr::CastKind CastKind = CastExpr::CK_Unknown; 1513 QualType BeforeToType; 1514 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) { 1515 CastKind = CastExpr::CK_UserDefinedConversion; 1516 1517 // If the user-defined conversion is specified by a conversion function, 1518 // the initial standard conversion sequence converts the source type to 1519 // the implicit object parameter of the conversion function. 1520 BeforeToType = Context.getTagDeclType(Conv->getParent()); 1521 } else if (const CXXConstructorDecl *Ctor = 1522 dyn_cast<CXXConstructorDecl>(FD)) { 1523 CastKind = CastExpr::CK_ConstructorConversion; 1524 // Do no conversion if dealing with ... for the first conversion. 1525 if (!ICS.UserDefined.EllipsisConversion) { 1526 // If the user-defined conversion is specified by a constructor, the 1527 // initial standard conversion sequence converts the source type to the 1528 // type required by the argument of the constructor 1529 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType(); 1530 } 1531 } 1532 else 1533 assert(0 && "Unknown conversion function kind!"); 1534 // Whatch out for elipsis conversion. 1535 if (!ICS.UserDefined.EllipsisConversion) { 1536 if (PerformImplicitConversion(From, BeforeToType, 1537 ICS.UserDefined.Before, AA_Converting, 1538 IgnoreBaseAccess)) 1539 return true; 1540 } 1541 1542 OwningExprResult CastArg 1543 = BuildCXXCastArgument(From->getLocStart(), 1544 ToType.getNonReferenceType(), 1545 CastKind, cast<CXXMethodDecl>(FD), 1546 Owned(From)); 1547 1548 if (CastArg.isInvalid()) 1549 return true; 1550 1551 From = CastArg.takeAs<Expr>(); 1552 1553 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After, 1554 AA_Converting, IgnoreBaseAccess); 1555 } 1556 1557 case ImplicitConversionSequence::AmbiguousConversion: 1558 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(), 1559 PDiag(diag::err_typecheck_ambiguous_condition) 1560 << From->getSourceRange()); 1561 return true; 1562 1563 case ImplicitConversionSequence::EllipsisConversion: 1564 assert(false && "Cannot perform an ellipsis conversion"); 1565 return false; 1566 1567 case ImplicitConversionSequence::BadConversion: 1568 return true; 1569 } 1570 1571 // Everything went well. 1572 return false; 1573} 1574 1575/// PerformImplicitConversion - Perform an implicit conversion of the 1576/// expression From to the type ToType by following the standard 1577/// conversion sequence SCS. Returns true if there was an error, false 1578/// otherwise. The expression From is replaced with the converted 1579/// expression. Flavor is the context in which we're performing this 1580/// conversion, for use in error messages. 1581bool 1582Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 1583 const StandardConversionSequence& SCS, 1584 AssignmentAction Action, bool IgnoreBaseAccess) { 1585 // Overall FIXME: we are recomputing too many types here and doing far too 1586 // much extra work. What this means is that we need to keep track of more 1587 // information that is computed when we try the implicit conversion initially, 1588 // so that we don't need to recompute anything here. 1589 QualType FromType = From->getType(); 1590 1591 if (SCS.CopyConstructor) { 1592 // FIXME: When can ToType be a reference type? 1593 assert(!ToType->isReferenceType()); 1594 if (SCS.Second == ICK_Derived_To_Base) { 1595 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this); 1596 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor), 1597 MultiExprArg(*this, (void **)&From, 1), 1598 /*FIXME:ConstructLoc*/SourceLocation(), 1599 ConstructorArgs)) 1600 return true; 1601 OwningExprResult FromResult = 1602 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(), 1603 ToType, SCS.CopyConstructor, 1604 move_arg(ConstructorArgs)); 1605 if (FromResult.isInvalid()) 1606 return true; 1607 From = FromResult.takeAs<Expr>(); 1608 return false; 1609 } 1610 OwningExprResult FromResult = 1611 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(), 1612 ToType, SCS.CopyConstructor, 1613 MultiExprArg(*this, (void**)&From, 1)); 1614 1615 if (FromResult.isInvalid()) 1616 return true; 1617 1618 From = FromResult.takeAs<Expr>(); 1619 return false; 1620 } 1621 1622 // Perform the first implicit conversion. 1623 switch (SCS.First) { 1624 case ICK_Identity: 1625 case ICK_Lvalue_To_Rvalue: 1626 // Nothing to do. 1627 break; 1628 1629 case ICK_Array_To_Pointer: 1630 FromType = Context.getArrayDecayedType(FromType); 1631 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay); 1632 break; 1633 1634 case ICK_Function_To_Pointer: 1635 if (Context.getCanonicalType(FromType) == Context.OverloadTy) { 1636 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true); 1637 if (!Fn) 1638 return true; 1639 1640 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin())) 1641 return true; 1642 1643 From = FixOverloadedFunctionReference(From, Fn); 1644 FromType = From->getType(); 1645 1646 // If there's already an address-of operator in the expression, we have 1647 // the right type already, and the code below would just introduce an 1648 // invalid additional pointer level. 1649 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType()) 1650 break; 1651 } 1652 FromType = Context.getPointerType(FromType); 1653 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay); 1654 break; 1655 1656 default: 1657 assert(false && "Improper first standard conversion"); 1658 break; 1659 } 1660 1661 // Perform the second implicit conversion 1662 switch (SCS.Second) { 1663 case ICK_Identity: 1664 // If both sides are functions (or pointers/references to them), there could 1665 // be incompatible exception declarations. 1666 if (CheckExceptionSpecCompatibility(From, ToType)) 1667 return true; 1668 // Nothing else to do. 1669 break; 1670 1671 case ICK_NoReturn_Adjustment: 1672 // If both sides are functions (or pointers/references to them), there could 1673 // be incompatible exception declarations. 1674 if (CheckExceptionSpecCompatibility(From, ToType)) 1675 return true; 1676 1677 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false), 1678 CastExpr::CK_NoOp); 1679 break; 1680 1681 case ICK_Integral_Promotion: 1682 case ICK_Integral_Conversion: 1683 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast); 1684 break; 1685 1686 case ICK_Floating_Promotion: 1687 case ICK_Floating_Conversion: 1688 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast); 1689 break; 1690 1691 case ICK_Complex_Promotion: 1692 case ICK_Complex_Conversion: 1693 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown); 1694 break; 1695 1696 case ICK_Floating_Integral: 1697 if (ToType->isFloatingType()) 1698 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating); 1699 else 1700 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral); 1701 break; 1702 1703 case ICK_Complex_Real: 1704 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown); 1705 break; 1706 1707 case ICK_Compatible_Conversion: 1708 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp); 1709 break; 1710 1711 case ICK_Pointer_Conversion: { 1712 if (SCS.IncompatibleObjC) { 1713 // Diagnose incompatible Objective-C conversions 1714 Diag(From->getSourceRange().getBegin(), 1715 diag::ext_typecheck_convert_incompatible_pointer) 1716 << From->getType() << ToType << Action 1717 << From->getSourceRange(); 1718 } 1719 1720 1721 CastExpr::CastKind Kind = CastExpr::CK_Unknown; 1722 if (CheckPointerConversion(From, ToType, Kind, IgnoreBaseAccess)) 1723 return true; 1724 ImpCastExprToType(From, ToType, Kind); 1725 break; 1726 } 1727 1728 case ICK_Pointer_Member: { 1729 CastExpr::CastKind Kind = CastExpr::CK_Unknown; 1730 if (CheckMemberPointerConversion(From, ToType, Kind, IgnoreBaseAccess)) 1731 return true; 1732 if (CheckExceptionSpecCompatibility(From, ToType)) 1733 return true; 1734 ImpCastExprToType(From, ToType, Kind); 1735 break; 1736 } 1737 case ICK_Boolean_Conversion: { 1738 CastExpr::CastKind Kind = CastExpr::CK_Unknown; 1739 if (FromType->isMemberPointerType()) 1740 Kind = CastExpr::CK_MemberPointerToBoolean; 1741 1742 ImpCastExprToType(From, Context.BoolTy, Kind); 1743 break; 1744 } 1745 1746 case ICK_Derived_To_Base: 1747 if (CheckDerivedToBaseConversion(From->getType(), 1748 ToType.getNonReferenceType(), 1749 From->getLocStart(), 1750 From->getSourceRange(), 1751 IgnoreBaseAccess)) 1752 return true; 1753 ImpCastExprToType(From, ToType.getNonReferenceType(), 1754 CastExpr::CK_DerivedToBase); 1755 break; 1756 1757 default: 1758 assert(false && "Improper second standard conversion"); 1759 break; 1760 } 1761 1762 switch (SCS.Third) { 1763 case ICK_Identity: 1764 // Nothing to do. 1765 break; 1766 1767 case ICK_Qualification: 1768 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue 1769 // references. 1770 ImpCastExprToType(From, ToType.getNonReferenceType(), 1771 CastExpr::CK_NoOp, 1772 ToType->isLValueReferenceType()); 1773 1774 if (SCS.DeprecatedStringLiteralToCharPtr) 1775 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion) 1776 << ToType.getNonReferenceType(); 1777 1778 break; 1779 1780 default: 1781 assert(false && "Improper second standard conversion"); 1782 break; 1783 } 1784 1785 return false; 1786} 1787 1788Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT, 1789 SourceLocation KWLoc, 1790 SourceLocation LParen, 1791 TypeTy *Ty, 1792 SourceLocation RParen) { 1793 QualType T = GetTypeFromParser(Ty); 1794 1795 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html 1796 // all traits except __is_class, __is_enum and __is_union require a the type 1797 // to be complete. 1798 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) { 1799 if (RequireCompleteType(KWLoc, T, 1800 diag::err_incomplete_type_used_in_type_trait_expr)) 1801 return ExprError(); 1802 } 1803 1804 // There is no point in eagerly computing the value. The traits are designed 1805 // to be used from type trait templates, so Ty will be a template parameter 1806 // 99% of the time. 1807 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T, 1808 RParen, Context.BoolTy)); 1809} 1810 1811QualType Sema::CheckPointerToMemberOperands( 1812 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) { 1813 const char *OpSpelling = isIndirect ? "->*" : ".*"; 1814 // C++ 5.5p2 1815 // The binary operator .* [p3: ->*] binds its second operand, which shall 1816 // be of type "pointer to member of T" (where T is a completely-defined 1817 // class type) [...] 1818 QualType RType = rex->getType(); 1819 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>(); 1820 if (!MemPtr) { 1821 Diag(Loc, diag::err_bad_memptr_rhs) 1822 << OpSpelling << RType << rex->getSourceRange(); 1823 return QualType(); 1824 } 1825 1826 QualType Class(MemPtr->getClass(), 0); 1827 1828 // C++ 5.5p2 1829 // [...] to its first operand, which shall be of class T or of a class of 1830 // which T is an unambiguous and accessible base class. [p3: a pointer to 1831 // such a class] 1832 QualType LType = lex->getType(); 1833 if (isIndirect) { 1834 if (const PointerType *Ptr = LType->getAs<PointerType>()) 1835 LType = Ptr->getPointeeType().getNonReferenceType(); 1836 else { 1837 Diag(Loc, diag::err_bad_memptr_lhs) 1838 << OpSpelling << 1 << LType 1839 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ".*"); 1840 return QualType(); 1841 } 1842 } 1843 1844 if (!Context.hasSameUnqualifiedType(Class, LType)) { 1845 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 1846 /*DetectVirtual=*/false); 1847 // FIXME: Would it be useful to print full ambiguity paths, or is that 1848 // overkill? 1849 if (!IsDerivedFrom(LType, Class, Paths) || 1850 Paths.isAmbiguous(Context.getCanonicalType(Class))) { 1851 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling 1852 << (int)isIndirect << lex->getType(); 1853 return QualType(); 1854 } 1855 // Cast LHS to type of use. 1856 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class; 1857 bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid; 1858 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue); 1859 } 1860 1861 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) { 1862 // Diagnose use of pointer-to-member type which when used as 1863 // the functional cast in a pointer-to-member expression. 1864 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect; 1865 return QualType(); 1866 } 1867 // C++ 5.5p2 1868 // The result is an object or a function of the type specified by the 1869 // second operand. 1870 // The cv qualifiers are the union of those in the pointer and the left side, 1871 // in accordance with 5.5p5 and 5.2.5. 1872 // FIXME: This returns a dereferenced member function pointer as a normal 1873 // function type. However, the only operation valid on such functions is 1874 // calling them. There's also a GCC extension to get a function pointer to the 1875 // thing, which is another complication, because this type - unlike the type 1876 // that is the result of this expression - takes the class as the first 1877 // argument. 1878 // We probably need a "MemberFunctionClosureType" or something like that. 1879 QualType Result = MemPtr->getPointeeType(); 1880 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers()); 1881 return Result; 1882} 1883 1884/// \brief Get the target type of a standard or user-defined conversion. 1885static QualType TargetType(const ImplicitConversionSequence &ICS) { 1886 switch (ICS.getKind()) { 1887 case ImplicitConversionSequence::StandardConversion: 1888 return ICS.Standard.getToType(2); 1889 case ImplicitConversionSequence::UserDefinedConversion: 1890 return ICS.UserDefined.After.getToType(2); 1891 case ImplicitConversionSequence::AmbiguousConversion: 1892 return ICS.Ambiguous.getToType(); 1893 1894 case ImplicitConversionSequence::EllipsisConversion: 1895 case ImplicitConversionSequence::BadConversion: 1896 llvm_unreachable("function not valid for ellipsis or bad conversions"); 1897 } 1898 return QualType(); // silence warnings 1899} 1900 1901/// \brief Try to convert a type to another according to C++0x 5.16p3. 1902/// 1903/// This is part of the parameter validation for the ? operator. If either 1904/// value operand is a class type, the two operands are attempted to be 1905/// converted to each other. This function does the conversion in one direction. 1906/// It emits a diagnostic and returns true only if it finds an ambiguous 1907/// conversion. 1908static bool TryClassUnification(Sema &Self, Expr *From, Expr *To, 1909 SourceLocation QuestionLoc, 1910 ImplicitConversionSequence &ICS) { 1911 // C++0x 5.16p3 1912 // The process for determining whether an operand expression E1 of type T1 1913 // can be converted to match an operand expression E2 of type T2 is defined 1914 // as follows: 1915 // -- If E2 is an lvalue: 1916 if (To->isLvalue(Self.Context) == Expr::LV_Valid) { 1917 // E1 can be converted to match E2 if E1 can be implicitly converted to 1918 // type "lvalue reference to T2", subject to the constraint that in the 1919 // conversion the reference must bind directly to E1. 1920 if (!Self.CheckReferenceInit(From, 1921 Self.Context.getLValueReferenceType(To->getType()), 1922 To->getLocStart(), 1923 /*SuppressUserConversions=*/false, 1924 /*AllowExplicit=*/false, 1925 /*ForceRValue=*/false, 1926 &ICS)) 1927 { 1928 assert((ICS.isStandard() || ICS.isUserDefined()) && 1929 "expected a definite conversion"); 1930 bool DirectBinding = 1931 ICS.isStandard() ? ICS.Standard.DirectBinding 1932 : ICS.UserDefined.After.DirectBinding; 1933 if (DirectBinding) 1934 return false; 1935 } 1936 } 1937 1938 // -- If E2 is an rvalue, or if the conversion above cannot be done: 1939 // -- if E1 and E2 have class type, and the underlying class types are 1940 // the same or one is a base class of the other: 1941 QualType FTy = From->getType(); 1942 QualType TTy = To->getType(); 1943 const RecordType *FRec = FTy->getAs<RecordType>(); 1944 const RecordType *TRec = TTy->getAs<RecordType>(); 1945 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy); 1946 if (FRec && TRec && (FRec == TRec || 1947 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) { 1948 // E1 can be converted to match E2 if the class of T2 is the 1949 // same type as, or a base class of, the class of T1, and 1950 // [cv2 > cv1]. 1951 if (FRec == TRec || FDerivedFromT) { 1952 if (TTy.isAtLeastAsQualifiedAs(FTy)) { 1953 // Could still fail if there's no copy constructor. 1954 // FIXME: Is this a hard error then, or just a conversion failure? The 1955 // standard doesn't say. 1956 ICS = Self.TryCopyInitialization(From, TTy, 1957 /*SuppressUserConversions=*/false, 1958 /*ForceRValue=*/false, 1959 /*InOverloadResolution=*/false); 1960 } else { 1961 ICS.setBad(BadConversionSequence::bad_qualifiers, From, TTy); 1962 } 1963 } else { 1964 // Can't implicitly convert FTy to a derived class TTy. 1965 // TODO: more specific error for this. 1966 ICS.setBad(BadConversionSequence::no_conversion, From, TTy); 1967 } 1968 } else { 1969 // -- Otherwise: E1 can be converted to match E2 if E1 can be 1970 // implicitly converted to the type that expression E2 would have 1971 // if E2 were converted to an rvalue. 1972 // First find the decayed type. 1973 if (TTy->isFunctionType()) 1974 TTy = Self.Context.getPointerType(TTy); 1975 else if (TTy->isArrayType()) 1976 TTy = Self.Context.getArrayDecayedType(TTy); 1977 1978 // Now try the implicit conversion. 1979 // FIXME: This doesn't detect ambiguities. 1980 ICS = Self.TryImplicitConversion(From, TTy, 1981 /*SuppressUserConversions=*/false, 1982 /*AllowExplicit=*/false, 1983 /*ForceRValue=*/false, 1984 /*InOverloadResolution=*/false); 1985 } 1986 return false; 1987} 1988 1989/// \brief Try to find a common type for two according to C++0x 5.16p5. 1990/// 1991/// This is part of the parameter validation for the ? operator. If either 1992/// value operand is a class type, overload resolution is used to find a 1993/// conversion to a common type. 1994static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS, 1995 SourceLocation Loc) { 1996 Expr *Args[2] = { LHS, RHS }; 1997 OverloadCandidateSet CandidateSet(Loc); 1998 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet); 1999 2000 OverloadCandidateSet::iterator Best; 2001 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) { 2002 case OR_Success: 2003 // We found a match. Perform the conversions on the arguments and move on. 2004 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0], 2005 Best->Conversions[0], Sema::AA_Converting) || 2006 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1], 2007 Best->Conversions[1], Sema::AA_Converting)) 2008 break; 2009 return false; 2010 2011 case OR_No_Viable_Function: 2012 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 2013 << LHS->getType() << RHS->getType() 2014 << LHS->getSourceRange() << RHS->getSourceRange(); 2015 return true; 2016 2017 case OR_Ambiguous: 2018 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl) 2019 << LHS->getType() << RHS->getType() 2020 << LHS->getSourceRange() << RHS->getSourceRange(); 2021 // FIXME: Print the possible common types by printing the return types of 2022 // the viable candidates. 2023 break; 2024 2025 case OR_Deleted: 2026 assert(false && "Conditional operator has only built-in overloads"); 2027 break; 2028 } 2029 return true; 2030} 2031 2032/// \brief Perform an "extended" implicit conversion as returned by 2033/// TryClassUnification. 2034/// 2035/// TryClassUnification generates ICSs that include reference bindings. 2036/// PerformImplicitConversion is not suitable for this; it chokes if the 2037/// second part of a standard conversion is ICK_DerivedToBase. This function 2038/// handles the reference binding specially. 2039static bool ConvertForConditional(Sema &Self, Expr *&E, 2040 const ImplicitConversionSequence &ICS) { 2041 if (ICS.isStandard() && ICS.Standard.ReferenceBinding) { 2042 assert(ICS.Standard.DirectBinding && 2043 "TryClassUnification should never generate indirect ref bindings"); 2044 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of 2045 // redoing all the work. 2046 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType( 2047 TargetType(ICS)), 2048 /*FIXME:*/E->getLocStart(), 2049 /*SuppressUserConversions=*/false, 2050 /*AllowExplicit=*/false, 2051 /*ForceRValue=*/false); 2052 } 2053 if (ICS.isUserDefined() && ICS.UserDefined.After.ReferenceBinding) { 2054 assert(ICS.UserDefined.After.DirectBinding && 2055 "TryClassUnification should never generate indirect ref bindings"); 2056 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType( 2057 TargetType(ICS)), 2058 /*FIXME:*/E->getLocStart(), 2059 /*SuppressUserConversions=*/false, 2060 /*AllowExplicit=*/false, 2061 /*ForceRValue=*/false); 2062 } 2063 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, Sema::AA_Converting)) 2064 return true; 2065 return false; 2066} 2067 2068/// \brief Check the operands of ?: under C++ semantics. 2069/// 2070/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y 2071/// extension. In this case, LHS == Cond. (But they're not aliases.) 2072QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS, 2073 SourceLocation QuestionLoc) { 2074 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++ 2075 // interface pointers. 2076 2077 // C++0x 5.16p1 2078 // The first expression is contextually converted to bool. 2079 if (!Cond->isTypeDependent()) { 2080 if (CheckCXXBooleanCondition(Cond)) 2081 return QualType(); 2082 } 2083 2084 // Either of the arguments dependent? 2085 if (LHS->isTypeDependent() || RHS->isTypeDependent()) 2086 return Context.DependentTy; 2087 2088 CheckSignCompare(LHS, RHS, QuestionLoc); 2089 2090 // C++0x 5.16p2 2091 // If either the second or the third operand has type (cv) void, ... 2092 QualType LTy = LHS->getType(); 2093 QualType RTy = RHS->getType(); 2094 bool LVoid = LTy->isVoidType(); 2095 bool RVoid = RTy->isVoidType(); 2096 if (LVoid || RVoid) { 2097 // ... then the [l2r] conversions are performed on the second and third 2098 // operands ... 2099 DefaultFunctionArrayLvalueConversion(LHS); 2100 DefaultFunctionArrayLvalueConversion(RHS); 2101 LTy = LHS->getType(); 2102 RTy = RHS->getType(); 2103 2104 // ... and one of the following shall hold: 2105 // -- The second or the third operand (but not both) is a throw- 2106 // expression; the result is of the type of the other and is an rvalue. 2107 bool LThrow = isa<CXXThrowExpr>(LHS); 2108 bool RThrow = isa<CXXThrowExpr>(RHS); 2109 if (LThrow && !RThrow) 2110 return RTy; 2111 if (RThrow && !LThrow) 2112 return LTy; 2113 2114 // -- Both the second and third operands have type void; the result is of 2115 // type void and is an rvalue. 2116 if (LVoid && RVoid) 2117 return Context.VoidTy; 2118 2119 // Neither holds, error. 2120 Diag(QuestionLoc, diag::err_conditional_void_nonvoid) 2121 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1) 2122 << LHS->getSourceRange() << RHS->getSourceRange(); 2123 return QualType(); 2124 } 2125 2126 // Neither is void. 2127 2128 // C++0x 5.16p3 2129 // Otherwise, if the second and third operand have different types, and 2130 // either has (cv) class type, and attempt is made to convert each of those 2131 // operands to the other. 2132 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) && 2133 (LTy->isRecordType() || RTy->isRecordType())) { 2134 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft; 2135 // These return true if a single direction is already ambiguous. 2136 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight)) 2137 return QualType(); 2138 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft)) 2139 return QualType(); 2140 2141 bool HaveL2R = !ICSLeftToRight.isBad(); 2142 bool HaveR2L = !ICSRightToLeft.isBad(); 2143 // If both can be converted, [...] the program is ill-formed. 2144 if (HaveL2R && HaveR2L) { 2145 Diag(QuestionLoc, diag::err_conditional_ambiguous) 2146 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange(); 2147 return QualType(); 2148 } 2149 2150 // If exactly one conversion is possible, that conversion is applied to 2151 // the chosen operand and the converted operands are used in place of the 2152 // original operands for the remainder of this section. 2153 if (HaveL2R) { 2154 if (ConvertForConditional(*this, LHS, ICSLeftToRight)) 2155 return QualType(); 2156 LTy = LHS->getType(); 2157 } else if (HaveR2L) { 2158 if (ConvertForConditional(*this, RHS, ICSRightToLeft)) 2159 return QualType(); 2160 RTy = RHS->getType(); 2161 } 2162 } 2163 2164 // C++0x 5.16p4 2165 // If the second and third operands are lvalues and have the same type, 2166 // the result is of that type [...] 2167 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy); 2168 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid && 2169 RHS->isLvalue(Context) == Expr::LV_Valid) 2170 return LTy; 2171 2172 // C++0x 5.16p5 2173 // Otherwise, the result is an rvalue. If the second and third operands 2174 // do not have the same type, and either has (cv) class type, ... 2175 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) { 2176 // ... overload resolution is used to determine the conversions (if any) 2177 // to be applied to the operands. If the overload resolution fails, the 2178 // program is ill-formed. 2179 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc)) 2180 return QualType(); 2181 } 2182 2183 // C++0x 5.16p6 2184 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard 2185 // conversions are performed on the second and third operands. 2186 DefaultFunctionArrayLvalueConversion(LHS); 2187 DefaultFunctionArrayLvalueConversion(RHS); 2188 LTy = LHS->getType(); 2189 RTy = RHS->getType(); 2190 2191 // After those conversions, one of the following shall hold: 2192 // -- The second and third operands have the same type; the result 2193 // is of that type. 2194 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) 2195 return LTy; 2196 2197 // -- The second and third operands have arithmetic or enumeration type; 2198 // the usual arithmetic conversions are performed to bring them to a 2199 // common type, and the result is of that type. 2200 if (LTy->isArithmeticType() && RTy->isArithmeticType()) { 2201 UsualArithmeticConversions(LHS, RHS); 2202 return LHS->getType(); 2203 } 2204 2205 // -- The second and third operands have pointer type, or one has pointer 2206 // type and the other is a null pointer constant; pointer conversions 2207 // and qualification conversions are performed to bring them to their 2208 // composite pointer type. The result is of the composite pointer type. 2209 // -- The second and third operands have pointer to member type, or one has 2210 // pointer to member type and the other is a null pointer constant; 2211 // pointer to member conversions and qualification conversions are 2212 // performed to bring them to a common type, whose cv-qualification 2213 // shall match the cv-qualification of either the second or the third 2214 // operand. The result is of the common type. 2215 bool NonStandardCompositeType = false; 2216 QualType Composite = FindCompositePointerType(LHS, RHS, 2217 isSFINAEContext()? 0 : &NonStandardCompositeType); 2218 if (!Composite.isNull()) { 2219 if (NonStandardCompositeType) 2220 Diag(QuestionLoc, 2221 diag::ext_typecheck_cond_incompatible_operands_nonstandard) 2222 << LTy << RTy << Composite 2223 << LHS->getSourceRange() << RHS->getSourceRange(); 2224 2225 return Composite; 2226 } 2227 2228 // Similarly, attempt to find composite type of twp objective-c pointers. 2229 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc); 2230 if (!Composite.isNull()) 2231 return Composite; 2232 2233 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 2234 << LHS->getType() << RHS->getType() 2235 << LHS->getSourceRange() << RHS->getSourceRange(); 2236 return QualType(); 2237} 2238 2239/// \brief Find a merged pointer type and convert the two expressions to it. 2240/// 2241/// This finds the composite pointer type (or member pointer type) for @p E1 2242/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this 2243/// type and returns it. 2244/// It does not emit diagnostics. 2245/// 2246/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find 2247/// a non-standard (but still sane) composite type to which both expressions 2248/// can be converted. When such a type is chosen, \c *NonStandardCompositeType 2249/// will be set true. 2250QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2, 2251 bool *NonStandardCompositeType) { 2252 if (NonStandardCompositeType) 2253 *NonStandardCompositeType = false; 2254 2255 assert(getLangOptions().CPlusPlus && "This function assumes C++"); 2256 QualType T1 = E1->getType(), T2 = E2->getType(); 2257 2258 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() && 2259 !T2->isAnyPointerType() && !T2->isMemberPointerType()) 2260 return QualType(); 2261 2262 // C++0x 5.9p2 2263 // Pointer conversions and qualification conversions are performed on 2264 // pointer operands to bring them to their composite pointer type. If 2265 // one operand is a null pointer constant, the composite pointer type is 2266 // the type of the other operand. 2267 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 2268 if (T2->isMemberPointerType()) 2269 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer); 2270 else 2271 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer); 2272 return T2; 2273 } 2274 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 2275 if (T1->isMemberPointerType()) 2276 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer); 2277 else 2278 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer); 2279 return T1; 2280 } 2281 2282 // Now both have to be pointers or member pointers. 2283 if ((!T1->isPointerType() && !T1->isMemberPointerType()) || 2284 (!T2->isPointerType() && !T2->isMemberPointerType())) 2285 return QualType(); 2286 2287 // Otherwise, of one of the operands has type "pointer to cv1 void," then 2288 // the other has type "pointer to cv2 T" and the composite pointer type is 2289 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2. 2290 // Otherwise, the composite pointer type is a pointer type similar to the 2291 // type of one of the operands, with a cv-qualification signature that is 2292 // the union of the cv-qualification signatures of the operand types. 2293 // In practice, the first part here is redundant; it's subsumed by the second. 2294 // What we do here is, we build the two possible composite types, and try the 2295 // conversions in both directions. If only one works, or if the two composite 2296 // types are the same, we have succeeded. 2297 // FIXME: extended qualifiers? 2298 typedef llvm::SmallVector<unsigned, 4> QualifierVector; 2299 QualifierVector QualifierUnion; 2300 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4> 2301 ContainingClassVector; 2302 ContainingClassVector MemberOfClass; 2303 QualType Composite1 = Context.getCanonicalType(T1), 2304 Composite2 = Context.getCanonicalType(T2); 2305 unsigned NeedConstBefore = 0; 2306 do { 2307 const PointerType *Ptr1, *Ptr2; 2308 if ((Ptr1 = Composite1->getAs<PointerType>()) && 2309 (Ptr2 = Composite2->getAs<PointerType>())) { 2310 Composite1 = Ptr1->getPointeeType(); 2311 Composite2 = Ptr2->getPointeeType(); 2312 2313 // If we're allowed to create a non-standard composite type, keep track 2314 // of where we need to fill in additional 'const' qualifiers. 2315 if (NonStandardCompositeType && 2316 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers()) 2317 NeedConstBefore = QualifierUnion.size(); 2318 2319 QualifierUnion.push_back( 2320 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); 2321 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0)); 2322 continue; 2323 } 2324 2325 const MemberPointerType *MemPtr1, *MemPtr2; 2326 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) && 2327 (MemPtr2 = Composite2->getAs<MemberPointerType>())) { 2328 Composite1 = MemPtr1->getPointeeType(); 2329 Composite2 = MemPtr2->getPointeeType(); 2330 2331 // If we're allowed to create a non-standard composite type, keep track 2332 // of where we need to fill in additional 'const' qualifiers. 2333 if (NonStandardCompositeType && 2334 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers()) 2335 NeedConstBefore = QualifierUnion.size(); 2336 2337 QualifierUnion.push_back( 2338 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); 2339 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(), 2340 MemPtr2->getClass())); 2341 continue; 2342 } 2343 2344 // FIXME: block pointer types? 2345 2346 // Cannot unwrap any more types. 2347 break; 2348 } while (true); 2349 2350 if (NeedConstBefore && NonStandardCompositeType) { 2351 // Extension: Add 'const' to qualifiers that come before the first qualifier 2352 // mismatch, so that our (non-standard!) composite type meets the 2353 // requirements of C++ [conv.qual]p4 bullet 3. 2354 for (unsigned I = 0; I != NeedConstBefore; ++I) { 2355 if ((QualifierUnion[I] & Qualifiers::Const) == 0) { 2356 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const; 2357 *NonStandardCompositeType = true; 2358 } 2359 } 2360 } 2361 2362 // Rewrap the composites as pointers or member pointers with the union CVRs. 2363 ContainingClassVector::reverse_iterator MOC 2364 = MemberOfClass.rbegin(); 2365 for (QualifierVector::reverse_iterator 2366 I = QualifierUnion.rbegin(), 2367 E = QualifierUnion.rend(); 2368 I != E; (void)++I, ++MOC) { 2369 Qualifiers Quals = Qualifiers::fromCVRMask(*I); 2370 if (MOC->first && MOC->second) { 2371 // Rebuild member pointer type 2372 Composite1 = Context.getMemberPointerType( 2373 Context.getQualifiedType(Composite1, Quals), 2374 MOC->first); 2375 Composite2 = Context.getMemberPointerType( 2376 Context.getQualifiedType(Composite2, Quals), 2377 MOC->second); 2378 } else { 2379 // Rebuild pointer type 2380 Composite1 2381 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals)); 2382 Composite2 2383 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals)); 2384 } 2385 } 2386 2387 ImplicitConversionSequence E1ToC1 = 2388 TryImplicitConversion(E1, Composite1, 2389 /*SuppressUserConversions=*/false, 2390 /*AllowExplicit=*/false, 2391 /*ForceRValue=*/false, 2392 /*InOverloadResolution=*/false); 2393 ImplicitConversionSequence E2ToC1 = 2394 TryImplicitConversion(E2, Composite1, 2395 /*SuppressUserConversions=*/false, 2396 /*AllowExplicit=*/false, 2397 /*ForceRValue=*/false, 2398 /*InOverloadResolution=*/false); 2399 2400 bool ToC2Viable = false; 2401 ImplicitConversionSequence E1ToC2, E2ToC2; 2402 if (Context.getCanonicalType(Composite1) != 2403 Context.getCanonicalType(Composite2)) { 2404 E1ToC2 = TryImplicitConversion(E1, Composite2, 2405 /*SuppressUserConversions=*/false, 2406 /*AllowExplicit=*/false, 2407 /*ForceRValue=*/false, 2408 /*InOverloadResolution=*/false); 2409 E2ToC2 = TryImplicitConversion(E2, Composite2, 2410 /*SuppressUserConversions=*/false, 2411 /*AllowExplicit=*/false, 2412 /*ForceRValue=*/false, 2413 /*InOverloadResolution=*/false); 2414 ToC2Viable = !E1ToC2.isBad() && !E2ToC2.isBad(); 2415 } 2416 2417 bool ToC1Viable = !E1ToC1.isBad() && !E2ToC1.isBad(); 2418 if (ToC1Viable && !ToC2Viable) { 2419 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, Sema::AA_Converting) && 2420 !PerformImplicitConversion(E2, Composite1, E2ToC1, Sema::AA_Converting)) 2421 return Composite1; 2422 } 2423 if (ToC2Viable && !ToC1Viable) { 2424 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, Sema::AA_Converting) && 2425 !PerformImplicitConversion(E2, Composite2, E2ToC2, Sema::AA_Converting)) 2426 return Composite2; 2427 } 2428 return QualType(); 2429} 2430 2431Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) { 2432 if (!Context.getLangOptions().CPlusPlus) 2433 return Owned(E); 2434 2435 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?"); 2436 2437 const RecordType *RT = E->getType()->getAs<RecordType>(); 2438 if (!RT) 2439 return Owned(E); 2440 2441 // If this is the result of a call expression, our source might 2442 // actually be a reference, in which case we shouldn't bind. 2443 if (CallExpr *CE = dyn_cast<CallExpr>(E)) { 2444 QualType Ty = CE->getCallee()->getType(); 2445 if (const PointerType *PT = Ty->getAs<PointerType>()) 2446 Ty = PT->getPointeeType(); 2447 else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>()) 2448 Ty = BPT->getPointeeType(); 2449 2450 const FunctionType *FTy = Ty->getAs<FunctionType>(); 2451 if (FTy->getResultType()->isReferenceType()) 2452 return Owned(E); 2453 } 2454 2455 // That should be enough to guarantee that this type is complete. 2456 // If it has a trivial destructor, we can avoid the extra copy. 2457 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 2458 if (RD->hasTrivialDestructor()) 2459 return Owned(E); 2460 2461 CXXTemporary *Temp = CXXTemporary::Create(Context, 2462 RD->getDestructor(Context)); 2463 ExprTemporaries.push_back(Temp); 2464 if (CXXDestructorDecl *Destructor = 2465 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context))) 2466 MarkDeclarationReferenced(E->getExprLoc(), Destructor); 2467 // FIXME: Add the temporary to the temporaries vector. 2468 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E)); 2469} 2470 2471Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) { 2472 assert(SubExpr && "sub expression can't be null!"); 2473 2474 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries; 2475 assert(ExprTemporaries.size() >= FirstTemporary); 2476 if (ExprTemporaries.size() == FirstTemporary) 2477 return SubExpr; 2478 2479 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr, 2480 &ExprTemporaries[FirstTemporary], 2481 ExprTemporaries.size() - FirstTemporary); 2482 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary, 2483 ExprTemporaries.end()); 2484 2485 return E; 2486} 2487 2488Sema::OwningExprResult 2489Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) { 2490 if (SubExpr.isInvalid()) 2491 return ExprError(); 2492 2493 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>())); 2494} 2495 2496FullExpr Sema::CreateFullExpr(Expr *SubExpr) { 2497 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries; 2498 assert(ExprTemporaries.size() >= FirstTemporary); 2499 2500 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary; 2501 CXXTemporary **Temporaries = 2502 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary]; 2503 2504 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries); 2505 2506 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary, 2507 ExprTemporaries.end()); 2508 2509 return E; 2510} 2511 2512Sema::OwningExprResult 2513Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc, 2514 tok::TokenKind OpKind, TypeTy *&ObjectType, 2515 bool &MayBePseudoDestructor) { 2516 // Since this might be a postfix expression, get rid of ParenListExprs. 2517 Base = MaybeConvertParenListExprToParenExpr(S, move(Base)); 2518 2519 Expr *BaseExpr = (Expr*)Base.get(); 2520 assert(BaseExpr && "no record expansion"); 2521 2522 QualType BaseType = BaseExpr->getType(); 2523 MayBePseudoDestructor = false; 2524 if (BaseType->isDependentType()) { 2525 // If we have a pointer to a dependent type and are using the -> operator, 2526 // the object type is the type that the pointer points to. We might still 2527 // have enough information about that type to do something useful. 2528 if (OpKind == tok::arrow) 2529 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) 2530 BaseType = Ptr->getPointeeType(); 2531 2532 ObjectType = BaseType.getAsOpaquePtr(); 2533 MayBePseudoDestructor = true; 2534 return move(Base); 2535 } 2536 2537 // C++ [over.match.oper]p8: 2538 // [...] When operator->returns, the operator-> is applied to the value 2539 // returned, with the original second operand. 2540 if (OpKind == tok::arrow) { 2541 // The set of types we've considered so far. 2542 llvm::SmallPtrSet<CanQualType,8> CTypes; 2543 llvm::SmallVector<SourceLocation, 8> Locations; 2544 CTypes.insert(Context.getCanonicalType(BaseType)); 2545 2546 while (BaseType->isRecordType()) { 2547 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc); 2548 BaseExpr = (Expr*)Base.get(); 2549 if (BaseExpr == NULL) 2550 return ExprError(); 2551 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr)) 2552 Locations.push_back(OpCall->getDirectCallee()->getLocation()); 2553 BaseType = BaseExpr->getType(); 2554 CanQualType CBaseType = Context.getCanonicalType(BaseType); 2555 if (!CTypes.insert(CBaseType)) { 2556 Diag(OpLoc, diag::err_operator_arrow_circular); 2557 for (unsigned i = 0; i < Locations.size(); i++) 2558 Diag(Locations[i], diag::note_declared_at); 2559 return ExprError(); 2560 } 2561 } 2562 2563 if (BaseType->isPointerType()) 2564 BaseType = BaseType->getPointeeType(); 2565 } 2566 2567 // We could end up with various non-record types here, such as extended 2568 // vector types or Objective-C interfaces. Just return early and let 2569 // ActOnMemberReferenceExpr do the work. 2570 if (!BaseType->isRecordType()) { 2571 // C++ [basic.lookup.classref]p2: 2572 // [...] If the type of the object expression is of pointer to scalar 2573 // type, the unqualified-id is looked up in the context of the complete 2574 // postfix-expression. 2575 // 2576 // This also indicates that we should be parsing a 2577 // pseudo-destructor-name. 2578 ObjectType = 0; 2579 MayBePseudoDestructor = true; 2580 return move(Base); 2581 } 2582 2583 // The object type must be complete (or dependent). 2584 if (!BaseType->isDependentType() && 2585 RequireCompleteType(OpLoc, BaseType, 2586 PDiag(diag::err_incomplete_member_access))) 2587 return ExprError(); 2588 2589 // C++ [basic.lookup.classref]p2: 2590 // If the id-expression in a class member access (5.2.5) is an 2591 // unqualified-id, and the type of the object expression is of a class 2592 // type C (or of pointer to a class type C), the unqualified-id is looked 2593 // up in the scope of class C. [...] 2594 ObjectType = BaseType.getAsOpaquePtr(); 2595 return move(Base); 2596} 2597 2598Sema::OwningExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc, 2599 ExprArg MemExpr) { 2600 Expr *E = (Expr *) MemExpr.get(); 2601 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc); 2602 Diag(E->getLocStart(), diag::err_dtor_expr_without_call) 2603 << isa<CXXPseudoDestructorExpr>(E) 2604 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()"); 2605 2606 return ActOnCallExpr(/*Scope*/ 0, 2607 move(MemExpr), 2608 /*LPLoc*/ ExpectedLParenLoc, 2609 Sema::MultiExprArg(*this, 0, 0), 2610 /*CommaLocs*/ 0, 2611 /*RPLoc*/ ExpectedLParenLoc); 2612} 2613 2614Sema::OwningExprResult Sema::BuildPseudoDestructorExpr(ExprArg Base, 2615 SourceLocation OpLoc, 2616 tok::TokenKind OpKind, 2617 const CXXScopeSpec &SS, 2618 TypeSourceInfo *ScopeTypeInfo, 2619 SourceLocation CCLoc, 2620 SourceLocation TildeLoc, 2621 PseudoDestructorTypeStorage Destructed, 2622 bool HasTrailingLParen) { 2623 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo(); 2624 2625 // C++ [expr.pseudo]p2: 2626 // The left-hand side of the dot operator shall be of scalar type. The 2627 // left-hand side of the arrow operator shall be of pointer to scalar type. 2628 // This scalar type is the object type. 2629 Expr *BaseE = (Expr *)Base.get(); 2630 QualType ObjectType = BaseE->getType(); 2631 if (OpKind == tok::arrow) { 2632 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) { 2633 ObjectType = Ptr->getPointeeType(); 2634 } else if (!BaseE->isTypeDependent()) { 2635 // The user wrote "p->" when she probably meant "p."; fix it. 2636 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 2637 << ObjectType << true 2638 << CodeModificationHint::CreateReplacement(OpLoc, "."); 2639 if (isSFINAEContext()) 2640 return ExprError(); 2641 2642 OpKind = tok::period; 2643 } 2644 } 2645 2646 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) { 2647 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar) 2648 << ObjectType << BaseE->getSourceRange(); 2649 return ExprError(); 2650 } 2651 2652 // C++ [expr.pseudo]p2: 2653 // [...] The cv-unqualified versions of the object type and of the type 2654 // designated by the pseudo-destructor-name shall be the same type. 2655 if (DestructedTypeInfo) { 2656 QualType DestructedType = DestructedTypeInfo->getType(); 2657 SourceLocation DestructedTypeStart 2658 = DestructedTypeInfo->getTypeLoc().getSourceRange().getBegin(); 2659 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() && 2660 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) { 2661 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch) 2662 << ObjectType << DestructedType << BaseE->getSourceRange() 2663 << DestructedTypeInfo->getTypeLoc().getSourceRange(); 2664 2665 // Recover by setting the destructed type to the object type. 2666 DestructedType = ObjectType; 2667 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType, 2668 DestructedTypeStart); 2669 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 2670 } 2671 } 2672 2673 // C++ [expr.pseudo]p2: 2674 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the 2675 // form 2676 // 2677 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name 2678 // 2679 // shall designate the same scalar type. 2680 if (ScopeTypeInfo) { 2681 QualType ScopeType = ScopeTypeInfo->getType(); 2682 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() && 2683 !Context.hasSameType(ScopeType, ObjectType)) { 2684 2685 Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(), 2686 diag::err_pseudo_dtor_type_mismatch) 2687 << ObjectType << ScopeType << BaseE->getSourceRange() 2688 << ScopeTypeInfo->getTypeLoc().getSourceRange(); 2689 2690 ScopeType = QualType(); 2691 ScopeTypeInfo = 0; 2692 } 2693 } 2694 2695 OwningExprResult Result 2696 = Owned(new (Context) CXXPseudoDestructorExpr(Context, 2697 Base.takeAs<Expr>(), 2698 OpKind == tok::arrow, 2699 OpLoc, 2700 (NestedNameSpecifier *) SS.getScopeRep(), 2701 SS.getRange(), 2702 ScopeTypeInfo, 2703 CCLoc, 2704 TildeLoc, 2705 Destructed)); 2706 2707 if (HasTrailingLParen) 2708 return move(Result); 2709 2710 return DiagnoseDtorReference(Destructed.getLocation(), move(Result)); 2711} 2712 2713Sema::OwningExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, ExprArg Base, 2714 SourceLocation OpLoc, 2715 tok::TokenKind OpKind, 2716 const CXXScopeSpec &SS, 2717 UnqualifiedId &FirstTypeName, 2718 SourceLocation CCLoc, 2719 SourceLocation TildeLoc, 2720 UnqualifiedId &SecondTypeName, 2721 bool HasTrailingLParen) { 2722 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId || 2723 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) && 2724 "Invalid first type name in pseudo-destructor"); 2725 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId || 2726 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) && 2727 "Invalid second type name in pseudo-destructor"); 2728 2729 Expr *BaseE = (Expr *)Base.get(); 2730 2731 // C++ [expr.pseudo]p2: 2732 // The left-hand side of the dot operator shall be of scalar type. The 2733 // left-hand side of the arrow operator shall be of pointer to scalar type. 2734 // This scalar type is the object type. 2735 QualType ObjectType = BaseE->getType(); 2736 if (OpKind == tok::arrow) { 2737 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) { 2738 ObjectType = Ptr->getPointeeType(); 2739 } else if (!ObjectType->isDependentType()) { 2740 // The user wrote "p->" when she probably meant "p."; fix it. 2741 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 2742 << ObjectType << true 2743 << CodeModificationHint::CreateReplacement(OpLoc, "."); 2744 if (isSFINAEContext()) 2745 return ExprError(); 2746 2747 OpKind = tok::period; 2748 } 2749 } 2750 2751 // Compute the object type that we should use for name lookup purposes. Only 2752 // record types and dependent types matter. 2753 void *ObjectTypePtrForLookup = 0; 2754 if (!SS.isSet()) { 2755 ObjectTypePtrForLookup = (void *)ObjectType->getAs<RecordType>(); 2756 if (!ObjectTypePtrForLookup && ObjectType->isDependentType()) 2757 ObjectTypePtrForLookup = Context.DependentTy.getAsOpaquePtr(); 2758 } 2759 2760 // Convert the name of the type being destructed (following the ~) into a 2761 // type (with source-location information). 2762 QualType DestructedType; 2763 TypeSourceInfo *DestructedTypeInfo = 0; 2764 PseudoDestructorTypeStorage Destructed; 2765 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) { 2766 TypeTy *T = getTypeName(*SecondTypeName.Identifier, 2767 SecondTypeName.StartLocation, 2768 S, &SS, true, ObjectTypePtrForLookup); 2769 if (!T && 2770 ((SS.isSet() && !computeDeclContext(SS, false)) || 2771 (!SS.isSet() && ObjectType->isDependentType()))) { 2772 // The name of the type being destroyed is a dependent name, and we 2773 // couldn't find anything useful in scope. Just store the identifier and 2774 // it's location, and we'll perform (qualified) name lookup again at 2775 // template instantiation time. 2776 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier, 2777 SecondTypeName.StartLocation); 2778 } else if (!T) { 2779 Diag(SecondTypeName.StartLocation, 2780 diag::err_pseudo_dtor_destructor_non_type) 2781 << SecondTypeName.Identifier << ObjectType; 2782 if (isSFINAEContext()) 2783 return ExprError(); 2784 2785 // Recover by assuming we had the right type all along. 2786 DestructedType = ObjectType; 2787 } else 2788 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo); 2789 } else { 2790 // Resolve the template-id to a type. 2791 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId; 2792 ASTTemplateArgsPtr TemplateArgsPtr(*this, 2793 TemplateId->getTemplateArgs(), 2794 TemplateId->NumArgs); 2795 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template), 2796 TemplateId->TemplateNameLoc, 2797 TemplateId->LAngleLoc, 2798 TemplateArgsPtr, 2799 TemplateId->RAngleLoc); 2800 if (T.isInvalid() || !T.get()) { 2801 // Recover by assuming we had the right type all along. 2802 DestructedType = ObjectType; 2803 } else 2804 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo); 2805 } 2806 2807 // If we've performed some kind of recovery, (re-)build the type source 2808 // information. 2809 if (!DestructedType.isNull()) { 2810 if (!DestructedTypeInfo) 2811 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType, 2812 SecondTypeName.StartLocation); 2813 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 2814 } 2815 2816 // Convert the name of the scope type (the type prior to '::') into a type. 2817 TypeSourceInfo *ScopeTypeInfo = 0; 2818 QualType ScopeType; 2819 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId || 2820 FirstTypeName.Identifier) { 2821 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) { 2822 TypeTy *T = getTypeName(*FirstTypeName.Identifier, 2823 FirstTypeName.StartLocation, 2824 S, &SS, false, ObjectTypePtrForLookup); 2825 if (!T) { 2826 Diag(FirstTypeName.StartLocation, 2827 diag::err_pseudo_dtor_destructor_non_type) 2828 << FirstTypeName.Identifier << ObjectType; 2829 2830 if (isSFINAEContext()) 2831 return ExprError(); 2832 2833 // Just drop this type. It's unnecessary anyway. 2834 ScopeType = QualType(); 2835 } else 2836 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo); 2837 } else { 2838 // Resolve the template-id to a type. 2839 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId; 2840 ASTTemplateArgsPtr TemplateArgsPtr(*this, 2841 TemplateId->getTemplateArgs(), 2842 TemplateId->NumArgs); 2843 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template), 2844 TemplateId->TemplateNameLoc, 2845 TemplateId->LAngleLoc, 2846 TemplateArgsPtr, 2847 TemplateId->RAngleLoc); 2848 if (T.isInvalid() || !T.get()) { 2849 // Recover by dropping this type. 2850 ScopeType = QualType(); 2851 } else 2852 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo); 2853 } 2854 } 2855 2856 if (!ScopeType.isNull() && !ScopeTypeInfo) 2857 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType, 2858 FirstTypeName.StartLocation); 2859 2860 2861 return BuildPseudoDestructorExpr(move(Base), OpLoc, OpKind, SS, 2862 ScopeTypeInfo, CCLoc, TildeLoc, 2863 Destructed, HasTrailingLParen); 2864} 2865 2866CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp, 2867 CXXMethodDecl *Method) { 2868 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0, Method)) 2869 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?"); 2870 2871 MemberExpr *ME = 2872 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method, 2873 SourceLocation(), Method->getType()); 2874 QualType ResultType = Method->getResultType().getNonReferenceType(); 2875 MarkDeclarationReferenced(Exp->getLocStart(), Method); 2876 CXXMemberCallExpr *CE = 2877 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, 2878 Exp->getLocEnd()); 2879 return CE; 2880} 2881 2882Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc, 2883 QualType Ty, 2884 CastExpr::CastKind Kind, 2885 CXXMethodDecl *Method, 2886 ExprArg Arg) { 2887 Expr *From = Arg.takeAs<Expr>(); 2888 2889 switch (Kind) { 2890 default: assert(0 && "Unhandled cast kind!"); 2891 case CastExpr::CK_ConstructorConversion: { 2892 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this); 2893 2894 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method), 2895 MultiExprArg(*this, (void **)&From, 1), 2896 CastLoc, ConstructorArgs)) 2897 return ExprError(); 2898 2899 OwningExprResult Result = 2900 BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method), 2901 move_arg(ConstructorArgs)); 2902 if (Result.isInvalid()) 2903 return ExprError(); 2904 2905 return MaybeBindToTemporary(Result.takeAs<Expr>()); 2906 } 2907 2908 case CastExpr::CK_UserDefinedConversion: { 2909 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!"); 2910 2911 // Create an implicit call expr that calls it. 2912 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method); 2913 return MaybeBindToTemporary(CE); 2914 } 2915 } 2916} 2917 2918Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) { 2919 Expr *FullExpr = Arg.takeAs<Expr>(); 2920 if (FullExpr) 2921 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr); 2922 2923 return Owned(FullExpr); 2924} 2925