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