SemaExprCXX.cpp revision 972041f45bdf8df7ea447221292d7827466ba94b
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 "SemaInherit.h" 15#include "Sema.h" 16#include "clang/AST/ExprCXX.h" 17#include "clang/AST/ASTContext.h" 18#include "clang/Parse/DeclSpec.h" 19#include "clang/Lex/Preprocessor.h" 20#include "clang/Basic/TargetInfo.h" 21#include "llvm/ADT/STLExtras.h" 22using namespace clang; 23 24/// ActOnCXXConversionFunctionExpr - Parse a C++ conversion function 25/// name (e.g., operator void const *) as an expression. This is 26/// very similar to ActOnIdentifierExpr, except that instead of 27/// providing an identifier the parser provides the type of the 28/// conversion function. 29Sema::OwningExprResult 30Sema::ActOnCXXConversionFunctionExpr(Scope *S, SourceLocation OperatorLoc, 31 TypeTy *Ty, bool HasTrailingLParen, 32 const CXXScopeSpec &SS, 33 bool isAddressOfOperand) { 34 QualType ConvType = QualType::getFromOpaquePtr(Ty); 35 QualType ConvTypeCanon = Context.getCanonicalType(ConvType); 36 DeclarationName ConvName 37 = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon); 38 return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen, 39 &SS, isAddressOfOperand); 40} 41 42/// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator 43/// name (e.g., @c operator+ ) as an expression. This is very 44/// similar to ActOnIdentifierExpr, except that instead of providing 45/// an identifier the parser provides the kind of overloaded 46/// operator that was parsed. 47Sema::OwningExprResult 48Sema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc, 49 OverloadedOperatorKind Op, 50 bool HasTrailingLParen, 51 const CXXScopeSpec &SS, 52 bool isAddressOfOperand) { 53 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op); 54 return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS, 55 isAddressOfOperand); 56} 57 58/// ActOnCXXTypeidOfType - Parse typeid( type-id ). 59Action::OwningExprResult 60Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, 61 bool isType, void *TyOrExpr, SourceLocation RParenLoc) { 62 NamespaceDecl *StdNs = GetStdNamespace(); 63 if (!StdNs) 64 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); 65 66 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info"); 67 Decl *TypeInfoDecl = LookupQualifiedName(StdNs, TypeInfoII, LookupTagName); 68 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl); 69 if (!TypeInfoRecordDecl) 70 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); 71 72 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl); 73 74 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr, 75 TypeInfoType.withConst(), 76 SourceRange(OpLoc, RParenLoc))); 77} 78 79/// ActOnCXXBoolLiteral - Parse {true,false} literals. 80Action::OwningExprResult 81Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 82 assert((Kind == tok::kw_true || Kind == tok::kw_false) && 83 "Unknown C++ Boolean value!"); 84 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true, 85 Context.BoolTy, OpLoc)); 86} 87 88/// ActOnCXXThrow - Parse throw expressions. 89Action::OwningExprResult 90Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) { 91 Expr *Ex = E.takeAs<Expr>(); 92 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex)) 93 return ExprError(); 94 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc)); 95} 96 97/// CheckCXXThrowOperand - Validate the operand of a throw. 98bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) { 99 // C++ [except.throw]p3: 100 // [...] adjusting the type from "array of T" or "function returning T" 101 // to "pointer to T" or "pointer to function returning T", [...] 102 DefaultFunctionArrayConversion(E); 103 104 // If the type of the exception would be an incomplete type or a pointer 105 // to an incomplete type other than (cv) void the program is ill-formed. 106 QualType Ty = E->getType(); 107 int isPointer = 0; 108 if (const PointerType* Ptr = Ty->getAsPointerType()) { 109 Ty = Ptr->getPointeeType(); 110 isPointer = 1; 111 } 112 if (!isPointer || !Ty->isVoidType()) { 113 if (RequireCompleteType(ThrowLoc, Ty, 114 isPointer ? diag::err_throw_incomplete_ptr 115 : diag::err_throw_incomplete, 116 E->getSourceRange(), SourceRange(), QualType())) 117 return true; 118 } 119 120 // FIXME: Construct a temporary here. 121 return false; 122} 123 124Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) { 125 /// C++ 9.3.2: In the body of a non-static member function, the keyword this 126 /// is a non-lvalue expression whose value is the address of the object for 127 /// which the function is called. 128 129 if (!isa<FunctionDecl>(CurContext)) 130 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use)); 131 132 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) 133 if (MD->isInstance()) 134 return Owned(new (Context) CXXThisExpr(ThisLoc, 135 MD->getThisType(Context))); 136 137 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use)); 138} 139 140/// ActOnCXXTypeConstructExpr - Parse construction of a specified type. 141/// Can be interpreted either as function-style casting ("int(x)") 142/// or class type construction ("ClassType(x,y,z)") 143/// or creation of a value-initialized type ("int()"). 144Action::OwningExprResult 145Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep, 146 SourceLocation LParenLoc, 147 MultiExprArg exprs, 148 SourceLocation *CommaLocs, 149 SourceLocation RParenLoc) { 150 assert(TypeRep && "Missing type!"); 151 QualType Ty = QualType::getFromOpaquePtr(TypeRep); 152 unsigned NumExprs = exprs.size(); 153 Expr **Exprs = (Expr**)exprs.get(); 154 SourceLocation TyBeginLoc = TypeRange.getBegin(); 155 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc); 156 157 if (Ty->isDependentType() || 158 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) { 159 exprs.release(); 160 161 // FIXME: Is this correct? 162 CXXTempVarDecl *Temp = CXXTempVarDecl::Create(Context, CurContext, Ty); 163 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Temp, 0, Ty, 164 TyBeginLoc, 165 Exprs, NumExprs, 166 RParenLoc)); 167 } 168 169 170 // C++ [expr.type.conv]p1: 171 // If the expression list is a single expression, the type conversion 172 // expression is equivalent (in definedness, and if defined in meaning) to the 173 // corresponding cast expression. 174 // 175 if (NumExprs == 1) { 176 if (CheckCastTypes(TypeRange, Ty, Exprs[0])) 177 return ExprError(); 178 exprs.release(); 179 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(), 180 Ty, TyBeginLoc, Exprs[0], 181 RParenLoc)); 182 } 183 184 if (const RecordType *RT = Ty->getAsRecordType()) { 185 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl()); 186 187 if (NumExprs > 1 || Record->hasUserDeclaredConstructor()) { 188 CXXConstructorDecl *Constructor 189 = PerformInitializationByConstructor(Ty, Exprs, NumExprs, 190 TypeRange.getBegin(), 191 SourceRange(TypeRange.getBegin(), 192 RParenLoc), 193 DeclarationName(), 194 IK_Direct); 195 196 if (!Constructor) 197 return ExprError(); 198 199 CXXTempVarDecl *Temp = CXXTempVarDecl::Create(Context, CurContext, Ty); 200 201 exprs.release(); 202 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Temp, 203 Constructor, Ty, 204 TyBeginLoc, Exprs, 205 NumExprs, RParenLoc)); 206 } 207 208 // Fall through to value-initialize an object of class type that 209 // doesn't have a user-declared default constructor. 210 } 211 212 // C++ [expr.type.conv]p1: 213 // If the expression list specifies more than a single value, the type shall 214 // be a class with a suitably declared constructor. 215 // 216 if (NumExprs > 1) 217 return ExprError(Diag(CommaLocs[0], 218 diag::err_builtin_func_cast_more_than_one_arg) 219 << FullRange); 220 221 assert(NumExprs == 0 && "Expected 0 expressions"); 222 223 // C++ [expr.type.conv]p2: 224 // The expression T(), where T is a simple-type-specifier for a non-array 225 // complete object type or the (possibly cv-qualified) void type, creates an 226 // rvalue of the specified type, which is value-initialized. 227 // 228 if (Ty->isArrayType()) 229 return ExprError(Diag(TyBeginLoc, 230 diag::err_value_init_for_array_type) << FullRange); 231 if (!Ty->isDependentType() && !Ty->isVoidType() && 232 RequireCompleteType(TyBeginLoc, Ty, 233 diag::err_invalid_incomplete_type_use, FullRange)) 234 return ExprError(); 235 236 if (RequireNonAbstractType(TyBeginLoc, Ty, 237 diag::err_allocation_of_abstract_type)) 238 return ExprError(); 239 240 exprs.release(); 241 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc)); 242} 243 244 245/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.: 246/// @code new (memory) int[size][4] @endcode 247/// or 248/// @code ::new Foo(23, "hello") @endcode 249/// For the interpretation of this heap of arguments, consult the base version. 250Action::OwningExprResult 251Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 252 SourceLocation PlacementLParen, MultiExprArg PlacementArgs, 253 SourceLocation PlacementRParen, bool ParenTypeId, 254 Declarator &D, SourceLocation ConstructorLParen, 255 MultiExprArg ConstructorArgs, 256 SourceLocation ConstructorRParen) 257{ 258 Expr *ArraySize = 0; 259 unsigned Skip = 0; 260 // If the specified type is an array, unwrap it and save the expression. 261 if (D.getNumTypeObjects() > 0 && 262 D.getTypeObject(0).Kind == DeclaratorChunk::Array) { 263 DeclaratorChunk &Chunk = D.getTypeObject(0); 264 if (Chunk.Arr.hasStatic) 265 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new) 266 << D.getSourceRange()); 267 if (!Chunk.Arr.NumElts) 268 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size) 269 << D.getSourceRange()); 270 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts); 271 Skip = 1; 272 } 273 274 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, Skip); 275 if (D.isInvalidType()) 276 return ExprError(); 277 278 if (CheckAllocatedType(AllocType, D)) 279 return ExprError(); 280 281 QualType ResultType = AllocType->isDependentType() 282 ? Context.DependentTy 283 : Context.getPointerType(AllocType); 284 285 // That every array dimension except the first is constant was already 286 // checked by the type check above. 287 288 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral 289 // or enumeration type with a non-negative value." 290 if (ArraySize && !ArraySize->isTypeDependent()) { 291 QualType SizeType = ArraySize->getType(); 292 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType()) 293 return ExprError(Diag(ArraySize->getSourceRange().getBegin(), 294 diag::err_array_size_not_integral) 295 << SizeType << ArraySize->getSourceRange()); 296 // Let's see if this is a constant < 0. If so, we reject it out of hand. 297 // We don't care about special rules, so we tell the machinery it's not 298 // evaluated - it gives us a result in more cases. 299 if (!ArraySize->isValueDependent()) { 300 llvm::APSInt Value; 301 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) { 302 if (Value < llvm::APSInt( 303 llvm::APInt::getNullValue(Value.getBitWidth()), false)) 304 return ExprError(Diag(ArraySize->getSourceRange().getBegin(), 305 diag::err_typecheck_negative_array_size) 306 << ArraySize->getSourceRange()); 307 } 308 } 309 } 310 311 FunctionDecl *OperatorNew = 0; 312 FunctionDecl *OperatorDelete = 0; 313 Expr **PlaceArgs = (Expr**)PlacementArgs.get(); 314 unsigned NumPlaceArgs = PlacementArgs.size(); 315 if (!AllocType->isDependentType() && 316 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) && 317 FindAllocationFunctions(StartLoc, 318 SourceRange(PlacementLParen, PlacementRParen), 319 UseGlobal, AllocType, ArraySize, PlaceArgs, 320 NumPlaceArgs, OperatorNew, OperatorDelete)) 321 return ExprError(); 322 323 bool Init = ConstructorLParen.isValid(); 324 // --- Choosing a constructor --- 325 // C++ 5.3.4p15 326 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid) 327 // the object is not initialized. If the object, or any part of it, is 328 // const-qualified, it's an error. 329 // 2) If T is a POD and there's an empty initializer, the object is value- 330 // initialized. 331 // 3) If T is a POD and there's one initializer argument, the object is copy- 332 // constructed. 333 // 4) If T is a POD and there's more initializer arguments, it's an error. 334 // 5) If T is not a POD, the initializer arguments are used as constructor 335 // arguments. 336 // 337 // Or by the C++0x formulation: 338 // 1) If there's no initializer, the object is default-initialized according 339 // to C++0x rules. 340 // 2) Otherwise, the object is direct-initialized. 341 CXXConstructorDecl *Constructor = 0; 342 Expr **ConsArgs = (Expr**)ConstructorArgs.get(); 343 unsigned NumConsArgs = ConstructorArgs.size(); 344 if (AllocType->isDependentType()) { 345 // Skip all the checks. 346 } 347 // FIXME: Should check for primitive/aggregate here, not record. 348 else if (const RecordType *RT = AllocType->getAsRecordType()) { 349 // FIXME: This is incorrect for when there is an empty initializer and 350 // no user-defined constructor. Must zero-initialize, not default-construct. 351 Constructor = PerformInitializationByConstructor( 352 AllocType, ConsArgs, NumConsArgs, 353 D.getSourceRange().getBegin(), 354 SourceRange(D.getSourceRange().getBegin(), 355 ConstructorRParen), 356 RT->getDecl()->getDeclName(), 357 NumConsArgs != 0 ? IK_Direct : IK_Default); 358 if (!Constructor) 359 return ExprError(); 360 } else { 361 if (!Init) { 362 // FIXME: Check that no subpart is const. 363 if (AllocType.isConstQualified()) 364 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const) 365 << D.getSourceRange()); 366 } else if (NumConsArgs == 0) { 367 // Object is value-initialized. Do nothing. 368 } else if (NumConsArgs == 1) { 369 // Object is direct-initialized. 370 // FIXME: WHAT DeclarationName do we pass in here? 371 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc, 372 DeclarationName() /*AllocType.getAsString()*/, 373 /*DirectInit=*/true)) 374 return ExprError(); 375 } else { 376 return ExprError(Diag(StartLoc, 377 diag::err_builtin_direct_init_more_than_one_arg) 378 << SourceRange(ConstructorLParen, ConstructorRParen)); 379 } 380 } 381 382 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16) 383 384 PlacementArgs.release(); 385 ConstructorArgs.release(); 386 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs, 387 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init, 388 ConsArgs, NumConsArgs, OperatorDelete, ResultType, 389 StartLoc, Init ? ConstructorRParen : SourceLocation())); 390} 391 392/// CheckAllocatedType - Checks that a type is suitable as the allocated type 393/// in a new-expression. 394/// dimension off and stores the size expression in ArraySize. 395bool Sema::CheckAllocatedType(QualType AllocType, const Declarator &D) 396{ 397 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an 398 // abstract class type or array thereof. 399 if (AllocType->isFunctionType()) 400 return Diag(D.getSourceRange().getBegin(), diag::err_bad_new_type) 401 << AllocType << 0 << D.getSourceRange(); 402 else if (AllocType->isReferenceType()) 403 return Diag(D.getSourceRange().getBegin(), diag::err_bad_new_type) 404 << AllocType << 1 << D.getSourceRange(); 405 else if (!AllocType->isDependentType() && 406 RequireCompleteType(D.getSourceRange().getBegin(), AllocType, 407 diag::err_new_incomplete_type, 408 D.getSourceRange())) 409 return true; 410 else if (RequireNonAbstractType(D.getSourceRange().getBegin(), AllocType, 411 diag::err_allocation_of_abstract_type)) 412 return true; 413 414 // Every dimension shall be of constant size. 415 unsigned i = 1; 416 while (const ArrayType *Array = Context.getAsArrayType(AllocType)) { 417 if (!Array->isConstantArrayType()) { 418 Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst) 419 << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange(); 420 return true; 421 } 422 AllocType = Array->getElementType(); 423 ++i; 424 } 425 426 return false; 427} 428 429/// FindAllocationFunctions - Finds the overloads of operator new and delete 430/// that are appropriate for the allocation. 431bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 432 bool UseGlobal, QualType AllocType, 433 bool IsArray, Expr **PlaceArgs, 434 unsigned NumPlaceArgs, 435 FunctionDecl *&OperatorNew, 436 FunctionDecl *&OperatorDelete) 437{ 438 // --- Choosing an allocation function --- 439 // C++ 5.3.4p8 - 14 & 18 440 // 1) If UseGlobal is true, only look in the global scope. Else, also look 441 // in the scope of the allocated class. 442 // 2) If an array size is given, look for operator new[], else look for 443 // operator new. 444 // 3) The first argument is always size_t. Append the arguments from the 445 // placement form. 446 // FIXME: Also find the appropriate delete operator. 447 448 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs); 449 // We don't care about the actual value of this argument. 450 // FIXME: Should the Sema create the expression and embed it in the syntax 451 // tree? Or should the consumer just recalculate the value? 452 AllocArgs[0] = new (Context) IntegerLiteral(llvm::APInt::getNullValue( 453 Context.Target.getPointerWidth(0)), 454 Context.getSizeType(), 455 SourceLocation()); 456 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1); 457 458 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName( 459 IsArray ? OO_Array_New : OO_New); 460 if (AllocType->isRecordType() && !UseGlobal) { 461 CXXRecordDecl *Record 462 = cast<CXXRecordDecl>(AllocType->getAsRecordType()->getDecl()); 463 // FIXME: We fail to find inherited overloads. 464 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0], 465 AllocArgs.size(), Record, /*AllowMissing=*/true, 466 OperatorNew)) 467 return true; 468 } 469 if (!OperatorNew) { 470 // Didn't find a member overload. Look for a global one. 471 DeclareGlobalNewDelete(); 472 DeclContext *TUDecl = Context.getTranslationUnitDecl(); 473 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0], 474 AllocArgs.size(), TUDecl, /*AllowMissing=*/false, 475 OperatorNew)) 476 return true; 477 } 478 479 // FIXME: This is leaked on error. But so much is currently in Sema that it's 480 // easier to clean it in one go. 481 AllocArgs[0]->Destroy(Context); 482 return false; 483} 484 485/// FindAllocationOverload - Find an fitting overload for the allocation 486/// function in the specified scope. 487bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range, 488 DeclarationName Name, Expr** Args, 489 unsigned NumArgs, DeclContext *Ctx, 490 bool AllowMissing, FunctionDecl *&Operator) 491{ 492 DeclContext::lookup_iterator Alloc, AllocEnd; 493 llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Context, Name); 494 if (Alloc == AllocEnd) { 495 if (AllowMissing) 496 return false; 497 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) 498 << Name << Range; 499 } 500 501 OverloadCandidateSet Candidates; 502 for (; Alloc != AllocEnd; ++Alloc) { 503 // Even member operator new/delete are implicitly treated as 504 // static, so don't use AddMemberCandidate. 505 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc)) 506 AddOverloadCandidate(Fn, Args, NumArgs, Candidates, 507 /*SuppressUserConversions=*/false); 508 } 509 510 // Do the resolution. 511 OverloadCandidateSet::iterator Best; 512 switch(BestViableFunction(Candidates, Best)) { 513 case OR_Success: { 514 // Got one! 515 FunctionDecl *FnDecl = Best->Function; 516 // The first argument is size_t, and the first parameter must be size_t, 517 // too. This is checked on declaration and can be assumed. (It can't be 518 // asserted on, though, since invalid decls are left in there.) 519 for (unsigned i = 1; i < NumArgs; ++i) { 520 // FIXME: Passing word to diagnostic. 521 if (PerformCopyInitialization(Args[i-1], 522 FnDecl->getParamDecl(i)->getType(), 523 "passing")) 524 return true; 525 } 526 Operator = FnDecl; 527 return false; 528 } 529 530 case OR_No_Viable_Function: 531 if (AllowMissing) 532 return false; 533 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) 534 << Name << Range; 535 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false); 536 return true; 537 538 case OR_Ambiguous: 539 Diag(StartLoc, diag::err_ovl_ambiguous_call) 540 << Name << Range; 541 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true); 542 return true; 543 544 case OR_Deleted: 545 Diag(StartLoc, diag::err_ovl_deleted_call) 546 << Best->Function->isDeleted() 547 << Name << Range; 548 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true); 549 return true; 550 } 551 assert(false && "Unreachable, bad result from BestViableFunction"); 552 return true; 553} 554 555 556/// DeclareGlobalNewDelete - Declare the global forms of operator new and 557/// delete. These are: 558/// @code 559/// void* operator new(std::size_t) throw(std::bad_alloc); 560/// void* operator new[](std::size_t) throw(std::bad_alloc); 561/// void operator delete(void *) throw(); 562/// void operator delete[](void *) throw(); 563/// @endcode 564/// Note that the placement and nothrow forms of new are *not* implicitly 565/// declared. Their use requires including \<new\>. 566void Sema::DeclareGlobalNewDelete() 567{ 568 if (GlobalNewDeleteDeclared) 569 return; 570 GlobalNewDeleteDeclared = true; 571 572 QualType VoidPtr = Context.getPointerType(Context.VoidTy); 573 QualType SizeT = Context.getSizeType(); 574 575 // FIXME: Exception specifications are not added. 576 DeclareGlobalAllocationFunction( 577 Context.DeclarationNames.getCXXOperatorName(OO_New), 578 VoidPtr, SizeT); 579 DeclareGlobalAllocationFunction( 580 Context.DeclarationNames.getCXXOperatorName(OO_Array_New), 581 VoidPtr, SizeT); 582 DeclareGlobalAllocationFunction( 583 Context.DeclarationNames.getCXXOperatorName(OO_Delete), 584 Context.VoidTy, VoidPtr); 585 DeclareGlobalAllocationFunction( 586 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete), 587 Context.VoidTy, VoidPtr); 588} 589 590/// DeclareGlobalAllocationFunction - Declares a single implicit global 591/// allocation function if it doesn't already exist. 592void Sema::DeclareGlobalAllocationFunction(DeclarationName Name, 593 QualType Return, QualType Argument) 594{ 595 DeclContext *GlobalCtx = Context.getTranslationUnitDecl(); 596 597 // Check if this function is already declared. 598 { 599 DeclContext::lookup_iterator Alloc, AllocEnd; 600 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Context, Name); 601 Alloc != AllocEnd; ++Alloc) { 602 // FIXME: Do we need to check for default arguments here? 603 FunctionDecl *Func = cast<FunctionDecl>(*Alloc); 604 if (Func->getNumParams() == 1 && 605 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument) 606 return; 607 } 608 } 609 610 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0); 611 FunctionDecl *Alloc = 612 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name, 613 FnType, FunctionDecl::None, false, true, 614 SourceLocation()); 615 Alloc->setImplicit(); 616 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(), 617 0, Argument, VarDecl::None, 0); 618 Alloc->setParams(Context, &Param, 1); 619 620 // FIXME: Also add this declaration to the IdentifierResolver, but 621 // make sure it is at the end of the chain to coincide with the 622 // global scope. 623 ((DeclContext *)TUScope->getEntity())->addDecl(Context, Alloc); 624} 625 626/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in: 627/// @code ::delete ptr; @endcode 628/// or 629/// @code delete [] ptr; @endcode 630Action::OwningExprResult 631Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, 632 bool ArrayForm, ExprArg Operand) 633{ 634 // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type 635 // having a single conversion function to a pointer type. The result has 636 // type void." 637 // DR599 amends "pointer type" to "pointer to object type" in both cases. 638 639 Expr *Ex = (Expr *)Operand.get(); 640 if (!Ex->isTypeDependent()) { 641 QualType Type = Ex->getType(); 642 643 if (Type->isRecordType()) { 644 // FIXME: Find that one conversion function and amend the type. 645 } 646 647 if (!Type->isPointerType()) 648 return ExprError(Diag(StartLoc, diag::err_delete_operand) 649 << Type << Ex->getSourceRange()); 650 651 QualType Pointee = Type->getAsPointerType()->getPointeeType(); 652 if (Pointee->isFunctionType() || Pointee->isVoidType()) 653 return ExprError(Diag(StartLoc, diag::err_delete_operand) 654 << Type << Ex->getSourceRange()); 655 else if (!Pointee->isDependentType() && 656 RequireCompleteType(StartLoc, Pointee, 657 diag::warn_delete_incomplete, 658 Ex->getSourceRange())) 659 return ExprError(); 660 661 // FIXME: Look up the correct operator delete overload and pass a pointer 662 // along. 663 // FIXME: Check access and ambiguity of operator delete and destructor. 664 } 665 666 Operand.release(); 667 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm, 668 0, Ex, StartLoc)); 669} 670 671 672/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 673/// C++ if/switch/while/for statement. 674/// e.g: "if (int x = f()) {...}" 675Action::OwningExprResult 676Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc, 677 Declarator &D, 678 SourceLocation EqualLoc, 679 ExprArg AssignExprVal) { 680 assert(AssignExprVal.get() && "Null assignment expression"); 681 682 // C++ 6.4p2: 683 // The declarator shall not specify a function or an array. 684 // The type-specifier-seq shall not contain typedef and shall not declare a 685 // new class or enumeration. 686 687 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 688 "Parser allowed 'typedef' as storage class of condition decl."); 689 690 QualType Ty = GetTypeForDeclarator(D, S); 691 692 if (Ty->isFunctionType()) { // The declarator shall not specify a function... 693 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl 694 // would be created and CXXConditionDeclExpr wants a VarDecl. 695 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type) 696 << SourceRange(StartLoc, EqualLoc)); 697 } else if (Ty->isArrayType()) { // ...or an array. 698 Diag(StartLoc, diag::err_invalid_use_of_array_type) 699 << SourceRange(StartLoc, EqualLoc); 700 } else if (const RecordType *RT = Ty->getAsRecordType()) { 701 RecordDecl *RD = RT->getDecl(); 702 // The type-specifier-seq shall not declare a new class... 703 if (RD->isDefinition() && 704 (RD->getIdentifier() == 0 || S->isDeclScope(DeclPtrTy::make(RD)))) 705 Diag(RD->getLocation(), diag::err_type_defined_in_condition); 706 } else if (const EnumType *ET = Ty->getAsEnumType()) { 707 EnumDecl *ED = ET->getDecl(); 708 // ...or enumeration. 709 if (ED->isDefinition() && 710 (ED->getIdentifier() == 0 || S->isDeclScope(DeclPtrTy::make(ED)))) 711 Diag(ED->getLocation(), diag::err_type_defined_in_condition); 712 } 713 714 DeclPtrTy Dcl = ActOnDeclarator(S, D, DeclPtrTy()); 715 if (!Dcl) 716 return ExprError(); 717 AddInitializerToDecl(Dcl, move(AssignExprVal)); 718 719 // Mark this variable as one that is declared within a conditional. 720 // We know that the decl had to be a VarDecl because that is the only type of 721 // decl that can be assigned and the grammar requires an '='. 722 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>()); 723 VD->setDeclaredInCondition(true); 724 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD)); 725} 726 727/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid. 728bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) { 729 // C++ 6.4p4: 730 // The value of a condition that is an initialized declaration in a statement 731 // other than a switch statement is the value of the declared variable 732 // implicitly converted to type bool. If that conversion is ill-formed, the 733 // program is ill-formed. 734 // The value of a condition that is an expression is the value of the 735 // expression, implicitly converted to bool. 736 // 737 return PerformContextuallyConvertToBool(CondExpr); 738} 739 740/// Helper function to determine whether this is the (deprecated) C++ 741/// conversion from a string literal to a pointer to non-const char or 742/// non-const wchar_t (for narrow and wide string literals, 743/// respectively). 744bool 745Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) { 746 // Look inside the implicit cast, if it exists. 747 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From)) 748 From = Cast->getSubExpr(); 749 750 // A string literal (2.13.4) that is not a wide string literal can 751 // be converted to an rvalue of type "pointer to char"; a wide 752 // string literal can be converted to an rvalue of type "pointer 753 // to wchar_t" (C++ 4.2p2). 754 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From)) 755 if (const PointerType *ToPtrType = ToType->getAsPointerType()) 756 if (const BuiltinType *ToPointeeType 757 = ToPtrType->getPointeeType()->getAsBuiltinType()) { 758 // This conversion is considered only when there is an 759 // explicit appropriate pointer target type (C++ 4.2p2). 760 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 && 761 ((StrLit->isWide() && ToPointeeType->isWideCharType()) || 762 (!StrLit->isWide() && 763 (ToPointeeType->getKind() == BuiltinType::Char_U || 764 ToPointeeType->getKind() == BuiltinType::Char_S)))) 765 return true; 766 } 767 768 return false; 769} 770 771/// PerformImplicitConversion - Perform an implicit conversion of the 772/// expression From to the type ToType. Returns true if there was an 773/// error, false otherwise. The expression From is replaced with the 774/// converted expression. Flavor is the kind of conversion we're 775/// performing, used in the error message. If @p AllowExplicit, 776/// explicit user-defined conversions are permitted. @p Elidable should be true 777/// when called for copies which may be elided (C++ 12.8p15). C++0x overload 778/// resolution works differently in that case. 779bool 780Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 781 const char *Flavor, bool AllowExplicit, 782 bool Elidable) 783{ 784 ImplicitConversionSequence ICS; 785 ICS.ConversionKind = ImplicitConversionSequence::BadConversion; 786 if (Elidable && getLangOptions().CPlusPlus0x) { 787 ICS = TryImplicitConversion(From, ToType, /*SuppressUserConversions*/false, 788 AllowExplicit, /*ForceRValue*/true); 789 } 790 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) { 791 ICS = TryImplicitConversion(From, ToType, false, AllowExplicit); 792 } 793 return PerformImplicitConversion(From, ToType, ICS, Flavor); 794} 795 796/// PerformImplicitConversion - Perform an implicit conversion of the 797/// expression From to the type ToType using the pre-computed implicit 798/// conversion sequence ICS. Returns true if there was an error, false 799/// otherwise. The expression From is replaced with the converted 800/// expression. Flavor is the kind of conversion we're performing, 801/// used in the error message. 802bool 803Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 804 const ImplicitConversionSequence &ICS, 805 const char* Flavor) { 806 switch (ICS.ConversionKind) { 807 case ImplicitConversionSequence::StandardConversion: 808 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor)) 809 return true; 810 break; 811 812 case ImplicitConversionSequence::UserDefinedConversion: 813 // FIXME: This is, of course, wrong. We'll need to actually call 814 // the constructor or conversion operator, and then cope with the 815 // standard conversions. 816 ImpCastExprToType(From, ToType.getNonReferenceType(), 817 ToType->isLValueReferenceType()); 818 return false; 819 820 case ImplicitConversionSequence::EllipsisConversion: 821 assert(false && "Cannot perform an ellipsis conversion"); 822 return false; 823 824 case ImplicitConversionSequence::BadConversion: 825 return true; 826 } 827 828 // Everything went well. 829 return false; 830} 831 832/// PerformImplicitConversion - Perform an implicit conversion of the 833/// expression From to the type ToType by following the standard 834/// conversion sequence SCS. Returns true if there was an error, false 835/// otherwise. The expression From is replaced with the converted 836/// expression. Flavor is the context in which we're performing this 837/// conversion, for use in error messages. 838bool 839Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 840 const StandardConversionSequence& SCS, 841 const char *Flavor) { 842 // Overall FIXME: we are recomputing too many types here and doing 843 // far too much extra work. What this means is that we need to keep 844 // track of more information that is computed when we try the 845 // implicit conversion initially, so that we don't need to recompute 846 // anything here. 847 QualType FromType = From->getType(); 848 849 if (SCS.CopyConstructor) { 850 // FIXME: Create a temporary object by calling the copy 851 // constructor. 852 ImpCastExprToType(From, ToType.getNonReferenceType(), 853 ToType->isLValueReferenceType()); 854 return false; 855 } 856 857 // Perform the first implicit conversion. 858 switch (SCS.First) { 859 case ICK_Identity: 860 case ICK_Lvalue_To_Rvalue: 861 // Nothing to do. 862 break; 863 864 case ICK_Array_To_Pointer: 865 FromType = Context.getArrayDecayedType(FromType); 866 ImpCastExprToType(From, FromType); 867 break; 868 869 case ICK_Function_To_Pointer: 870 if (Context.getCanonicalType(FromType) == Context.OverloadTy) { 871 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true); 872 if (!Fn) 873 return true; 874 875 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin())) 876 return true; 877 878 FixOverloadedFunctionReference(From, Fn); 879 FromType = From->getType(); 880 } 881 FromType = Context.getPointerType(FromType); 882 ImpCastExprToType(From, FromType); 883 break; 884 885 default: 886 assert(false && "Improper first standard conversion"); 887 break; 888 } 889 890 // Perform the second implicit conversion 891 switch (SCS.Second) { 892 case ICK_Identity: 893 // Nothing to do. 894 break; 895 896 case ICK_Integral_Promotion: 897 case ICK_Floating_Promotion: 898 case ICK_Complex_Promotion: 899 case ICK_Integral_Conversion: 900 case ICK_Floating_Conversion: 901 case ICK_Complex_Conversion: 902 case ICK_Floating_Integral: 903 case ICK_Complex_Real: 904 case ICK_Compatible_Conversion: 905 // FIXME: Go deeper to get the unqualified type! 906 FromType = ToType.getUnqualifiedType(); 907 ImpCastExprToType(From, FromType); 908 break; 909 910 case ICK_Pointer_Conversion: 911 if (SCS.IncompatibleObjC) { 912 // Diagnose incompatible Objective-C conversions 913 Diag(From->getSourceRange().getBegin(), 914 diag::ext_typecheck_convert_incompatible_pointer) 915 << From->getType() << ToType << Flavor 916 << From->getSourceRange(); 917 } 918 919 if (CheckPointerConversion(From, ToType)) 920 return true; 921 ImpCastExprToType(From, ToType); 922 break; 923 924 case ICK_Pointer_Member: 925 if (CheckMemberPointerConversion(From, ToType)) 926 return true; 927 ImpCastExprToType(From, ToType); 928 break; 929 930 case ICK_Boolean_Conversion: 931 FromType = Context.BoolTy; 932 ImpCastExprToType(From, FromType); 933 break; 934 935 default: 936 assert(false && "Improper second standard conversion"); 937 break; 938 } 939 940 switch (SCS.Third) { 941 case ICK_Identity: 942 // Nothing to do. 943 break; 944 945 case ICK_Qualification: 946 // FIXME: Not sure about lvalue vs rvalue here in the presence of 947 // rvalue references. 948 ImpCastExprToType(From, ToType.getNonReferenceType(), 949 ToType->isLValueReferenceType()); 950 break; 951 952 default: 953 assert(false && "Improper second standard conversion"); 954 break; 955 } 956 957 return false; 958} 959 960Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT, 961 SourceLocation KWLoc, 962 SourceLocation LParen, 963 TypeTy *Ty, 964 SourceLocation RParen) { 965 // FIXME: Some of the type traits have requirements. Interestingly, only the 966 // __is_base_of requirement is explicitly stated to be diagnosed. Indeed, 967 // G++ accepts __is_pod(Incomplete) without complaints, and claims that the 968 // type is indeed a POD. 969 970 // There is no point in eagerly computing the value. The traits are designed 971 // to be used from type trait templates, so Ty will be a template parameter 972 // 99% of the time. 973 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, 974 QualType::getFromOpaquePtr(Ty), 975 RParen, Context.BoolTy)); 976} 977 978QualType Sema::CheckPointerToMemberOperands( 979 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) 980{ 981 const char *OpSpelling = isIndirect ? "->*" : ".*"; 982 // C++ 5.5p2 983 // The binary operator .* [p3: ->*] binds its second operand, which shall 984 // be of type "pointer to member of T" (where T is a completely-defined 985 // class type) [...] 986 QualType RType = rex->getType(); 987 const MemberPointerType *MemPtr = RType->getAsMemberPointerType(); 988 if (!MemPtr) { 989 Diag(Loc, diag::err_bad_memptr_rhs) 990 << OpSpelling << RType << rex->getSourceRange(); 991 return QualType(); 992 } else if (RequireCompleteType(Loc, QualType(MemPtr->getClass(), 0), 993 diag::err_memptr_rhs_incomplete, 994 rex->getSourceRange())) 995 return QualType(); 996 997 QualType Class(MemPtr->getClass(), 0); 998 999 // C++ 5.5p2 1000 // [...] to its first operand, which shall be of class T or of a class of 1001 // which T is an unambiguous and accessible base class. [p3: a pointer to 1002 // such a class] 1003 QualType LType = lex->getType(); 1004 if (isIndirect) { 1005 if (const PointerType *Ptr = LType->getAsPointerType()) 1006 LType = Ptr->getPointeeType().getNonReferenceType(); 1007 else { 1008 Diag(Loc, diag::err_bad_memptr_lhs) 1009 << OpSpelling << 1 << LType << lex->getSourceRange(); 1010 return QualType(); 1011 } 1012 } 1013 1014 if (Context.getCanonicalType(Class).getUnqualifiedType() != 1015 Context.getCanonicalType(LType).getUnqualifiedType()) { 1016 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 1017 /*DetectVirtual=*/false); 1018 // FIXME: Would it be useful to print full ambiguity paths, 1019 // or is that overkill? 1020 if (!IsDerivedFrom(LType, Class, Paths) || 1021 Paths.isAmbiguous(Context.getCanonicalType(Class))) { 1022 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling 1023 << (int)isIndirect << lex->getType() << lex->getSourceRange(); 1024 return QualType(); 1025 } 1026 } 1027 1028 // C++ 5.5p2 1029 // The result is an object or a function of the type specified by the 1030 // second operand. 1031 // The cv qualifiers are the union of those in the pointer and the left side, 1032 // in accordance with 5.5p5 and 5.2.5. 1033 // FIXME: This returns a dereferenced member function pointer as a normal 1034 // function type. However, the only operation valid on such functions is 1035 // calling them. There's also a GCC extension to get a function pointer to 1036 // the thing, which is another complication, because this type - unlike the 1037 // type that is the result of this expression - takes the class as the first 1038 // argument. 1039 // We probably need a "MemberFunctionClosureType" or something like that. 1040 QualType Result = MemPtr->getPointeeType(); 1041 if (LType.isConstQualified()) 1042 Result.addConst(); 1043 if (LType.isVolatileQualified()) 1044 Result.addVolatile(); 1045 return Result; 1046} 1047 1048/// \brief Get the target type of a standard or user-defined conversion. 1049static QualType TargetType(const ImplicitConversionSequence &ICS) { 1050 assert((ICS.ConversionKind == 1051 ImplicitConversionSequence::StandardConversion || 1052 ICS.ConversionKind == 1053 ImplicitConversionSequence::UserDefinedConversion) && 1054 "function only valid for standard or user-defined conversions"); 1055 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion) 1056 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr); 1057 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr); 1058} 1059 1060/// \brief Try to convert a type to another according to C++0x 5.16p3. 1061/// 1062/// This is part of the parameter validation for the ? operator. If either 1063/// value operand is a class type, the two operands are attempted to be 1064/// converted to each other. This function does the conversion in one direction. 1065/// It emits a diagnostic and returns true only if it finds an ambiguous 1066/// conversion. 1067static bool TryClassUnification(Sema &Self, Expr *From, Expr *To, 1068 SourceLocation QuestionLoc, 1069 ImplicitConversionSequence &ICS) 1070{ 1071 // C++0x 5.16p3 1072 // The process for determining whether an operand expression E1 of type T1 1073 // can be converted to match an operand expression E2 of type T2 is defined 1074 // as follows: 1075 // -- If E2 is an lvalue: 1076 if (To->isLvalue(Self.Context) == Expr::LV_Valid) { 1077 // E1 can be converted to match E2 if E1 can be implicitly converted to 1078 // type "lvalue reference to T2", subject to the constraint that in the 1079 // conversion the reference must bind directly to E1. 1080 if (!Self.CheckReferenceInit(From, 1081 Self.Context.getLValueReferenceType(To->getType()), 1082 &ICS)) 1083 { 1084 assert((ICS.ConversionKind == 1085 ImplicitConversionSequence::StandardConversion || 1086 ICS.ConversionKind == 1087 ImplicitConversionSequence::UserDefinedConversion) && 1088 "expected a definite conversion"); 1089 bool DirectBinding = 1090 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ? 1091 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding; 1092 if (DirectBinding) 1093 return false; 1094 } 1095 } 1096 ICS.ConversionKind = ImplicitConversionSequence::BadConversion; 1097 // -- If E2 is an rvalue, or if the conversion above cannot be done: 1098 // -- if E1 and E2 have class type, and the underlying class types are 1099 // the same or one is a base class of the other: 1100 QualType FTy = From->getType(); 1101 QualType TTy = To->getType(); 1102 const RecordType *FRec = FTy->getAsRecordType(); 1103 const RecordType *TRec = TTy->getAsRecordType(); 1104 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy); 1105 if (FRec && TRec && (FRec == TRec || 1106 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) { 1107 // E1 can be converted to match E2 if the class of T2 is the 1108 // same type as, or a base class of, the class of T1, and 1109 // [cv2 > cv1]. 1110 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) { 1111 // Could still fail if there's no copy constructor. 1112 // FIXME: Is this a hard error then, or just a conversion failure? The 1113 // standard doesn't say. 1114 ICS = Self.TryCopyInitialization(From, TTy); 1115 } 1116 } else { 1117 // -- Otherwise: E1 can be converted to match E2 if E1 can be 1118 // implicitly converted to the type that expression E2 would have 1119 // if E2 were converted to an rvalue. 1120 // First find the decayed type. 1121 if (TTy->isFunctionType()) 1122 TTy = Self.Context.getPointerType(TTy); 1123 else if(TTy->isArrayType()) 1124 TTy = Self.Context.getArrayDecayedType(TTy); 1125 1126 // Now try the implicit conversion. 1127 // FIXME: This doesn't detect ambiguities. 1128 ICS = Self.TryImplicitConversion(From, TTy); 1129 } 1130 return false; 1131} 1132 1133/// \brief Try to find a common type for two according to C++0x 5.16p5. 1134/// 1135/// This is part of the parameter validation for the ? operator. If either 1136/// value operand is a class type, overload resolution is used to find a 1137/// conversion to a common type. 1138static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS, 1139 SourceLocation Loc) { 1140 Expr *Args[2] = { LHS, RHS }; 1141 OverloadCandidateSet CandidateSet; 1142 Self.AddBuiltinOperatorCandidates(OO_Conditional, Args, 2, CandidateSet); 1143 1144 OverloadCandidateSet::iterator Best; 1145 switch (Self.BestViableFunction(CandidateSet, Best)) { 1146 case Sema::OR_Success: 1147 // We found a match. Perform the conversions on the arguments and move on. 1148 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0], 1149 Best->Conversions[0], "converting") || 1150 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1], 1151 Best->Conversions[1], "converting")) 1152 break; 1153 return false; 1154 1155 case Sema::OR_No_Viable_Function: 1156 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 1157 << LHS->getType() << RHS->getType() 1158 << LHS->getSourceRange() << RHS->getSourceRange(); 1159 return true; 1160 1161 case Sema::OR_Ambiguous: 1162 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl) 1163 << LHS->getType() << RHS->getType() 1164 << LHS->getSourceRange() << RHS->getSourceRange(); 1165 // FIXME: Print the possible common types by printing the return types 1166 // of the viable candidates. 1167 break; 1168 1169 case Sema::OR_Deleted: 1170 assert(false && "Conditional operator has only built-in overloads"); 1171 break; 1172 } 1173 return true; 1174} 1175 1176/// \brief Perform an "extended" implicit conversion as returned by 1177/// TryClassUnification. 1178/// 1179/// TryClassUnification generates ICSs that include reference bindings. 1180/// PerformImplicitConversion is not suitable for this; it chokes if the 1181/// second part of a standard conversion is ICK_DerivedToBase. This function 1182/// handles the reference binding specially. 1183static bool ConvertForConditional(Sema &Self, Expr *&E, 1184 const ImplicitConversionSequence &ICS) 1185{ 1186 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion && 1187 ICS.Standard.ReferenceBinding) { 1188 assert(ICS.Standard.DirectBinding && 1189 "TryClassUnification should never generate indirect ref bindings"); 1190 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of 1191 // redoing all the work. 1192 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType( 1193 TargetType(ICS))); 1194 } 1195 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion && 1196 ICS.UserDefined.After.ReferenceBinding) { 1197 assert(ICS.UserDefined.After.DirectBinding && 1198 "TryClassUnification should never generate indirect ref bindings"); 1199 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType( 1200 TargetType(ICS))); 1201 } 1202 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting")) 1203 return true; 1204 return false; 1205} 1206 1207/// \brief Check the operands of ?: under C++ semantics. 1208/// 1209/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y 1210/// extension. In this case, LHS == Cond. (But they're not aliases.) 1211QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS, 1212 SourceLocation QuestionLoc) { 1213 // FIXME: Handle C99's complex types, vector types, block pointers and 1214 // Obj-C++ interface pointers. 1215 1216 // C++0x 5.16p1 1217 // The first expression is contextually converted to bool. 1218 if (!Cond->isTypeDependent()) { 1219 if (CheckCXXBooleanCondition(Cond)) 1220 return QualType(); 1221 } 1222 1223 // Either of the arguments dependent? 1224 if (LHS->isTypeDependent() || RHS->isTypeDependent()) 1225 return Context.DependentTy; 1226 1227 // C++0x 5.16p2 1228 // If either the second or the third operand has type (cv) void, ... 1229 QualType LTy = LHS->getType(); 1230 QualType RTy = RHS->getType(); 1231 bool LVoid = LTy->isVoidType(); 1232 bool RVoid = RTy->isVoidType(); 1233 if (LVoid || RVoid) { 1234 // ... then the [l2r] conversions are performed on the second and third 1235 // operands ... 1236 DefaultFunctionArrayConversion(LHS); 1237 DefaultFunctionArrayConversion(RHS); 1238 LTy = LHS->getType(); 1239 RTy = RHS->getType(); 1240 1241 // ... and one of the following shall hold: 1242 // -- The second or the third operand (but not both) is a throw- 1243 // expression; the result is of the type of the other and is an rvalue. 1244 bool LThrow = isa<CXXThrowExpr>(LHS); 1245 bool RThrow = isa<CXXThrowExpr>(RHS); 1246 if (LThrow && !RThrow) 1247 return RTy; 1248 if (RThrow && !LThrow) 1249 return LTy; 1250 1251 // -- Both the second and third operands have type void; the result is of 1252 // type void and is an rvalue. 1253 if (LVoid && RVoid) 1254 return Context.VoidTy; 1255 1256 // Neither holds, error. 1257 Diag(QuestionLoc, diag::err_conditional_void_nonvoid) 1258 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1) 1259 << LHS->getSourceRange() << RHS->getSourceRange(); 1260 return QualType(); 1261 } 1262 1263 // Neither is void. 1264 1265 // C++0x 5.16p3 1266 // Otherwise, if the second and third operand have different types, and 1267 // either has (cv) class type, and attempt is made to convert each of those 1268 // operands to the other. 1269 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) && 1270 (LTy->isRecordType() || RTy->isRecordType())) { 1271 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft; 1272 // These return true if a single direction is already ambiguous. 1273 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight)) 1274 return QualType(); 1275 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft)) 1276 return QualType(); 1277 1278 bool HaveL2R = ICSLeftToRight.ConversionKind != 1279 ImplicitConversionSequence::BadConversion; 1280 bool HaveR2L = ICSRightToLeft.ConversionKind != 1281 ImplicitConversionSequence::BadConversion; 1282 // If both can be converted, [...] the program is ill-formed. 1283 if (HaveL2R && HaveR2L) { 1284 Diag(QuestionLoc, diag::err_conditional_ambiguous) 1285 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange(); 1286 return QualType(); 1287 } 1288 1289 // If exactly one conversion is possible, that conversion is applied to 1290 // the chosen operand and the converted operands are used in place of the 1291 // original operands for the remainder of this section. 1292 if (HaveL2R) { 1293 if (ConvertForConditional(*this, LHS, ICSLeftToRight)) 1294 return QualType(); 1295 LTy = LHS->getType(); 1296 } else if (HaveR2L) { 1297 if (ConvertForConditional(*this, RHS, ICSRightToLeft)) 1298 return QualType(); 1299 RTy = RHS->getType(); 1300 } 1301 } 1302 1303 // C++0x 5.16p4 1304 // If the second and third operands are lvalues and have the same type, 1305 // the result is of that type [...] 1306 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy); 1307 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid && 1308 RHS->isLvalue(Context) == Expr::LV_Valid) 1309 return LTy; 1310 1311 // C++0x 5.16p5 1312 // Otherwise, the result is an rvalue. If the second and third operands 1313 // do not have the same type, and either has (cv) class type, ... 1314 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) { 1315 // ... overload resolution is used to determine the conversions (if any) 1316 // to be applied to the operands. If the overload resolution fails, the 1317 // program is ill-formed. 1318 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc)) 1319 return QualType(); 1320 } 1321 1322 // C++0x 5.16p6 1323 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard 1324 // conversions are performed on the second and third operands. 1325 DefaultFunctionArrayConversion(LHS); 1326 DefaultFunctionArrayConversion(RHS); 1327 LTy = LHS->getType(); 1328 RTy = RHS->getType(); 1329 1330 // After those conversions, one of the following shall hold: 1331 // -- The second and third operands have the same type; the result 1332 // is of that type. 1333 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) 1334 return LTy; 1335 1336 // -- The second and third operands have arithmetic or enumeration type; 1337 // the usual arithmetic conversions are performed to bring them to a 1338 // common type, and the result is of that type. 1339 if (LTy->isArithmeticType() && RTy->isArithmeticType()) { 1340 UsualArithmeticConversions(LHS, RHS); 1341 return LHS->getType(); 1342 } 1343 1344 // -- The second and third operands have pointer type, or one has pointer 1345 // type and the other is a null pointer constant; pointer conversions 1346 // and qualification conversions are performed to bring them to their 1347 // composite pointer type. The result is of the composite pointer type. 1348 QualType Composite = FindCompositePointerType(LHS, RHS); 1349 if (!Composite.isNull()) 1350 return Composite; 1351 1352 // Fourth bullet is same for pointers-to-member. However, the possible 1353 // conversions are far more limited: we have null-to-pointer, upcast of 1354 // containing class, and second-level cv-ness. 1355 // cv-ness is not a union, but must match one of the two operands. (Which, 1356 // frankly, is stupid.) 1357 const MemberPointerType *LMemPtr = LTy->getAsMemberPointerType(); 1358 const MemberPointerType *RMemPtr = RTy->getAsMemberPointerType(); 1359 if (LMemPtr && RHS->isNullPointerConstant(Context)) { 1360 ImpCastExprToType(RHS, LTy); 1361 return LTy; 1362 } 1363 if (RMemPtr && LHS->isNullPointerConstant(Context)) { 1364 ImpCastExprToType(LHS, RTy); 1365 return RTy; 1366 } 1367 if (LMemPtr && RMemPtr) { 1368 QualType LPointee = LMemPtr->getPointeeType(); 1369 QualType RPointee = RMemPtr->getPointeeType(); 1370 // First, we check that the unqualified pointee type is the same. If it's 1371 // not, there's no conversion that will unify the two pointers. 1372 if (Context.getCanonicalType(LPointee).getUnqualifiedType() == 1373 Context.getCanonicalType(RPointee).getUnqualifiedType()) { 1374 // Second, we take the greater of the two cv qualifications. If neither 1375 // is greater than the other, the conversion is not possible. 1376 unsigned Q = LPointee.getCVRQualifiers() | RPointee.getCVRQualifiers(); 1377 if (Q == LPointee.getCVRQualifiers() || Q == RPointee.getCVRQualifiers()){ 1378 // Third, we check if either of the container classes is derived from 1379 // the other. 1380 QualType LContainer(LMemPtr->getClass(), 0); 1381 QualType RContainer(RMemPtr->getClass(), 0); 1382 QualType MoreDerived; 1383 if (Context.getCanonicalType(LContainer) == 1384 Context.getCanonicalType(RContainer)) 1385 MoreDerived = LContainer; 1386 else if (IsDerivedFrom(LContainer, RContainer)) 1387 MoreDerived = LContainer; 1388 else if (IsDerivedFrom(RContainer, LContainer)) 1389 MoreDerived = RContainer; 1390 1391 if (!MoreDerived.isNull()) { 1392 // The type 'Q Pointee (MoreDerived::*)' is the common type. 1393 // We don't use ImpCastExprToType here because this could still fail 1394 // for ambiguous or inaccessible conversions. 1395 QualType Common = Context.getMemberPointerType( 1396 LPointee.getQualifiedType(Q), MoreDerived.getTypePtr()); 1397 if (PerformImplicitConversion(LHS, Common, "converting")) 1398 return QualType(); 1399 if (PerformImplicitConversion(RHS, Common, "converting")) 1400 return QualType(); 1401 return Common; 1402 } 1403 } 1404 } 1405 } 1406 1407 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 1408 << LHS->getType() << RHS->getType() 1409 << LHS->getSourceRange() << RHS->getSourceRange(); 1410 return QualType(); 1411} 1412 1413/// \brief Find a merged pointer type and convert the two expressions to it. 1414/// 1415/// This finds the composite pointer type for @p E1 and @p E2 according to 1416/// C++0x 5.9p2. It converts both expressions to this type and returns it. 1417/// It does not emit diagnostics. 1418QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) { 1419 assert(getLangOptions().CPlusPlus && "This function assumes C++"); 1420 QualType T1 = E1->getType(), T2 = E2->getType(); 1421 if(!T1->isPointerType() && !T2->isPointerType()) 1422 return QualType(); 1423 1424 // C++0x 5.9p2 1425 // Pointer conversions and qualification conversions are performed on 1426 // pointer operands to bring them to their composite pointer type. If 1427 // one operand is a null pointer constant, the composite pointer type is 1428 // the type of the other operand. 1429 if (E1->isNullPointerConstant(Context)) { 1430 ImpCastExprToType(E1, T2); 1431 return T2; 1432 } 1433 if (E2->isNullPointerConstant(Context)) { 1434 ImpCastExprToType(E2, T1); 1435 return T1; 1436 } 1437 // Now both have to be pointers. 1438 if(!T1->isPointerType() || !T2->isPointerType()) 1439 return QualType(); 1440 1441 // Otherwise, of one of the operands has type "pointer to cv1 void," then 1442 // the other has type "pointer to cv2 T" and the composite pointer type is 1443 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2. 1444 // Otherwise, the composite pointer type is a pointer type similar to the 1445 // type of one of the operands, with a cv-qualification signature that is 1446 // the union of the cv-qualification signatures of the operand types. 1447 // In practice, the first part here is redundant; it's subsumed by the second. 1448 // What we do here is, we build the two possible composite types, and try the 1449 // conversions in both directions. If only one works, or if the two composite 1450 // types are the same, we have succeeded. 1451 llvm::SmallVector<unsigned, 4> QualifierUnion; 1452 QualType Composite1 = T1, Composite2 = T2; 1453 const PointerType *Ptr1, *Ptr2; 1454 while ((Ptr1 = Composite1->getAsPointerType()) && 1455 (Ptr2 = Composite2->getAsPointerType())) { 1456 Composite1 = Ptr1->getPointeeType(); 1457 Composite2 = Ptr2->getPointeeType(); 1458 QualifierUnion.push_back( 1459 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); 1460 } 1461 // Rewrap the composites as pointers with the union CVRs. 1462 for (llvm::SmallVector<unsigned, 4>::iterator I = QualifierUnion.begin(), 1463 E = QualifierUnion.end(); I != E; ++I) { 1464 Composite1 = Context.getPointerType(Composite1.getQualifiedType(*I)); 1465 Composite2 = Context.getPointerType(Composite2.getQualifiedType(*I)); 1466 } 1467 1468 ImplicitConversionSequence E1ToC1 = TryImplicitConversion(E1, Composite1); 1469 ImplicitConversionSequence E2ToC1 = TryImplicitConversion(E2, Composite1); 1470 ImplicitConversionSequence E1ToC2, E2ToC2; 1471 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion; 1472 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion; 1473 if (Context.getCanonicalType(Composite1) != 1474 Context.getCanonicalType(Composite2)) { 1475 E1ToC2 = TryImplicitConversion(E1, Composite2); 1476 E2ToC2 = TryImplicitConversion(E2, Composite2); 1477 } 1478 1479 bool ToC1Viable = E1ToC1.ConversionKind != 1480 ImplicitConversionSequence::BadConversion 1481 && E2ToC1.ConversionKind != 1482 ImplicitConversionSequence::BadConversion; 1483 bool ToC2Viable = E1ToC2.ConversionKind != 1484 ImplicitConversionSequence::BadConversion 1485 && E2ToC2.ConversionKind != 1486 ImplicitConversionSequence::BadConversion; 1487 if (ToC1Viable && !ToC2Viable) { 1488 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") && 1489 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting")) 1490 return Composite1; 1491 } 1492 if (ToC2Viable && !ToC1Viable) { 1493 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") && 1494 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting")) 1495 return Composite2; 1496 } 1497 return QualType(); 1498} 1499