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