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