SemaExprCXX.cpp revision fc2844846e91398205fddc71196fe9dda04e105f
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/Basic/PartialDiagnostic.h" 21#include "clang/Basic/TargetInfo.h" 22#include "clang/Lex/Preprocessor.h" 23#include "clang/Parse/DeclSpec.h" 24#include "llvm/ADT/STLExtras.h" 25using namespace clang; 26 27/// ActOnCXXTypeidOfType - Parse typeid( type-id ). 28Action::OwningExprResult 29Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, 30 bool isType, void *TyOrExpr, SourceLocation RParenLoc) { 31 if (!StdNamespace) 32 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); 33 34 if (isType) 35 // FIXME: Preserve type source info. 36 TyOrExpr = GetTypeFromParser(TyOrExpr).getAsOpaquePtr(); 37 38 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info"); 39 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName); 40 LookupQualifiedName(R, StdNamespace); 41 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>(); 42 if (!TypeInfoRecordDecl) 43 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); 44 45 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl); 46 47 if (!isType) { 48 // C++0x [expr.typeid]p3: 49 // When typeid is applied to an expression other than an lvalue of a 50 // polymorphic class type [...] [the] expression is an unevaluated 51 // operand. 52 53 // FIXME: if the type of the expression is a class type, the class 54 // shall be completely defined. 55 bool isUnevaluatedOperand = true; 56 Expr *E = static_cast<Expr *>(TyOrExpr); 57 if (E && !E->isTypeDependent() && E->isLvalue(Context) == Expr::LV_Valid) { 58 QualType T = E->getType(); 59 if (const RecordType *RecordT = T->getAs<RecordType>()) { 60 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl()); 61 if (RecordD->isPolymorphic()) 62 isUnevaluatedOperand = false; 63 } 64 } 65 66 // If this is an unevaluated operand, clear out the set of 67 // declaration references we have been computing and eliminate any 68 // temporaries introduced in its computation. 69 if (isUnevaluatedOperand) 70 ExprEvalContexts.back().Context = Unevaluated; 71 } 72 73 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr, 74 TypeInfoType.withConst(), 75 SourceRange(OpLoc, RParenLoc))); 76} 77 78/// ActOnCXXBoolLiteral - Parse {true,false} literals. 79Action::OwningExprResult 80Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 81 assert((Kind == tok::kw_true || Kind == tok::kw_false) && 82 "Unknown C++ Boolean value!"); 83 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true, 84 Context.BoolTy, OpLoc)); 85} 86 87/// ActOnCXXNullPtrLiteral - Parse 'nullptr'. 88Action::OwningExprResult 89Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) { 90 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc)); 91} 92 93/// ActOnCXXThrow - Parse throw expressions. 94Action::OwningExprResult 95Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) { 96 Expr *Ex = E.takeAs<Expr>(); 97 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex)) 98 return ExprError(); 99 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc)); 100} 101 102/// CheckCXXThrowOperand - Validate the operand of a throw. 103bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) { 104 // C++ [except.throw]p3: 105 // [...] adjusting the type from "array of T" or "function returning T" 106 // to "pointer to T" or "pointer to function returning T", [...] 107 DefaultFunctionArrayConversion(E); 108 109 // If the type of the exception would be an incomplete type or a pointer 110 // to an incomplete type other than (cv) void the program is ill-formed. 111 QualType Ty = E->getType(); 112 int isPointer = 0; 113 if (const PointerType* Ptr = Ty->getAs<PointerType>()) { 114 Ty = Ptr->getPointeeType(); 115 isPointer = 1; 116 } 117 if (!isPointer || !Ty->isVoidType()) { 118 if (RequireCompleteType(ThrowLoc, Ty, 119 PDiag(isPointer ? diag::err_throw_incomplete_ptr 120 : diag::err_throw_incomplete) 121 << E->getSourceRange())) 122 return true; 123 } 124 125 // FIXME: Construct a temporary here. 126 return false; 127} 128 129Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) { 130 /// C++ 9.3.2: In the body of a non-static member function, the keyword this 131 /// is a non-lvalue expression whose value is the address of the object for 132 /// which the function is called. 133 134 if (!isa<FunctionDecl>(CurContext)) 135 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use)); 136 137 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) 138 if (MD->isInstance()) 139 return Owned(new (Context) CXXThisExpr(ThisLoc, 140 MD->getThisType(Context))); 141 142 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use)); 143} 144 145/// ActOnCXXTypeConstructExpr - Parse construction of a specified type. 146/// Can be interpreted either as function-style casting ("int(x)") 147/// or class type construction ("ClassType(x,y,z)") 148/// or creation of a value-initialized type ("int()"). 149Action::OwningExprResult 150Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep, 151 SourceLocation LParenLoc, 152 MultiExprArg exprs, 153 SourceLocation *CommaLocs, 154 SourceLocation RParenLoc) { 155 assert(TypeRep && "Missing type!"); 156 // FIXME: Preserve type source info. 157 QualType Ty = GetTypeFromParser(TypeRep); 158 unsigned NumExprs = exprs.size(); 159 Expr **Exprs = (Expr**)exprs.get(); 160 SourceLocation TyBeginLoc = TypeRange.getBegin(); 161 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc); 162 163 if (Ty->isDependentType() || 164 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) { 165 exprs.release(); 166 167 return Owned(CXXUnresolvedConstructExpr::Create(Context, 168 TypeRange.getBegin(), Ty, 169 LParenLoc, 170 Exprs, NumExprs, 171 RParenLoc)); 172 } 173 174 if (Ty->isArrayType()) 175 return ExprError(Diag(TyBeginLoc, 176 diag::err_value_init_for_array_type) << FullRange); 177 if (!Ty->isVoidType() && 178 RequireCompleteType(TyBeginLoc, Ty, 179 PDiag(diag::err_invalid_incomplete_type_use) 180 << FullRange)) 181 return ExprError(); 182 183 if (RequireNonAbstractType(TyBeginLoc, Ty, 184 diag::err_allocation_of_abstract_type)) 185 return ExprError(); 186 187 188 // C++ [expr.type.conv]p1: 189 // If the expression list is a single expression, the type conversion 190 // expression is equivalent (in definedness, and if defined in meaning) to the 191 // corresponding cast expression. 192 // 193 if (NumExprs == 1) { 194 CastExpr::CastKind Kind = CastExpr::CK_Unknown; 195 CXXMethodDecl *Method = 0; 196 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method, 197 /*FunctionalStyle=*/true)) 198 return ExprError(); 199 200 exprs.release(); 201 if (Method) { 202 OwningExprResult CastArg 203 = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(), 204 Kind, Method, Owned(Exprs[0])); 205 if (CastArg.isInvalid()) 206 return ExprError(); 207 208 Exprs[0] = CastArg.takeAs<Expr>(); 209 } 210 211 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(), 212 Ty, TyBeginLoc, Kind, 213 Exprs[0], RParenLoc)); 214 } 215 216 if (const RecordType *RT = Ty->getAs<RecordType>()) { 217 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl()); 218 219 if (NumExprs > 1 || !Record->hasTrivialConstructor() || 220 !Record->hasTrivialDestructor()) { 221 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this); 222 223 CXXConstructorDecl *Constructor 224 = PerformInitializationByConstructor(Ty, move(exprs), 225 TypeRange.getBegin(), 226 SourceRange(TypeRange.getBegin(), 227 RParenLoc), 228 DeclarationName(), 229 InitializationKind::CreateDirect(TypeRange.getBegin(), 230 LParenLoc, 231 RParenLoc), 232 ConstructorArgs); 233 234 if (!Constructor) 235 return ExprError(); 236 237 OwningExprResult Result = 238 BuildCXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc, 239 move_arg(ConstructorArgs), RParenLoc); 240 if (Result.isInvalid()) 241 return ExprError(); 242 243 return MaybeBindToTemporary(Result.takeAs<Expr>()); 244 } 245 246 // Fall through to value-initialize an object of class type that 247 // doesn't have a user-declared default constructor. 248 } 249 250 // C++ [expr.type.conv]p1: 251 // If the expression list specifies more than a single value, the type shall 252 // be a class with a suitably declared constructor. 253 // 254 if (NumExprs > 1) 255 return ExprError(Diag(CommaLocs[0], 256 diag::err_builtin_func_cast_more_than_one_arg) 257 << FullRange); 258 259 assert(NumExprs == 0 && "Expected 0 expressions"); 260 // C++ [expr.type.conv]p2: 261 // The expression T(), where T is a simple-type-specifier for a non-array 262 // complete object type or the (possibly cv-qualified) void type, creates an 263 // rvalue of the specified type, which is value-initialized. 264 // 265 exprs.release(); 266 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc)); 267} 268 269 270/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.: 271/// @code new (memory) int[size][4] @endcode 272/// or 273/// @code ::new Foo(23, "hello") @endcode 274/// For the interpretation of this heap of arguments, consult the base version. 275Action::OwningExprResult 276Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 277 SourceLocation PlacementLParen, MultiExprArg PlacementArgs, 278 SourceLocation PlacementRParen, bool ParenTypeId, 279 Declarator &D, SourceLocation ConstructorLParen, 280 MultiExprArg ConstructorArgs, 281 SourceLocation ConstructorRParen) { 282 Expr *ArraySize = 0; 283 // If the specified type is an array, unwrap it and save the expression. 284 if (D.getNumTypeObjects() > 0 && 285 D.getTypeObject(0).Kind == DeclaratorChunk::Array) { 286 DeclaratorChunk &Chunk = D.getTypeObject(0); 287 if (Chunk.Arr.hasStatic) 288 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new) 289 << D.getSourceRange()); 290 if (!Chunk.Arr.NumElts) 291 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size) 292 << D.getSourceRange()); 293 294 if (ParenTypeId) { 295 // Can't have dynamic array size when the type-id is in parentheses. 296 Expr *NumElts = (Expr *)Chunk.Arr.NumElts; 297 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() && 298 !NumElts->isIntegerConstantExpr(Context)) { 299 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst) 300 << NumElts->getSourceRange(); 301 return ExprError(); 302 } 303 } 304 305 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts); 306 D.DropFirstTypeObject(); 307 } 308 309 // Every dimension shall be of constant size. 310 if (ArraySize) { 311 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) { 312 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array) 313 break; 314 315 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr; 316 if (Expr *NumElts = (Expr *)Array.NumElts) { 317 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() && 318 !NumElts->isIntegerConstantExpr(Context)) { 319 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst) 320 << NumElts->getSourceRange(); 321 return ExprError(); 322 } 323 } 324 } 325 } 326 327 //FIXME: Store TypeSourceInfo in CXXNew expression. 328 TypeSourceInfo *TInfo = 0; 329 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo); 330 if (D.isInvalidType()) 331 return ExprError(); 332 333 return BuildCXXNew(StartLoc, UseGlobal, 334 PlacementLParen, 335 move(PlacementArgs), 336 PlacementRParen, 337 ParenTypeId, 338 AllocType, 339 D.getSourceRange().getBegin(), 340 D.getSourceRange(), 341 Owned(ArraySize), 342 ConstructorLParen, 343 move(ConstructorArgs), 344 ConstructorRParen); 345} 346 347Sema::OwningExprResult 348Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal, 349 SourceLocation PlacementLParen, 350 MultiExprArg PlacementArgs, 351 SourceLocation PlacementRParen, 352 bool ParenTypeId, 353 QualType AllocType, 354 SourceLocation TypeLoc, 355 SourceRange TypeRange, 356 ExprArg ArraySizeE, 357 SourceLocation ConstructorLParen, 358 MultiExprArg ConstructorArgs, 359 SourceLocation ConstructorRParen) { 360 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange)) 361 return ExprError(); 362 363 QualType ResultType = Context.getPointerType(AllocType); 364 365 // That every array dimension except the first is constant was already 366 // checked by the type check above. 367 368 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral 369 // or enumeration type with a non-negative value." 370 Expr *ArraySize = (Expr *)ArraySizeE.get(); 371 if (ArraySize && !ArraySize->isTypeDependent()) { 372 QualType SizeType = ArraySize->getType(); 373 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType()) 374 return ExprError(Diag(ArraySize->getSourceRange().getBegin(), 375 diag::err_array_size_not_integral) 376 << SizeType << ArraySize->getSourceRange()); 377 // Let's see if this is a constant < 0. If so, we reject it out of hand. 378 // We don't care about special rules, so we tell the machinery it's not 379 // evaluated - it gives us a result in more cases. 380 if (!ArraySize->isValueDependent()) { 381 llvm::APSInt Value; 382 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) { 383 if (Value < llvm::APSInt( 384 llvm::APInt::getNullValue(Value.getBitWidth()), 385 Value.isUnsigned())) 386 return ExprError(Diag(ArraySize->getSourceRange().getBegin(), 387 diag::err_typecheck_negative_array_size) 388 << ArraySize->getSourceRange()); 389 } 390 } 391 392 ImpCastExprToType(ArraySize, Context.getSizeType(), 393 CastExpr::CK_IntegralCast); 394 } 395 396 FunctionDecl *OperatorNew = 0; 397 FunctionDecl *OperatorDelete = 0; 398 Expr **PlaceArgs = (Expr**)PlacementArgs.get(); 399 unsigned NumPlaceArgs = PlacementArgs.size(); 400 401 if (!AllocType->isDependentType() && 402 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) && 403 FindAllocationFunctions(StartLoc, 404 SourceRange(PlacementLParen, PlacementRParen), 405 UseGlobal, AllocType, ArraySize, PlaceArgs, 406 NumPlaceArgs, OperatorNew, OperatorDelete)) 407 return ExprError(); 408 llvm::SmallVector<Expr *, 8> AllPlaceArgs; 409 if (OperatorNew) { 410 // Add default arguments, if any. 411 const FunctionProtoType *Proto = 412 OperatorNew->getType()->getAs<FunctionProtoType>(); 413 VariadicCallType CallType = 414 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply; 415 bool Invalid = GatherArgumentsForCall(PlacementLParen, OperatorNew, 416 Proto, 1, PlaceArgs, NumPlaceArgs, 417 AllPlaceArgs, CallType); 418 if (Invalid) 419 return ExprError(); 420 421 NumPlaceArgs = AllPlaceArgs.size(); 422 if (NumPlaceArgs > 0) 423 PlaceArgs = &AllPlaceArgs[0]; 424 } 425 426 bool Init = ConstructorLParen.isValid(); 427 // --- Choosing a constructor --- 428 CXXConstructorDecl *Constructor = 0; 429 Expr **ConsArgs = (Expr**)ConstructorArgs.get(); 430 unsigned NumConsArgs = ConstructorArgs.size(); 431 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this); 432 433 if (!AllocType->isDependentType() && 434 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) { 435 // C++0x [expr.new]p15: 436 // A new-expression that creates an object of type T initializes that 437 // object as follows: 438 InitializationKind Kind 439 // - If the new-initializer is omitted, the object is default- 440 // initialized (8.5); if no initialization is performed, 441 // the object has indeterminate value 442 = !Init? InitializationKind::CreateDefault(TypeLoc) 443 // - Otherwise, the new-initializer is interpreted according to the 444 // initialization rules of 8.5 for direct-initialization. 445 : InitializationKind::CreateDirect(TypeLoc, 446 ConstructorLParen, 447 ConstructorRParen); 448 449 // FIXME: We shouldn't have to fake this. 450 TypeSourceInfo *TInfo 451 = Context.getTrivialTypeSourceInfo(AllocType, TypeLoc); 452 InitializedEntity Entity 453 = InitializedEntity::InitializeTemporary(TInfo->getTypeLoc()); 454 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs); 455 456 if (!InitSeq) { 457 InitSeq.Diagnose(*this, Entity, Kind, ConsArgs, NumConsArgs); 458 return ExprError(); 459 } 460 461 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, 462 move(ConstructorArgs)); 463 if (FullInit.isInvalid()) 464 return ExprError(); 465 466 // FullInit is our initializer; walk through it to determine if it's a 467 // constructor call, which CXXNewExpr handles directly. 468 if (Expr *FullInitExpr = (Expr *)FullInit.get()) { 469 if (CXXBindTemporaryExpr *Binder 470 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr)) 471 FullInitExpr = Binder->getSubExpr(); 472 if (CXXConstructExpr *Construct 473 = dyn_cast<CXXConstructExpr>(FullInitExpr)) { 474 Constructor = Construct->getConstructor(); 475 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(), 476 AEnd = Construct->arg_end(); 477 A != AEnd; ++A) 478 ConvertedConstructorArgs.push_back(A->Retain()); 479 } else { 480 // Take the converted initializer. 481 ConvertedConstructorArgs.push_back(FullInit.release()); 482 } 483 } else { 484 // No initialization required. 485 } 486 487 // Take the converted arguments and use them for the new expression. 488 NumConsArgs = ConvertedConstructorArgs.size(); 489 ConsArgs = (Expr **)ConvertedConstructorArgs.take(); 490 } 491 492 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16) 493 494 PlacementArgs.release(); 495 ConstructorArgs.release(); 496 ArraySizeE.release(); 497 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs, 498 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init, 499 ConsArgs, NumConsArgs, OperatorDelete, ResultType, 500 StartLoc, Init ? ConstructorRParen : SourceLocation())); 501} 502 503/// CheckAllocatedType - Checks that a type is suitable as the allocated type 504/// in a new-expression. 505/// dimension off and stores the size expression in ArraySize. 506bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc, 507 SourceRange R) { 508 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an 509 // abstract class type or array thereof. 510 if (AllocType->isFunctionType()) 511 return Diag(Loc, diag::err_bad_new_type) 512 << AllocType << 0 << R; 513 else if (AllocType->isReferenceType()) 514 return Diag(Loc, diag::err_bad_new_type) 515 << AllocType << 1 << R; 516 else if (!AllocType->isDependentType() && 517 RequireCompleteType(Loc, AllocType, 518 PDiag(diag::err_new_incomplete_type) 519 << R)) 520 return true; 521 else if (RequireNonAbstractType(Loc, AllocType, 522 diag::err_allocation_of_abstract_type)) 523 return true; 524 525 return false; 526} 527 528/// FindAllocationFunctions - Finds the overloads of operator new and delete 529/// that are appropriate for the allocation. 530bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 531 bool UseGlobal, QualType AllocType, 532 bool IsArray, Expr **PlaceArgs, 533 unsigned NumPlaceArgs, 534 FunctionDecl *&OperatorNew, 535 FunctionDecl *&OperatorDelete) { 536 // --- Choosing an allocation function --- 537 // C++ 5.3.4p8 - 14 & 18 538 // 1) If UseGlobal is true, only look in the global scope. Else, also look 539 // in the scope of the allocated class. 540 // 2) If an array size is given, look for operator new[], else look for 541 // operator new. 542 // 3) The first argument is always size_t. Append the arguments from the 543 // placement form. 544 // FIXME: Also find the appropriate delete operator. 545 546 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs); 547 // We don't care about the actual value of this argument. 548 // FIXME: Should the Sema create the expression and embed it in the syntax 549 // tree? Or should the consumer just recalculate the value? 550 IntegerLiteral Size(llvm::APInt::getNullValue( 551 Context.Target.getPointerWidth(0)), 552 Context.getSizeType(), 553 SourceLocation()); 554 AllocArgs[0] = &Size; 555 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1); 556 557 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName( 558 IsArray ? OO_Array_New : OO_New); 559 if (AllocType->isRecordType() && !UseGlobal) { 560 CXXRecordDecl *Record 561 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl()); 562 // FIXME: We fail to find inherited overloads. 563 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0], 564 AllocArgs.size(), Record, /*AllowMissing=*/true, 565 OperatorNew)) 566 return true; 567 } 568 if (!OperatorNew) { 569 // Didn't find a member overload. Look for a global one. 570 DeclareGlobalNewDelete(); 571 DeclContext *TUDecl = Context.getTranslationUnitDecl(); 572 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0], 573 AllocArgs.size(), TUDecl, /*AllowMissing=*/false, 574 OperatorNew)) 575 return true; 576 } 577 578 // FindAllocationOverload can change the passed in arguments, so we need to 579 // copy them back. 580 if (NumPlaceArgs > 0) 581 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs); 582 583 return false; 584} 585 586/// FindAllocationOverload - Find an fitting overload for the allocation 587/// function in the specified scope. 588bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range, 589 DeclarationName Name, Expr** Args, 590 unsigned NumArgs, DeclContext *Ctx, 591 bool AllowMissing, FunctionDecl *&Operator) { 592 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName); 593 LookupQualifiedName(R, Ctx); 594 if (R.empty()) { 595 if (AllowMissing) 596 return false; 597 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) 598 << Name << Range; 599 } 600 601 // FIXME: handle ambiguity 602 603 OverloadCandidateSet Candidates; 604 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end(); 605 Alloc != AllocEnd; ++Alloc) { 606 // Even member operator new/delete are implicitly treated as 607 // static, so don't use AddMemberCandidate. 608 if (FunctionDecl *Fn = 609 dyn_cast<FunctionDecl>((*Alloc)->getUnderlyingDecl())) { 610 AddOverloadCandidate(Fn, Args, NumArgs, Candidates, 611 /*SuppressUserConversions=*/false); 612 continue; 613 } 614 615 // FIXME: Handle function templates 616 } 617 618 // Do the resolution. 619 OverloadCandidateSet::iterator Best; 620 switch(BestViableFunction(Candidates, StartLoc, Best)) { 621 case OR_Success: { 622 // Got one! 623 FunctionDecl *FnDecl = Best->Function; 624 // The first argument is size_t, and the first parameter must be size_t, 625 // too. This is checked on declaration and can be assumed. (It can't be 626 // asserted on, though, since invalid decls are left in there.) 627 // Whatch out for variadic allocator function. 628 unsigned NumArgsInFnDecl = FnDecl->getNumParams(); 629 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) { 630 if (PerformCopyInitialization(Args[i], 631 FnDecl->getParamDecl(i)->getType(), 632 AA_Passing)) 633 return true; 634 } 635 Operator = FnDecl; 636 return false; 637 } 638 639 case OR_No_Viable_Function: 640 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) 641 << Name << Range; 642 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false); 643 return true; 644 645 case OR_Ambiguous: 646 Diag(StartLoc, diag::err_ovl_ambiguous_call) 647 << Name << Range; 648 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true); 649 return true; 650 651 case OR_Deleted: 652 Diag(StartLoc, diag::err_ovl_deleted_call) 653 << Best->Function->isDeleted() 654 << Name << Range; 655 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true); 656 return true; 657 } 658 assert(false && "Unreachable, bad result from BestViableFunction"); 659 return true; 660} 661 662 663/// DeclareGlobalNewDelete - Declare the global forms of operator new and 664/// delete. These are: 665/// @code 666/// void* operator new(std::size_t) throw(std::bad_alloc); 667/// void* operator new[](std::size_t) throw(std::bad_alloc); 668/// void operator delete(void *) throw(); 669/// void operator delete[](void *) throw(); 670/// @endcode 671/// Note that the placement and nothrow forms of new are *not* implicitly 672/// declared. Their use requires including \<new\>. 673void Sema::DeclareGlobalNewDelete() { 674 if (GlobalNewDeleteDeclared) 675 return; 676 677 // C++ [basic.std.dynamic]p2: 678 // [...] The following allocation and deallocation functions (18.4) are 679 // implicitly declared in global scope in each translation unit of a 680 // program 681 // 682 // void* operator new(std::size_t) throw(std::bad_alloc); 683 // void* operator new[](std::size_t) throw(std::bad_alloc); 684 // void operator delete(void*) throw(); 685 // void operator delete[](void*) throw(); 686 // 687 // These implicit declarations introduce only the function names operator 688 // new, operator new[], operator delete, operator delete[]. 689 // 690 // Here, we need to refer to std::bad_alloc, so we will implicitly declare 691 // "std" or "bad_alloc" as necessary to form the exception specification. 692 // However, we do not make these implicit declarations visible to name 693 // lookup. 694 if (!StdNamespace) { 695 // The "std" namespace has not yet been defined, so build one implicitly. 696 StdNamespace = NamespaceDecl::Create(Context, 697 Context.getTranslationUnitDecl(), 698 SourceLocation(), 699 &PP.getIdentifierTable().get("std")); 700 StdNamespace->setImplicit(true); 701 } 702 703 if (!StdBadAlloc) { 704 // The "std::bad_alloc" class has not yet been declared, so build it 705 // implicitly. 706 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class, 707 StdNamespace, 708 SourceLocation(), 709 &PP.getIdentifierTable().get("bad_alloc"), 710 SourceLocation(), 0); 711 StdBadAlloc->setImplicit(true); 712 } 713 714 GlobalNewDeleteDeclared = true; 715 716 QualType VoidPtr = Context.getPointerType(Context.VoidTy); 717 QualType SizeT = Context.getSizeType(); 718 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew; 719 720 DeclareGlobalAllocationFunction( 721 Context.DeclarationNames.getCXXOperatorName(OO_New), 722 VoidPtr, SizeT, AssumeSaneOperatorNew); 723 DeclareGlobalAllocationFunction( 724 Context.DeclarationNames.getCXXOperatorName(OO_Array_New), 725 VoidPtr, SizeT, AssumeSaneOperatorNew); 726 DeclareGlobalAllocationFunction( 727 Context.DeclarationNames.getCXXOperatorName(OO_Delete), 728 Context.VoidTy, VoidPtr); 729 DeclareGlobalAllocationFunction( 730 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete), 731 Context.VoidTy, VoidPtr); 732} 733 734/// DeclareGlobalAllocationFunction - Declares a single implicit global 735/// allocation function if it doesn't already exist. 736void Sema::DeclareGlobalAllocationFunction(DeclarationName Name, 737 QualType Return, QualType Argument, 738 bool AddMallocAttr) { 739 DeclContext *GlobalCtx = Context.getTranslationUnitDecl(); 740 741 // Check if this function is already declared. 742 { 743 DeclContext::lookup_iterator Alloc, AllocEnd; 744 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name); 745 Alloc != AllocEnd; ++Alloc) { 746 // FIXME: Do we need to check for default arguments here? 747 FunctionDecl *Func = cast<FunctionDecl>(*Alloc); 748 if (Func->getNumParams() == 1 && 749 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument) 750 return; 751 } 752 } 753 754 QualType BadAllocType; 755 bool HasBadAllocExceptionSpec 756 = (Name.getCXXOverloadedOperator() == OO_New || 757 Name.getCXXOverloadedOperator() == OO_Array_New); 758 if (HasBadAllocExceptionSpec) { 759 assert(StdBadAlloc && "Must have std::bad_alloc declared"); 760 BadAllocType = Context.getTypeDeclType(StdBadAlloc); 761 } 762 763 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0, 764 true, false, 765 HasBadAllocExceptionSpec? 1 : 0, 766 &BadAllocType); 767 FunctionDecl *Alloc = 768 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name, 769 FnType, /*TInfo=*/0, FunctionDecl::None, false, true); 770 Alloc->setImplicit(); 771 772 if (AddMallocAttr) 773 Alloc->addAttr(::new (Context) MallocAttr()); 774 775 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(), 776 0, Argument, /*TInfo=*/0, 777 VarDecl::None, 0); 778 Alloc->setParams(Context, &Param, 1); 779 780 // FIXME: Also add this declaration to the IdentifierResolver, but 781 // make sure it is at the end of the chain to coincide with the 782 // global scope. 783 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc); 784} 785 786bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, 787 DeclarationName Name, 788 FunctionDecl* &Operator) { 789 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName); 790 // Try to find operator delete/operator delete[] in class scope. 791 LookupQualifiedName(Found, RD); 792 793 if (Found.isAmbiguous()) 794 return true; 795 796 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end(); 797 F != FEnd; ++F) { 798 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F)) 799 if (Delete->isUsualDeallocationFunction()) { 800 Operator = Delete; 801 return false; 802 } 803 } 804 805 // We did find operator delete/operator delete[] declarations, but 806 // none of them were suitable. 807 if (!Found.empty()) { 808 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found) 809 << Name << RD; 810 811 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end(); 812 F != FEnd; ++F) { 813 Diag((*F)->getLocation(), 814 diag::note_delete_member_function_declared_here) 815 << Name; 816 } 817 818 return true; 819 } 820 821 // Look for a global declaration. 822 DeclareGlobalNewDelete(); 823 DeclContext *TUDecl = Context.getTranslationUnitDecl(); 824 825 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation()); 826 Expr* DeallocArgs[1]; 827 DeallocArgs[0] = &Null; 828 if (FindAllocationOverload(StartLoc, SourceRange(), Name, 829 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false, 830 Operator)) 831 return true; 832 833 assert(Operator && "Did not find a deallocation function!"); 834 return false; 835} 836 837/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in: 838/// @code ::delete ptr; @endcode 839/// or 840/// @code delete [] ptr; @endcode 841Action::OwningExprResult 842Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, 843 bool ArrayForm, ExprArg Operand) { 844 // C++ [expr.delete]p1: 845 // The operand shall have a pointer type, or a class type having a single 846 // conversion function to a pointer type. The result has type void. 847 // 848 // DR599 amends "pointer type" to "pointer to object type" in both cases. 849 850 FunctionDecl *OperatorDelete = 0; 851 852 Expr *Ex = (Expr *)Operand.get(); 853 if (!Ex->isTypeDependent()) { 854 QualType Type = Ex->getType(); 855 856 if (const RecordType *Record = Type->getAs<RecordType>()) { 857 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions; 858 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 859 const UnresolvedSet *Conversions = RD->getVisibleConversionFunctions(); 860 861 for (UnresolvedSet::iterator I = Conversions->begin(), 862 E = Conversions->end(); I != E; ++I) { 863 // Skip over templated conversion functions; they aren't considered. 864 if (isa<FunctionTemplateDecl>(*I)) 865 continue; 866 867 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I); 868 869 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 870 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 871 if (ConvPtrType->getPointeeType()->isObjectType()) 872 ObjectPtrConversions.push_back(Conv); 873 } 874 if (ObjectPtrConversions.size() == 1) { 875 // We have a single conversion to a pointer-to-object type. Perform 876 // that conversion. 877 Operand.release(); 878 if (!PerformImplicitConversion(Ex, 879 ObjectPtrConversions.front()->getConversionType(), 880 AA_Converting)) { 881 Operand = Owned(Ex); 882 Type = Ex->getType(); 883 } 884 } 885 else if (ObjectPtrConversions.size() > 1) { 886 Diag(StartLoc, diag::err_ambiguous_delete_operand) 887 << Type << Ex->getSourceRange(); 888 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) { 889 CXXConversionDecl *Conv = ObjectPtrConversions[i]; 890 Diag(Conv->getLocation(), diag::err_ovl_candidate); 891 } 892 return ExprError(); 893 } 894 } 895 896 if (!Type->isPointerType()) 897 return ExprError(Diag(StartLoc, diag::err_delete_operand) 898 << Type << Ex->getSourceRange()); 899 900 QualType Pointee = Type->getAs<PointerType>()->getPointeeType(); 901 if (Pointee->isFunctionType() || Pointee->isVoidType()) 902 return ExprError(Diag(StartLoc, diag::err_delete_operand) 903 << Type << Ex->getSourceRange()); 904 else if (!Pointee->isDependentType() && 905 RequireCompleteType(StartLoc, Pointee, 906 PDiag(diag::warn_delete_incomplete) 907 << Ex->getSourceRange())) 908 return ExprError(); 909 910 // C++ [expr.delete]p2: 911 // [Note: a pointer to a const type can be the operand of a 912 // delete-expression; it is not necessary to cast away the constness 913 // (5.2.11) of the pointer expression before it is used as the operand 914 // of the delete-expression. ] 915 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy), 916 CastExpr::CK_NoOp); 917 918 // Update the operand. 919 Operand.take(); 920 Operand = ExprArg(*this, Ex); 921 922 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( 923 ArrayForm ? OO_Array_Delete : OO_Delete); 924 925 if (const RecordType *RT = Pointee->getAs<RecordType>()) { 926 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 927 928 if (!UseGlobal && 929 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete)) 930 return ExprError(); 931 932 if (!RD->hasTrivialDestructor()) 933 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context)) 934 MarkDeclarationReferenced(StartLoc, 935 const_cast<CXXDestructorDecl*>(Dtor)); 936 } 937 938 if (!OperatorDelete) { 939 // Look for a global declaration. 940 DeclareGlobalNewDelete(); 941 DeclContext *TUDecl = Context.getTranslationUnitDecl(); 942 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName, 943 &Ex, 1, TUDecl, /*AllowMissing=*/false, 944 OperatorDelete)) 945 return ExprError(); 946 } 947 948 // FIXME: Check access and ambiguity of operator delete and destructor. 949 } 950 951 Operand.release(); 952 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm, 953 OperatorDelete, Ex, StartLoc)); 954} 955 956/// \brief Check the use of the given variable as a C++ condition in an if, 957/// while, do-while, or switch statement. 958Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar) { 959 QualType T = ConditionVar->getType(); 960 961 // C++ [stmt.select]p2: 962 // The declarator shall not specify a function or an array. 963 if (T->isFunctionType()) 964 return ExprError(Diag(ConditionVar->getLocation(), 965 diag::err_invalid_use_of_function_type) 966 << ConditionVar->getSourceRange()); 967 else if (T->isArrayType()) 968 return ExprError(Diag(ConditionVar->getLocation(), 969 diag::err_invalid_use_of_array_type) 970 << ConditionVar->getSourceRange()); 971 972 return Owned(DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar, 973 ConditionVar->getLocation(), 974 ConditionVar->getType().getNonReferenceType())); 975} 976 977/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid. 978bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) { 979 // C++ 6.4p4: 980 // The value of a condition that is an initialized declaration in a statement 981 // other than a switch statement is the value of the declared variable 982 // implicitly converted to type bool. If that conversion is ill-formed, the 983 // program is ill-formed. 984 // The value of a condition that is an expression is the value of the 985 // expression, implicitly converted to bool. 986 // 987 return PerformContextuallyConvertToBool(CondExpr); 988} 989 990/// Helper function to determine whether this is the (deprecated) C++ 991/// conversion from a string literal to a pointer to non-const char or 992/// non-const wchar_t (for narrow and wide string literals, 993/// respectively). 994bool 995Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) { 996 // Look inside the implicit cast, if it exists. 997 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From)) 998 From = Cast->getSubExpr(); 999 1000 // A string literal (2.13.4) that is not a wide string literal can 1001 // be converted to an rvalue of type "pointer to char"; a wide 1002 // string literal can be converted to an rvalue of type "pointer 1003 // to wchar_t" (C++ 4.2p2). 1004 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From)) 1005 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) 1006 if (const BuiltinType *ToPointeeType 1007 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) { 1008 // This conversion is considered only when there is an 1009 // explicit appropriate pointer target type (C++ 4.2p2). 1010 if (!ToPtrType->getPointeeType().hasQualifiers() && 1011 ((StrLit->isWide() && ToPointeeType->isWideCharType()) || 1012 (!StrLit->isWide() && 1013 (ToPointeeType->getKind() == BuiltinType::Char_U || 1014 ToPointeeType->getKind() == BuiltinType::Char_S)))) 1015 return true; 1016 } 1017 1018 return false; 1019} 1020 1021/// PerformImplicitConversion - Perform an implicit conversion of the 1022/// expression From to the type ToType. Returns true if there was an 1023/// error, false otherwise. The expression From is replaced with the 1024/// converted expression. Flavor is the kind of conversion we're 1025/// performing, used in the error message. If @p AllowExplicit, 1026/// explicit user-defined conversions are permitted. @p Elidable should be true 1027/// when called for copies which may be elided (C++ 12.8p15). C++0x overload 1028/// resolution works differently in that case. 1029bool 1030Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 1031 AssignmentAction Action, bool AllowExplicit, 1032 bool Elidable) { 1033 ImplicitConversionSequence ICS; 1034 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, 1035 Elidable, ICS); 1036} 1037 1038bool 1039Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 1040 AssignmentAction Action, bool AllowExplicit, 1041 bool Elidable, 1042 ImplicitConversionSequence& ICS) { 1043 ICS.ConversionKind = ImplicitConversionSequence::BadConversion; 1044 if (Elidable && getLangOptions().CPlusPlus0x) { 1045 ICS = TryImplicitConversion(From, ToType, 1046 /*SuppressUserConversions=*/false, 1047 AllowExplicit, 1048 /*ForceRValue=*/true, 1049 /*InOverloadResolution=*/false); 1050 } 1051 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) { 1052 ICS = TryImplicitConversion(From, ToType, 1053 /*SuppressUserConversions=*/false, 1054 AllowExplicit, 1055 /*ForceRValue=*/false, 1056 /*InOverloadResolution=*/false); 1057 } 1058 return PerformImplicitConversion(From, ToType, ICS, Action); 1059} 1060 1061/// BuildCXXDerivedToBaseExpr - This routine generates the suitable AST 1062/// for the derived to base conversion of the expression 'From'. All 1063/// necessary information is passed in ICS. 1064bool 1065Sema::BuildCXXDerivedToBaseExpr(Expr *&From, CastExpr::CastKind CastKind, 1066 const ImplicitConversionSequence& ICS) { 1067 QualType BaseType = 1068 QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr); 1069 // Must do additional defined to base conversion. 1070 QualType DerivedType = 1071 QualType::getFromOpaquePtr(ICS.UserDefined.After.FromTypePtr); 1072 1073 From = new (Context) ImplicitCastExpr( 1074 DerivedType.getNonReferenceType(), 1075 CastKind, 1076 From, 1077 DerivedType->isLValueReferenceType()); 1078 From = new (Context) ImplicitCastExpr(BaseType.getNonReferenceType(), 1079 CastExpr::CK_DerivedToBase, From, 1080 BaseType->isLValueReferenceType()); 1081 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this); 1082 OwningExprResult FromResult = 1083 BuildCXXConstructExpr( 1084 ICS.UserDefined.After.CopyConstructor->getLocation(), 1085 BaseType, 1086 ICS.UserDefined.After.CopyConstructor, 1087 MultiExprArg(*this, (void **)&From, 1)); 1088 if (FromResult.isInvalid()) 1089 return true; 1090 From = FromResult.takeAs<Expr>(); 1091 return false; 1092} 1093 1094/// PerformImplicitConversion - Perform an implicit conversion of the 1095/// expression From to the type ToType using the pre-computed implicit 1096/// conversion sequence ICS. Returns true if there was an error, false 1097/// otherwise. The expression From is replaced with the converted 1098/// expression. Action is the kind of conversion we're performing, 1099/// used in the error message. 1100bool 1101Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 1102 const ImplicitConversionSequence &ICS, 1103 AssignmentAction Action, bool IgnoreBaseAccess) { 1104 switch (ICS.ConversionKind) { 1105 case ImplicitConversionSequence::StandardConversion: 1106 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action, 1107 IgnoreBaseAccess)) 1108 return true; 1109 break; 1110 1111 case ImplicitConversionSequence::UserDefinedConversion: { 1112 1113 FunctionDecl *FD = ICS.UserDefined.ConversionFunction; 1114 CastExpr::CastKind CastKind = CastExpr::CK_Unknown; 1115 QualType BeforeToType; 1116 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) { 1117 CastKind = CastExpr::CK_UserDefinedConversion; 1118 1119 // If the user-defined conversion is specified by a conversion function, 1120 // the initial standard conversion sequence converts the source type to 1121 // the implicit object parameter of the conversion function. 1122 BeforeToType = Context.getTagDeclType(Conv->getParent()); 1123 } else if (const CXXConstructorDecl *Ctor = 1124 dyn_cast<CXXConstructorDecl>(FD)) { 1125 CastKind = CastExpr::CK_ConstructorConversion; 1126 // Do no conversion if dealing with ... for the first conversion. 1127 if (!ICS.UserDefined.EllipsisConversion) { 1128 // If the user-defined conversion is specified by a constructor, the 1129 // initial standard conversion sequence converts the source type to the 1130 // type required by the argument of the constructor 1131 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType(); 1132 } 1133 } 1134 else 1135 assert(0 && "Unknown conversion function kind!"); 1136 // Whatch out for elipsis conversion. 1137 if (!ICS.UserDefined.EllipsisConversion) { 1138 if (PerformImplicitConversion(From, BeforeToType, 1139 ICS.UserDefined.Before, AA_Converting, 1140 IgnoreBaseAccess)) 1141 return true; 1142 } 1143 1144 OwningExprResult CastArg 1145 = BuildCXXCastArgument(From->getLocStart(), 1146 ToType.getNonReferenceType(), 1147 CastKind, cast<CXXMethodDecl>(FD), 1148 Owned(From)); 1149 1150 if (CastArg.isInvalid()) 1151 return true; 1152 1153 From = CastArg.takeAs<Expr>(); 1154 1155 // FIXME: This and the following if statement shouldn't be necessary, but 1156 // there's some nasty stuff involving MaybeBindToTemporary going on here. 1157 if (ICS.UserDefined.After.Second == ICK_Derived_To_Base && 1158 ICS.UserDefined.After.CopyConstructor) { 1159 return BuildCXXDerivedToBaseExpr(From, CastKind, ICS); 1160 } 1161 1162 if (ICS.UserDefined.After.CopyConstructor) { 1163 From = new (Context) ImplicitCastExpr(ToType.getNonReferenceType(), 1164 CastKind, From, 1165 ToType->isLValueReferenceType()); 1166 return false; 1167 } 1168 1169 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After, 1170 AA_Converting, IgnoreBaseAccess); 1171 } 1172 1173 case ImplicitConversionSequence::EllipsisConversion: 1174 assert(false && "Cannot perform an ellipsis conversion"); 1175 return false; 1176 1177 case ImplicitConversionSequence::BadConversion: 1178 return true; 1179 } 1180 1181 // Everything went well. 1182 return false; 1183} 1184 1185/// PerformImplicitConversion - Perform an implicit conversion of the 1186/// expression From to the type ToType by following the standard 1187/// conversion sequence SCS. Returns true if there was an error, false 1188/// otherwise. The expression From is replaced with the converted 1189/// expression. Flavor is the context in which we're performing this 1190/// conversion, for use in error messages. 1191bool 1192Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 1193 const StandardConversionSequence& SCS, 1194 AssignmentAction Action, bool IgnoreBaseAccess) { 1195 // Overall FIXME: we are recomputing too many types here and doing far too 1196 // much extra work. What this means is that we need to keep track of more 1197 // information that is computed when we try the implicit conversion initially, 1198 // so that we don't need to recompute anything here. 1199 QualType FromType = From->getType(); 1200 1201 if (SCS.CopyConstructor) { 1202 // FIXME: When can ToType be a reference type? 1203 assert(!ToType->isReferenceType()); 1204 if (SCS.Second == ICK_Derived_To_Base) { 1205 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this); 1206 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor), 1207 MultiExprArg(*this, (void **)&From, 1), 1208 /*FIXME:ConstructLoc*/SourceLocation(), 1209 ConstructorArgs)) 1210 return true; 1211 OwningExprResult FromResult = 1212 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(), 1213 ToType, SCS.CopyConstructor, 1214 move_arg(ConstructorArgs)); 1215 if (FromResult.isInvalid()) 1216 return true; 1217 From = FromResult.takeAs<Expr>(); 1218 return false; 1219 } 1220 OwningExprResult FromResult = 1221 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(), 1222 ToType, SCS.CopyConstructor, 1223 MultiExprArg(*this, (void**)&From, 1)); 1224 1225 if (FromResult.isInvalid()) 1226 return true; 1227 1228 From = FromResult.takeAs<Expr>(); 1229 return false; 1230 } 1231 1232 // Perform the first implicit conversion. 1233 switch (SCS.First) { 1234 case ICK_Identity: 1235 case ICK_Lvalue_To_Rvalue: 1236 // Nothing to do. 1237 break; 1238 1239 case ICK_Array_To_Pointer: 1240 FromType = Context.getArrayDecayedType(FromType); 1241 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay); 1242 break; 1243 1244 case ICK_Function_To_Pointer: 1245 if (Context.getCanonicalType(FromType) == Context.OverloadTy) { 1246 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true); 1247 if (!Fn) 1248 return true; 1249 1250 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin())) 1251 return true; 1252 1253 From = FixOverloadedFunctionReference(From, Fn); 1254 FromType = From->getType(); 1255 1256 // If there's already an address-of operator in the expression, we have 1257 // the right type already, and the code below would just introduce an 1258 // invalid additional pointer level. 1259 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType()) 1260 break; 1261 } 1262 FromType = Context.getPointerType(FromType); 1263 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay); 1264 break; 1265 1266 default: 1267 assert(false && "Improper first standard conversion"); 1268 break; 1269 } 1270 1271 // Perform the second implicit conversion 1272 switch (SCS.Second) { 1273 case ICK_Identity: 1274 // If both sides are functions (or pointers/references to them), there could 1275 // be incompatible exception declarations. 1276 if (CheckExceptionSpecCompatibility(From, ToType)) 1277 return true; 1278 // Nothing else to do. 1279 break; 1280 1281 case ICK_NoReturn_Adjustment: 1282 // If both sides are functions (or pointers/references to them), there could 1283 // be incompatible exception declarations. 1284 if (CheckExceptionSpecCompatibility(From, ToType)) 1285 return true; 1286 1287 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false), 1288 CastExpr::CK_NoOp); 1289 break; 1290 1291 case ICK_Integral_Promotion: 1292 case ICK_Integral_Conversion: 1293 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast); 1294 break; 1295 1296 case ICK_Floating_Promotion: 1297 case ICK_Floating_Conversion: 1298 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast); 1299 break; 1300 1301 case ICK_Complex_Promotion: 1302 case ICK_Complex_Conversion: 1303 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown); 1304 break; 1305 1306 case ICK_Floating_Integral: 1307 if (ToType->isFloatingType()) 1308 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating); 1309 else 1310 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral); 1311 break; 1312 1313 case ICK_Complex_Real: 1314 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown); 1315 break; 1316 1317 case ICK_Compatible_Conversion: 1318 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp); 1319 break; 1320 1321 case ICK_Pointer_Conversion: { 1322 if (SCS.IncompatibleObjC) { 1323 // Diagnose incompatible Objective-C conversions 1324 Diag(From->getSourceRange().getBegin(), 1325 diag::ext_typecheck_convert_incompatible_pointer) 1326 << From->getType() << ToType << Action 1327 << From->getSourceRange(); 1328 } 1329 1330 1331 CastExpr::CastKind Kind = CastExpr::CK_Unknown; 1332 if (CheckPointerConversion(From, ToType, Kind, IgnoreBaseAccess)) 1333 return true; 1334 ImpCastExprToType(From, ToType, Kind); 1335 break; 1336 } 1337 1338 case ICK_Pointer_Member: { 1339 CastExpr::CastKind Kind = CastExpr::CK_Unknown; 1340 if (CheckMemberPointerConversion(From, ToType, Kind, IgnoreBaseAccess)) 1341 return true; 1342 if (CheckExceptionSpecCompatibility(From, ToType)) 1343 return true; 1344 ImpCastExprToType(From, ToType, Kind); 1345 break; 1346 } 1347 case ICK_Boolean_Conversion: { 1348 CastExpr::CastKind Kind = CastExpr::CK_Unknown; 1349 if (FromType->isMemberPointerType()) 1350 Kind = CastExpr::CK_MemberPointerToBoolean; 1351 1352 ImpCastExprToType(From, Context.BoolTy, Kind); 1353 break; 1354 } 1355 1356 case ICK_Derived_To_Base: 1357 if (CheckDerivedToBaseConversion(From->getType(), 1358 ToType.getNonReferenceType(), 1359 From->getLocStart(), 1360 From->getSourceRange(), 1361 IgnoreBaseAccess)) 1362 return true; 1363 ImpCastExprToType(From, ToType.getNonReferenceType(), 1364 CastExpr::CK_DerivedToBase); 1365 break; 1366 1367 default: 1368 assert(false && "Improper second standard conversion"); 1369 break; 1370 } 1371 1372 switch (SCS.Third) { 1373 case ICK_Identity: 1374 // Nothing to do. 1375 break; 1376 1377 case ICK_Qualification: 1378 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue 1379 // references. 1380 ImpCastExprToType(From, ToType.getNonReferenceType(), 1381 CastExpr::CK_NoOp, 1382 ToType->isLValueReferenceType()); 1383 break; 1384 1385 default: 1386 assert(false && "Improper second standard conversion"); 1387 break; 1388 } 1389 1390 return false; 1391} 1392 1393Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT, 1394 SourceLocation KWLoc, 1395 SourceLocation LParen, 1396 TypeTy *Ty, 1397 SourceLocation RParen) { 1398 QualType T = GetTypeFromParser(Ty); 1399 1400 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html 1401 // all traits except __is_class, __is_enum and __is_union require a the type 1402 // to be complete. 1403 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) { 1404 if (RequireCompleteType(KWLoc, T, 1405 diag::err_incomplete_type_used_in_type_trait_expr)) 1406 return ExprError(); 1407 } 1408 1409 // There is no point in eagerly computing the value. The traits are designed 1410 // to be used from type trait templates, so Ty will be a template parameter 1411 // 99% of the time. 1412 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T, 1413 RParen, Context.BoolTy)); 1414} 1415 1416QualType Sema::CheckPointerToMemberOperands( 1417 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) { 1418 const char *OpSpelling = isIndirect ? "->*" : ".*"; 1419 // C++ 5.5p2 1420 // The binary operator .* [p3: ->*] binds its second operand, which shall 1421 // be of type "pointer to member of T" (where T is a completely-defined 1422 // class type) [...] 1423 QualType RType = rex->getType(); 1424 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>(); 1425 if (!MemPtr) { 1426 Diag(Loc, diag::err_bad_memptr_rhs) 1427 << OpSpelling << RType << rex->getSourceRange(); 1428 return QualType(); 1429 } 1430 1431 QualType Class(MemPtr->getClass(), 0); 1432 1433 // C++ 5.5p2 1434 // [...] to its first operand, which shall be of class T or of a class of 1435 // which T is an unambiguous and accessible base class. [p3: a pointer to 1436 // such a class] 1437 QualType LType = lex->getType(); 1438 if (isIndirect) { 1439 if (const PointerType *Ptr = LType->getAs<PointerType>()) 1440 LType = Ptr->getPointeeType().getNonReferenceType(); 1441 else { 1442 Diag(Loc, diag::err_bad_memptr_lhs) 1443 << OpSpelling << 1 << LType 1444 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ".*"); 1445 return QualType(); 1446 } 1447 } 1448 1449 if (!Context.hasSameUnqualifiedType(Class, LType)) { 1450 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 1451 /*DetectVirtual=*/false); 1452 // FIXME: Would it be useful to print full ambiguity paths, or is that 1453 // overkill? 1454 if (!IsDerivedFrom(LType, Class, Paths) || 1455 Paths.isAmbiguous(Context.getCanonicalType(Class))) { 1456 const char *ReplaceStr = isIndirect ? ".*" : "->*"; 1457 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling 1458 << (int)isIndirect << lex->getType() << 1459 CodeModificationHint::CreateReplacement(SourceRange(Loc), ReplaceStr); 1460 return QualType(); 1461 } 1462 } 1463 1464 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) { 1465 // Diagnose use of pointer-to-member type which when used as 1466 // the functional cast in a pointer-to-member expression. 1467 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect; 1468 return QualType(); 1469 } 1470 // C++ 5.5p2 1471 // The result is an object or a function of the type specified by the 1472 // second operand. 1473 // The cv qualifiers are the union of those in the pointer and the left side, 1474 // in accordance with 5.5p5 and 5.2.5. 1475 // FIXME: This returns a dereferenced member function pointer as a normal 1476 // function type. However, the only operation valid on such functions is 1477 // calling them. There's also a GCC extension to get a function pointer to the 1478 // thing, which is another complication, because this type - unlike the type 1479 // that is the result of this expression - takes the class as the first 1480 // argument. 1481 // We probably need a "MemberFunctionClosureType" or something like that. 1482 QualType Result = MemPtr->getPointeeType(); 1483 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers()); 1484 return Result; 1485} 1486 1487/// \brief Get the target type of a standard or user-defined conversion. 1488static QualType TargetType(const ImplicitConversionSequence &ICS) { 1489 assert((ICS.ConversionKind == 1490 ImplicitConversionSequence::StandardConversion || 1491 ICS.ConversionKind == 1492 ImplicitConversionSequence::UserDefinedConversion) && 1493 "function only valid for standard or user-defined conversions"); 1494 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion) 1495 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr); 1496 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr); 1497} 1498 1499/// \brief Try to convert a type to another according to C++0x 5.16p3. 1500/// 1501/// This is part of the parameter validation for the ? operator. If either 1502/// value operand is a class type, the two operands are attempted to be 1503/// converted to each other. This function does the conversion in one direction. 1504/// It emits a diagnostic and returns true only if it finds an ambiguous 1505/// conversion. 1506static bool TryClassUnification(Sema &Self, Expr *From, Expr *To, 1507 SourceLocation QuestionLoc, 1508 ImplicitConversionSequence &ICS) { 1509 // C++0x 5.16p3 1510 // The process for determining whether an operand expression E1 of type T1 1511 // can be converted to match an operand expression E2 of type T2 is defined 1512 // as follows: 1513 // -- If E2 is an lvalue: 1514 if (To->isLvalue(Self.Context) == Expr::LV_Valid) { 1515 // E1 can be converted to match E2 if E1 can be implicitly converted to 1516 // type "lvalue reference to T2", subject to the constraint that in the 1517 // conversion the reference must bind directly to E1. 1518 if (!Self.CheckReferenceInit(From, 1519 Self.Context.getLValueReferenceType(To->getType()), 1520 To->getLocStart(), 1521 /*SuppressUserConversions=*/false, 1522 /*AllowExplicit=*/false, 1523 /*ForceRValue=*/false, 1524 &ICS)) 1525 { 1526 assert((ICS.ConversionKind == 1527 ImplicitConversionSequence::StandardConversion || 1528 ICS.ConversionKind == 1529 ImplicitConversionSequence::UserDefinedConversion) && 1530 "expected a definite conversion"); 1531 bool DirectBinding = 1532 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ? 1533 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding; 1534 if (DirectBinding) 1535 return false; 1536 } 1537 } 1538 ICS.ConversionKind = ImplicitConversionSequence::BadConversion; 1539 // -- If E2 is an rvalue, or if the conversion above cannot be done: 1540 // -- if E1 and E2 have class type, and the underlying class types are 1541 // the same or one is a base class of the other: 1542 QualType FTy = From->getType(); 1543 QualType TTy = To->getType(); 1544 const RecordType *FRec = FTy->getAs<RecordType>(); 1545 const RecordType *TRec = TTy->getAs<RecordType>(); 1546 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy); 1547 if (FRec && TRec && (FRec == TRec || 1548 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) { 1549 // E1 can be converted to match E2 if the class of T2 is the 1550 // same type as, or a base class of, the class of T1, and 1551 // [cv2 > cv1]. 1552 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) { 1553 // Could still fail if there's no copy constructor. 1554 // FIXME: Is this a hard error then, or just a conversion failure? The 1555 // standard doesn't say. 1556 ICS = Self.TryCopyInitialization(From, TTy, 1557 /*SuppressUserConversions=*/false, 1558 /*ForceRValue=*/false, 1559 /*InOverloadResolution=*/false); 1560 } 1561 } else { 1562 // -- Otherwise: E1 can be converted to match E2 if E1 can be 1563 // implicitly converted to the type that expression E2 would have 1564 // if E2 were converted to an rvalue. 1565 // First find the decayed type. 1566 if (TTy->isFunctionType()) 1567 TTy = Self.Context.getPointerType(TTy); 1568 else if (TTy->isArrayType()) 1569 TTy = Self.Context.getArrayDecayedType(TTy); 1570 1571 // Now try the implicit conversion. 1572 // FIXME: This doesn't detect ambiguities. 1573 ICS = Self.TryImplicitConversion(From, TTy, 1574 /*SuppressUserConversions=*/false, 1575 /*AllowExplicit=*/false, 1576 /*ForceRValue=*/false, 1577 /*InOverloadResolution=*/false); 1578 } 1579 return false; 1580} 1581 1582/// \brief Try to find a common type for two according to C++0x 5.16p5. 1583/// 1584/// This is part of the parameter validation for the ? operator. If either 1585/// value operand is a class type, overload resolution is used to find a 1586/// conversion to a common type. 1587static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS, 1588 SourceLocation Loc) { 1589 Expr *Args[2] = { LHS, RHS }; 1590 OverloadCandidateSet CandidateSet; 1591 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet); 1592 1593 OverloadCandidateSet::iterator Best; 1594 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) { 1595 case OR_Success: 1596 // We found a match. Perform the conversions on the arguments and move on. 1597 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0], 1598 Best->Conversions[0], Sema::AA_Converting) || 1599 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1], 1600 Best->Conversions[1], Sema::AA_Converting)) 1601 break; 1602 return false; 1603 1604 case OR_No_Viable_Function: 1605 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 1606 << LHS->getType() << RHS->getType() 1607 << LHS->getSourceRange() << RHS->getSourceRange(); 1608 return true; 1609 1610 case OR_Ambiguous: 1611 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl) 1612 << LHS->getType() << RHS->getType() 1613 << LHS->getSourceRange() << RHS->getSourceRange(); 1614 // FIXME: Print the possible common types by printing the return types of 1615 // the viable candidates. 1616 break; 1617 1618 case OR_Deleted: 1619 assert(false && "Conditional operator has only built-in overloads"); 1620 break; 1621 } 1622 return true; 1623} 1624 1625/// \brief Perform an "extended" implicit conversion as returned by 1626/// TryClassUnification. 1627/// 1628/// TryClassUnification generates ICSs that include reference bindings. 1629/// PerformImplicitConversion is not suitable for this; it chokes if the 1630/// second part of a standard conversion is ICK_DerivedToBase. This function 1631/// handles the reference binding specially. 1632static bool ConvertForConditional(Sema &Self, Expr *&E, 1633 const ImplicitConversionSequence &ICS) { 1634 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion && 1635 ICS.Standard.ReferenceBinding) { 1636 assert(ICS.Standard.DirectBinding && 1637 "TryClassUnification should never generate indirect ref bindings"); 1638 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of 1639 // redoing all the work. 1640 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType( 1641 TargetType(ICS)), 1642 /*FIXME:*/E->getLocStart(), 1643 /*SuppressUserConversions=*/false, 1644 /*AllowExplicit=*/false, 1645 /*ForceRValue=*/false); 1646 } 1647 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion && 1648 ICS.UserDefined.After.ReferenceBinding) { 1649 assert(ICS.UserDefined.After.DirectBinding && 1650 "TryClassUnification should never generate indirect ref bindings"); 1651 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType( 1652 TargetType(ICS)), 1653 /*FIXME:*/E->getLocStart(), 1654 /*SuppressUserConversions=*/false, 1655 /*AllowExplicit=*/false, 1656 /*ForceRValue=*/false); 1657 } 1658 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, Sema::AA_Converting)) 1659 return true; 1660 return false; 1661} 1662 1663/// \brief Check the operands of ?: under C++ semantics. 1664/// 1665/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y 1666/// extension. In this case, LHS == Cond. (But they're not aliases.) 1667QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS, 1668 SourceLocation QuestionLoc) { 1669 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++ 1670 // interface pointers. 1671 1672 // C++0x 5.16p1 1673 // The first expression is contextually converted to bool. 1674 if (!Cond->isTypeDependent()) { 1675 if (CheckCXXBooleanCondition(Cond)) 1676 return QualType(); 1677 } 1678 1679 // Either of the arguments dependent? 1680 if (LHS->isTypeDependent() || RHS->isTypeDependent()) 1681 return Context.DependentTy; 1682 1683 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional); 1684 1685 // C++0x 5.16p2 1686 // If either the second or the third operand has type (cv) void, ... 1687 QualType LTy = LHS->getType(); 1688 QualType RTy = RHS->getType(); 1689 bool LVoid = LTy->isVoidType(); 1690 bool RVoid = RTy->isVoidType(); 1691 if (LVoid || RVoid) { 1692 // ... then the [l2r] conversions are performed on the second and third 1693 // operands ... 1694 DefaultFunctionArrayConversion(LHS); 1695 DefaultFunctionArrayConversion(RHS); 1696 LTy = LHS->getType(); 1697 RTy = RHS->getType(); 1698 1699 // ... and one of the following shall hold: 1700 // -- The second or the third operand (but not both) is a throw- 1701 // expression; the result is of the type of the other and is an rvalue. 1702 bool LThrow = isa<CXXThrowExpr>(LHS); 1703 bool RThrow = isa<CXXThrowExpr>(RHS); 1704 if (LThrow && !RThrow) 1705 return RTy; 1706 if (RThrow && !LThrow) 1707 return LTy; 1708 1709 // -- Both the second and third operands have type void; the result is of 1710 // type void and is an rvalue. 1711 if (LVoid && RVoid) 1712 return Context.VoidTy; 1713 1714 // Neither holds, error. 1715 Diag(QuestionLoc, diag::err_conditional_void_nonvoid) 1716 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1) 1717 << LHS->getSourceRange() << RHS->getSourceRange(); 1718 return QualType(); 1719 } 1720 1721 // Neither is void. 1722 1723 // C++0x 5.16p3 1724 // Otherwise, if the second and third operand have different types, and 1725 // either has (cv) class type, and attempt is made to convert each of those 1726 // operands to the other. 1727 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) && 1728 (LTy->isRecordType() || RTy->isRecordType())) { 1729 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft; 1730 // These return true if a single direction is already ambiguous. 1731 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight)) 1732 return QualType(); 1733 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft)) 1734 return QualType(); 1735 1736 bool HaveL2R = ICSLeftToRight.ConversionKind != 1737 ImplicitConversionSequence::BadConversion; 1738 bool HaveR2L = ICSRightToLeft.ConversionKind != 1739 ImplicitConversionSequence::BadConversion; 1740 // If both can be converted, [...] the program is ill-formed. 1741 if (HaveL2R && HaveR2L) { 1742 Diag(QuestionLoc, diag::err_conditional_ambiguous) 1743 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange(); 1744 return QualType(); 1745 } 1746 1747 // If exactly one conversion is possible, that conversion is applied to 1748 // the chosen operand and the converted operands are used in place of the 1749 // original operands for the remainder of this section. 1750 if (HaveL2R) { 1751 if (ConvertForConditional(*this, LHS, ICSLeftToRight)) 1752 return QualType(); 1753 LTy = LHS->getType(); 1754 } else if (HaveR2L) { 1755 if (ConvertForConditional(*this, RHS, ICSRightToLeft)) 1756 return QualType(); 1757 RTy = RHS->getType(); 1758 } 1759 } 1760 1761 // C++0x 5.16p4 1762 // If the second and third operands are lvalues and have the same type, 1763 // the result is of that type [...] 1764 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy); 1765 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid && 1766 RHS->isLvalue(Context) == Expr::LV_Valid) 1767 return LTy; 1768 1769 // C++0x 5.16p5 1770 // Otherwise, the result is an rvalue. If the second and third operands 1771 // do not have the same type, and either has (cv) class type, ... 1772 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) { 1773 // ... overload resolution is used to determine the conversions (if any) 1774 // to be applied to the operands. If the overload resolution fails, the 1775 // program is ill-formed. 1776 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc)) 1777 return QualType(); 1778 } 1779 1780 // C++0x 5.16p6 1781 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard 1782 // conversions are performed on the second and third operands. 1783 DefaultFunctionArrayConversion(LHS); 1784 DefaultFunctionArrayConversion(RHS); 1785 LTy = LHS->getType(); 1786 RTy = RHS->getType(); 1787 1788 // After those conversions, one of the following shall hold: 1789 // -- The second and third operands have the same type; the result 1790 // is of that type. 1791 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) 1792 return LTy; 1793 1794 // -- The second and third operands have arithmetic or enumeration type; 1795 // the usual arithmetic conversions are performed to bring them to a 1796 // common type, and the result is of that type. 1797 if (LTy->isArithmeticType() && RTy->isArithmeticType()) { 1798 UsualArithmeticConversions(LHS, RHS); 1799 return LHS->getType(); 1800 } 1801 1802 // -- The second and third operands have pointer type, or one has pointer 1803 // type and the other is a null pointer constant; pointer conversions 1804 // and qualification conversions are performed to bring them to their 1805 // composite pointer type. The result is of the composite pointer type. 1806 QualType Composite = FindCompositePointerType(LHS, RHS); 1807 if (!Composite.isNull()) 1808 return Composite; 1809 1810 // Similarly, attempt to find composite type of twp objective-c pointers. 1811 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc); 1812 if (!Composite.isNull()) 1813 return Composite; 1814 1815 // Fourth bullet is same for pointers-to-member. However, the possible 1816 // conversions are far more limited: we have null-to-pointer, upcast of 1817 // containing class, and second-level cv-ness. 1818 // cv-ness is not a union, but must match one of the two operands. (Which, 1819 // frankly, is stupid.) 1820 const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>(); 1821 const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>(); 1822 if (LMemPtr && 1823 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 1824 ImpCastExprToType(RHS, LTy, CastExpr::CK_NullToMemberPointer); 1825 return LTy; 1826 } 1827 if (RMemPtr && 1828 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 1829 ImpCastExprToType(LHS, RTy, CastExpr::CK_NullToMemberPointer); 1830 return RTy; 1831 } 1832 if (LMemPtr && RMemPtr) { 1833 QualType LPointee = LMemPtr->getPointeeType(); 1834 QualType RPointee = RMemPtr->getPointeeType(); 1835 1836 QualifierCollector LPQuals, RPQuals; 1837 const Type *LPCan = LPQuals.strip(Context.getCanonicalType(LPointee)); 1838 const Type *RPCan = RPQuals.strip(Context.getCanonicalType(RPointee)); 1839 1840 // First, we check that the unqualified pointee type is the same. If it's 1841 // not, there's no conversion that will unify the two pointers. 1842 if (LPCan == RPCan) { 1843 1844 // Second, we take the greater of the two qualifications. If neither 1845 // is greater than the other, the conversion is not possible. 1846 1847 Qualifiers MergedQuals = LPQuals + RPQuals; 1848 1849 bool CompatibleQuals = true; 1850 if (MergedQuals.getCVRQualifiers() != LPQuals.getCVRQualifiers() && 1851 MergedQuals.getCVRQualifiers() != RPQuals.getCVRQualifiers()) 1852 CompatibleQuals = false; 1853 else if (LPQuals.getAddressSpace() != RPQuals.getAddressSpace()) 1854 // FIXME: 1855 // C99 6.5.15 as modified by TR 18037: 1856 // If the second and third operands are pointers into different 1857 // address spaces, the address spaces must overlap. 1858 CompatibleQuals = false; 1859 // FIXME: GC qualifiers? 1860 1861 if (CompatibleQuals) { 1862 // Third, we check if either of the container classes is derived from 1863 // the other. 1864 QualType LContainer(LMemPtr->getClass(), 0); 1865 QualType RContainer(RMemPtr->getClass(), 0); 1866 QualType MoreDerived; 1867 if (Context.getCanonicalType(LContainer) == 1868 Context.getCanonicalType(RContainer)) 1869 MoreDerived = LContainer; 1870 else if (IsDerivedFrom(LContainer, RContainer)) 1871 MoreDerived = LContainer; 1872 else if (IsDerivedFrom(RContainer, LContainer)) 1873 MoreDerived = RContainer; 1874 1875 if (!MoreDerived.isNull()) { 1876 // The type 'Q Pointee (MoreDerived::*)' is the common type. 1877 // We don't use ImpCastExprToType here because this could still fail 1878 // for ambiguous or inaccessible conversions. 1879 LPointee = Context.getQualifiedType(LPointee, MergedQuals); 1880 QualType Common 1881 = Context.getMemberPointerType(LPointee, MoreDerived.getTypePtr()); 1882 if (PerformImplicitConversion(LHS, Common, Sema::AA_Converting)) 1883 return QualType(); 1884 if (PerformImplicitConversion(RHS, Common, Sema::AA_Converting)) 1885 return QualType(); 1886 return Common; 1887 } 1888 } 1889 } 1890 } 1891 1892 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 1893 << LHS->getType() << RHS->getType() 1894 << LHS->getSourceRange() << RHS->getSourceRange(); 1895 return QualType(); 1896} 1897 1898/// \brief Find a merged pointer type and convert the two expressions to it. 1899/// 1900/// This finds the composite pointer type (or member pointer type) for @p E1 1901/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this 1902/// type and returns it. 1903/// It does not emit diagnostics. 1904QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) { 1905 assert(getLangOptions().CPlusPlus && "This function assumes C++"); 1906 QualType T1 = E1->getType(), T2 = E2->getType(); 1907 1908 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() && 1909 !T2->isAnyPointerType() && !T2->isMemberPointerType()) 1910 return QualType(); 1911 1912 // C++0x 5.9p2 1913 // Pointer conversions and qualification conversions are performed on 1914 // pointer operands to bring them to their composite pointer type. If 1915 // one operand is a null pointer constant, the composite pointer type is 1916 // the type of the other operand. 1917 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 1918 if (T2->isMemberPointerType()) 1919 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer); 1920 else 1921 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer); 1922 return T2; 1923 } 1924 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 1925 if (T1->isMemberPointerType()) 1926 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer); 1927 else 1928 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer); 1929 return T1; 1930 } 1931 1932 // Now both have to be pointers or member pointers. 1933 if ((!T1->isPointerType() && !T1->isMemberPointerType()) || 1934 (!T2->isPointerType() && !T2->isMemberPointerType())) 1935 return QualType(); 1936 1937 // Otherwise, of one of the operands has type "pointer to cv1 void," then 1938 // the other has type "pointer to cv2 T" and the composite pointer type is 1939 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2. 1940 // Otherwise, the composite pointer type is a pointer type similar to the 1941 // type of one of the operands, with a cv-qualification signature that is 1942 // the union of the cv-qualification signatures of the operand types. 1943 // In practice, the first part here is redundant; it's subsumed by the second. 1944 // What we do here is, we build the two possible composite types, and try the 1945 // conversions in both directions. If only one works, or if the two composite 1946 // types are the same, we have succeeded. 1947 // FIXME: extended qualifiers? 1948 typedef llvm::SmallVector<unsigned, 4> QualifierVector; 1949 QualifierVector QualifierUnion; 1950 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4> 1951 ContainingClassVector; 1952 ContainingClassVector MemberOfClass; 1953 QualType Composite1 = Context.getCanonicalType(T1), 1954 Composite2 = Context.getCanonicalType(T2); 1955 do { 1956 const PointerType *Ptr1, *Ptr2; 1957 if ((Ptr1 = Composite1->getAs<PointerType>()) && 1958 (Ptr2 = Composite2->getAs<PointerType>())) { 1959 Composite1 = Ptr1->getPointeeType(); 1960 Composite2 = Ptr2->getPointeeType(); 1961 QualifierUnion.push_back( 1962 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); 1963 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0)); 1964 continue; 1965 } 1966 1967 const MemberPointerType *MemPtr1, *MemPtr2; 1968 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) && 1969 (MemPtr2 = Composite2->getAs<MemberPointerType>())) { 1970 Composite1 = MemPtr1->getPointeeType(); 1971 Composite2 = MemPtr2->getPointeeType(); 1972 QualifierUnion.push_back( 1973 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); 1974 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(), 1975 MemPtr2->getClass())); 1976 continue; 1977 } 1978 1979 // FIXME: block pointer types? 1980 1981 // Cannot unwrap any more types. 1982 break; 1983 } while (true); 1984 1985 // Rewrap the composites as pointers or member pointers with the union CVRs. 1986 ContainingClassVector::reverse_iterator MOC 1987 = MemberOfClass.rbegin(); 1988 for (QualifierVector::reverse_iterator 1989 I = QualifierUnion.rbegin(), 1990 E = QualifierUnion.rend(); 1991 I != E; (void)++I, ++MOC) { 1992 Qualifiers Quals = Qualifiers::fromCVRMask(*I); 1993 if (MOC->first && MOC->second) { 1994 // Rebuild member pointer type 1995 Composite1 = Context.getMemberPointerType( 1996 Context.getQualifiedType(Composite1, Quals), 1997 MOC->first); 1998 Composite2 = Context.getMemberPointerType( 1999 Context.getQualifiedType(Composite2, Quals), 2000 MOC->second); 2001 } else { 2002 // Rebuild pointer type 2003 Composite1 2004 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals)); 2005 Composite2 2006 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals)); 2007 } 2008 } 2009 2010 ImplicitConversionSequence E1ToC1 = 2011 TryImplicitConversion(E1, Composite1, 2012 /*SuppressUserConversions=*/false, 2013 /*AllowExplicit=*/false, 2014 /*ForceRValue=*/false, 2015 /*InOverloadResolution=*/false); 2016 ImplicitConversionSequence E2ToC1 = 2017 TryImplicitConversion(E2, Composite1, 2018 /*SuppressUserConversions=*/false, 2019 /*AllowExplicit=*/false, 2020 /*ForceRValue=*/false, 2021 /*InOverloadResolution=*/false); 2022 2023 ImplicitConversionSequence E1ToC2, E2ToC2; 2024 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion; 2025 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion; 2026 if (Context.getCanonicalType(Composite1) != 2027 Context.getCanonicalType(Composite2)) { 2028 E1ToC2 = TryImplicitConversion(E1, Composite2, 2029 /*SuppressUserConversions=*/false, 2030 /*AllowExplicit=*/false, 2031 /*ForceRValue=*/false, 2032 /*InOverloadResolution=*/false); 2033 E2ToC2 = TryImplicitConversion(E2, Composite2, 2034 /*SuppressUserConversions=*/false, 2035 /*AllowExplicit=*/false, 2036 /*ForceRValue=*/false, 2037 /*InOverloadResolution=*/false); 2038 } 2039 2040 bool ToC1Viable = E1ToC1.ConversionKind != 2041 ImplicitConversionSequence::BadConversion 2042 && E2ToC1.ConversionKind != 2043 ImplicitConversionSequence::BadConversion; 2044 bool ToC2Viable = E1ToC2.ConversionKind != 2045 ImplicitConversionSequence::BadConversion 2046 && E2ToC2.ConversionKind != 2047 ImplicitConversionSequence::BadConversion; 2048 if (ToC1Viable && !ToC2Viable) { 2049 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, Sema::AA_Converting) && 2050 !PerformImplicitConversion(E2, Composite1, E2ToC1, Sema::AA_Converting)) 2051 return Composite1; 2052 } 2053 if (ToC2Viable && !ToC1Viable) { 2054 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, Sema::AA_Converting) && 2055 !PerformImplicitConversion(E2, Composite2, E2ToC2, Sema::AA_Converting)) 2056 return Composite2; 2057 } 2058 return QualType(); 2059} 2060 2061Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) { 2062 if (!Context.getLangOptions().CPlusPlus) 2063 return Owned(E); 2064 2065 const RecordType *RT = E->getType()->getAs<RecordType>(); 2066 if (!RT) 2067 return Owned(E); 2068 2069 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 2070 if (RD->hasTrivialDestructor()) 2071 return Owned(E); 2072 2073 if (CallExpr *CE = dyn_cast<CallExpr>(E)) { 2074 QualType Ty = CE->getCallee()->getType(); 2075 if (const PointerType *PT = Ty->getAs<PointerType>()) 2076 Ty = PT->getPointeeType(); 2077 2078 const FunctionType *FTy = Ty->getAs<FunctionType>(); 2079 if (FTy->getResultType()->isReferenceType()) 2080 return Owned(E); 2081 } 2082 CXXTemporary *Temp = CXXTemporary::Create(Context, 2083 RD->getDestructor(Context)); 2084 ExprTemporaries.push_back(Temp); 2085 if (CXXDestructorDecl *Destructor = 2086 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context))) 2087 MarkDeclarationReferenced(E->getExprLoc(), Destructor); 2088 // FIXME: Add the temporary to the temporaries vector. 2089 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E)); 2090} 2091 2092Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) { 2093 assert(SubExpr && "sub expression can't be null!"); 2094 2095 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries; 2096 assert(ExprTemporaries.size() >= FirstTemporary); 2097 if (ExprTemporaries.size() == FirstTemporary) 2098 return SubExpr; 2099 2100 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr, 2101 &ExprTemporaries[FirstTemporary], 2102 ExprTemporaries.size() - FirstTemporary); 2103 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary, 2104 ExprTemporaries.end()); 2105 2106 return E; 2107} 2108 2109FullExpr Sema::CreateFullExpr(Expr *SubExpr) { 2110 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries; 2111 assert(ExprTemporaries.size() >= FirstTemporary); 2112 2113 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary; 2114 CXXTemporary **Temporaries = 2115 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary]; 2116 2117 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries); 2118 2119 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary, 2120 ExprTemporaries.end()); 2121 2122 return E; 2123} 2124 2125Sema::OwningExprResult 2126Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc, 2127 tok::TokenKind OpKind, TypeTy *&ObjectType) { 2128 // Since this might be a postfix expression, get rid of ParenListExprs. 2129 Base = MaybeConvertParenListExprToParenExpr(S, move(Base)); 2130 2131 Expr *BaseExpr = (Expr*)Base.get(); 2132 assert(BaseExpr && "no record expansion"); 2133 2134 QualType BaseType = BaseExpr->getType(); 2135 if (BaseType->isDependentType()) { 2136 // If we have a pointer to a dependent type and are using the -> operator, 2137 // the object type is the type that the pointer points to. We might still 2138 // have enough information about that type to do something useful. 2139 if (OpKind == tok::arrow) 2140 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) 2141 BaseType = Ptr->getPointeeType(); 2142 2143 ObjectType = BaseType.getAsOpaquePtr(); 2144 return move(Base); 2145 } 2146 2147 // C++ [over.match.oper]p8: 2148 // [...] When operator->returns, the operator-> is applied to the value 2149 // returned, with the original second operand. 2150 if (OpKind == tok::arrow) { 2151 // The set of types we've considered so far. 2152 llvm::SmallPtrSet<CanQualType,8> CTypes; 2153 llvm::SmallVector<SourceLocation, 8> Locations; 2154 CTypes.insert(Context.getCanonicalType(BaseType)); 2155 2156 while (BaseType->isRecordType()) { 2157 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc); 2158 BaseExpr = (Expr*)Base.get(); 2159 if (BaseExpr == NULL) 2160 return ExprError(); 2161 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr)) 2162 Locations.push_back(OpCall->getDirectCallee()->getLocation()); 2163 BaseType = BaseExpr->getType(); 2164 CanQualType CBaseType = Context.getCanonicalType(BaseType); 2165 if (!CTypes.insert(CBaseType)) { 2166 Diag(OpLoc, diag::err_operator_arrow_circular); 2167 for (unsigned i = 0; i < Locations.size(); i++) 2168 Diag(Locations[i], diag::note_declared_at); 2169 return ExprError(); 2170 } 2171 } 2172 2173 if (BaseType->isPointerType()) 2174 BaseType = BaseType->getPointeeType(); 2175 } 2176 2177 // We could end up with various non-record types here, such as extended 2178 // vector types or Objective-C interfaces. Just return early and let 2179 // ActOnMemberReferenceExpr do the work. 2180 if (!BaseType->isRecordType()) { 2181 // C++ [basic.lookup.classref]p2: 2182 // [...] If the type of the object expression is of pointer to scalar 2183 // type, the unqualified-id is looked up in the context of the complete 2184 // postfix-expression. 2185 ObjectType = 0; 2186 return move(Base); 2187 } 2188 2189 // The object type must be complete (or dependent). 2190 if (!BaseType->isDependentType() && 2191 RequireCompleteType(OpLoc, BaseType, 2192 PDiag(diag::err_incomplete_member_access))) 2193 return ExprError(); 2194 2195 // C++ [basic.lookup.classref]p2: 2196 // If the id-expression in a class member access (5.2.5) is an 2197 // unqualified-id, and the type of the object expression is of a class 2198 // type C (or of pointer to a class type C), the unqualified-id is looked 2199 // up in the scope of class C. [...] 2200 ObjectType = BaseType.getAsOpaquePtr(); 2201 2202 return move(Base); 2203} 2204 2205CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp, 2206 CXXMethodDecl *Method) { 2207 if (PerformObjectArgumentInitialization(Exp, Method)) 2208 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?"); 2209 2210 MemberExpr *ME = 2211 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method, 2212 SourceLocation(), Method->getType()); 2213 QualType ResultType = Method->getResultType().getNonReferenceType(); 2214 MarkDeclarationReferenced(Exp->getLocStart(), Method); 2215 CXXMemberCallExpr *CE = 2216 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, 2217 Exp->getLocEnd()); 2218 return CE; 2219} 2220 2221Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc, 2222 QualType Ty, 2223 CastExpr::CastKind Kind, 2224 CXXMethodDecl *Method, 2225 ExprArg Arg) { 2226 Expr *From = Arg.takeAs<Expr>(); 2227 2228 switch (Kind) { 2229 default: assert(0 && "Unhandled cast kind!"); 2230 case CastExpr::CK_ConstructorConversion: { 2231 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this); 2232 2233 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method), 2234 MultiExprArg(*this, (void **)&From, 1), 2235 CastLoc, ConstructorArgs)) 2236 return ExprError(); 2237 2238 OwningExprResult Result = 2239 BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method), 2240 move_arg(ConstructorArgs)); 2241 if (Result.isInvalid()) 2242 return ExprError(); 2243 2244 return MaybeBindToTemporary(Result.takeAs<Expr>()); 2245 } 2246 2247 case CastExpr::CK_UserDefinedConversion: { 2248 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!"); 2249 2250 // Create an implicit call expr that calls it. 2251 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method); 2252 return MaybeBindToTemporary(CE); 2253 } 2254 } 2255} 2256 2257Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) { 2258 Expr *FullExpr = Arg.takeAs<Expr>(); 2259 if (FullExpr) 2260 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr); 2261 2262 return Owned(FullExpr); 2263} 2264 2265/// \brief Determine whether a reference to the given declaration in the 2266/// current context is an implicit member access 2267/// (C++ [class.mfct.non-static]p2). 2268/// 2269/// FIXME: Should Objective-C also use this approach? 2270/// 2271/// \param D the declaration being referenced from the current scope. 2272/// 2273/// \param NameLoc the location of the name in the source. 2274/// 2275/// \param ThisType if the reference to this declaration is an implicit member 2276/// access, will be set to the type of the "this" pointer to be used when 2277/// building that implicit member access. 2278/// 2279/// \returns true if this is an implicit member reference (in which case 2280/// \p ThisType and \p MemberType will be set), or false if it is not an 2281/// implicit member reference. 2282bool Sema::isImplicitMemberReference(const LookupResult &R, 2283 QualType &ThisType) { 2284 // If this isn't a C++ method, then it isn't an implicit member reference. 2285 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext); 2286 if (!MD || MD->isStatic()) 2287 return false; 2288 2289 // C++ [class.mfct.nonstatic]p2: 2290 // [...] if name lookup (3.4.1) resolves the name in the 2291 // id-expression to a nonstatic nontype member of class X or of 2292 // a base class of X, the id-expression is transformed into a 2293 // class member access expression (5.2.5) using (*this) (9.3.2) 2294 // as the postfix-expression to the left of the '.' operator. 2295 DeclContext *Ctx = 0; 2296 if (R.isUnresolvableResult()) { 2297 // FIXME: this is just picking one at random 2298 Ctx = R.getRepresentativeDecl()->getDeclContext(); 2299 } else if (FieldDecl *FD = R.getAsSingle<FieldDecl>()) { 2300 Ctx = FD->getDeclContext(); 2301 } else { 2302 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2303 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*I); 2304 FunctionTemplateDecl *FunTmpl = 0; 2305 if (!Method && (FunTmpl = dyn_cast<FunctionTemplateDecl>(*I))) 2306 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl()); 2307 2308 // FIXME: Do we have to know if there are explicit template arguments? 2309 if (Method && !Method->isStatic()) { 2310 Ctx = Method->getParent(); 2311 break; 2312 } 2313 } 2314 } 2315 2316 if (!Ctx || !Ctx->isRecord()) 2317 return false; 2318 2319 // Determine whether the declaration(s) we found are actually in a base 2320 // class. If not, this isn't an implicit member reference. 2321 ThisType = MD->getThisType(Context); 2322 2323 // FIXME: this doesn't really work for overloaded lookups. 2324 2325 QualType CtxType = Context.getTypeDeclType(cast<CXXRecordDecl>(Ctx)); 2326 QualType ClassType 2327 = Context.getTypeDeclType(cast<CXXRecordDecl>(MD->getParent())); 2328 return Context.hasSameType(CtxType, ClassType) || 2329 IsDerivedFrom(ClassType, CtxType); 2330} 2331 2332