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