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