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