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