SemaExprCXX.cpp revision e672d5bf6c04c3f24599f49c323ee774815d12ac
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 NamespaceDecl *StdNs = GetStdNamespace(); 65 if (!StdNs) 66 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); 67 68 if (isType) 69 // FIXME: Preserve type source info. 70 TyOrExpr = GetTypeFromParser(TyOrExpr).getAsOpaquePtr(); 71 72 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info"); 73 Decl *TypeInfoDecl = LookupQualifiedName(StdNs, TypeInfoII, 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 GlobalNewDeleteDeclared = true; 665 666 QualType VoidPtr = Context.getPointerType(Context.VoidTy); 667 QualType SizeT = Context.getSizeType(); 668 669 // FIXME: Exception specifications are not added. 670 DeclareGlobalAllocationFunction( 671 Context.DeclarationNames.getCXXOperatorName(OO_New), 672 VoidPtr, SizeT); 673 DeclareGlobalAllocationFunction( 674 Context.DeclarationNames.getCXXOperatorName(OO_Array_New), 675 VoidPtr, SizeT); 676 DeclareGlobalAllocationFunction( 677 Context.DeclarationNames.getCXXOperatorName(OO_Delete), 678 Context.VoidTy, VoidPtr); 679 DeclareGlobalAllocationFunction( 680 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete), 681 Context.VoidTy, VoidPtr); 682} 683 684/// DeclareGlobalAllocationFunction - Declares a single implicit global 685/// allocation function if it doesn't already exist. 686void Sema::DeclareGlobalAllocationFunction(DeclarationName Name, 687 QualType Return, QualType Argument) { 688 DeclContext *GlobalCtx = Context.getTranslationUnitDecl(); 689 690 // Check if this function is already declared. 691 { 692 DeclContext::lookup_iterator Alloc, AllocEnd; 693 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name); 694 Alloc != AllocEnd; ++Alloc) { 695 // FIXME: Do we need to check for default arguments here? 696 FunctionDecl *Func = cast<FunctionDecl>(*Alloc); 697 if (Func->getNumParams() == 1 && 698 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument) 699 return; 700 } 701 } 702 703 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0); 704 FunctionDecl *Alloc = 705 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name, 706 FnType, /*DInfo=*/0, FunctionDecl::None, false, true); 707 Alloc->setImplicit(); 708 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(), 709 0, Argument, /*DInfo=*/0, 710 VarDecl::None, 0); 711 Alloc->setParams(Context, &Param, 1); 712 713 // FIXME: Also add this declaration to the IdentifierResolver, but 714 // make sure it is at the end of the chain to coincide with the 715 // global scope. 716 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc); 717} 718 719/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in: 720/// @code ::delete ptr; @endcode 721/// or 722/// @code delete [] ptr; @endcode 723Action::OwningExprResult 724Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, 725 bool ArrayForm, ExprArg Operand) { 726 // C++ [expr.delete]p1: 727 // The operand shall have a pointer type, or a class type having a single 728 // conversion function to a pointer type. The result has type void. 729 // 730 // DR599 amends "pointer type" to "pointer to object type" in both cases. 731 732 FunctionDecl *OperatorDelete = 0; 733 734 Expr *Ex = (Expr *)Operand.get(); 735 if (!Ex->isTypeDependent()) { 736 QualType Type = Ex->getType(); 737 738 if (const RecordType *Record = Type->getAs<RecordType>()) { 739 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions; 740 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 741 OverloadedFunctionDecl *Conversions = 742 RD->getVisibleConversionFunctions(); 743 744 for (OverloadedFunctionDecl::function_iterator 745 Func = Conversions->function_begin(), 746 FuncEnd = Conversions->function_end(); 747 Func != FuncEnd; ++Func) { 748 // Skip over templated conversion functions; they aren't considered. 749 if (isa<FunctionTemplateDecl>(*Func)) 750 continue; 751 752 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func); 753 754 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 755 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 756 if (ConvPtrType->getPointeeType()->isObjectType()) 757 ObjectPtrConversions.push_back(Conv); 758 } 759 760 if (ObjectPtrConversions.size() == 1) { 761 // We have a single conversion to a pointer-to-object type. Perform 762 // that conversion. 763 Operand.release(); 764 if (PerformImplicitConversion(Ex, 765 ObjectPtrConversions.front()->getConversionType(), 766 "converting")) 767 return ExprError(); 768 769 Operand = Owned(Ex); 770 Type = Ex->getType(); 771 } 772 } 773 774 if (!Type->isPointerType()) 775 return ExprError(Diag(StartLoc, diag::err_delete_operand) 776 << Type << Ex->getSourceRange()); 777 778 QualType Pointee = Type->getAs<PointerType>()->getPointeeType(); 779 if (Pointee->isFunctionType() || Pointee->isVoidType()) 780 return ExprError(Diag(StartLoc, diag::err_delete_operand) 781 << Type << Ex->getSourceRange()); 782 else if (!Pointee->isDependentType() && 783 RequireCompleteType(StartLoc, Pointee, 784 PDiag(diag::warn_delete_incomplete) 785 << Ex->getSourceRange())) 786 return ExprError(); 787 788 // FIXME: This should be shared with the code for finding the delete 789 // operator in ActOnCXXNew. 790 IntegerLiteral Size(llvm::APInt::getNullValue( 791 Context.Target.getPointerWidth(0)), 792 Context.getSizeType(), 793 SourceLocation()); 794 ImplicitCastExpr Cast(Context.getPointerType(Context.VoidTy), 795 CastExpr::CK_Unknown, &Size, false); 796 Expr *DeleteArg = &Cast; 797 798 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( 799 ArrayForm ? OO_Array_Delete : OO_Delete); 800 801 if (Pointee->isRecordType() && !UseGlobal) { 802 CXXRecordDecl *Record 803 = cast<CXXRecordDecl>(Pointee->getAs<RecordType>()->getDecl()); 804 // FIXME: We fail to find inherited overloads. 805 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName, 806 &DeleteArg, 1, Record, /*AllowMissing=*/true, 807 OperatorDelete)) 808 return ExprError(); 809 if (!Record->hasTrivialDestructor()) 810 if (const CXXDestructorDecl *Dtor = Record->getDestructor(Context)) 811 MarkDeclarationReferenced(StartLoc, 812 const_cast<CXXDestructorDecl*>(Dtor)); 813 } 814 815 if (!OperatorDelete) { 816 // Didn't find a member overload. Look for a global one. 817 DeclareGlobalNewDelete(); 818 DeclContext *TUDecl = Context.getTranslationUnitDecl(); 819 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName, 820 &DeleteArg, 1, TUDecl, /*AllowMissing=*/false, 821 OperatorDelete)) 822 return ExprError(); 823 } 824 825 // FIXME: Check access and ambiguity of operator delete and destructor. 826 } 827 828 Operand.release(); 829 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm, 830 OperatorDelete, Ex, StartLoc)); 831} 832 833 834/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 835/// C++ if/switch/while/for statement. 836/// e.g: "if (int x = f()) {...}" 837Action::OwningExprResult 838Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc, 839 Declarator &D, 840 SourceLocation EqualLoc, 841 ExprArg AssignExprVal) { 842 assert(AssignExprVal.get() && "Null assignment expression"); 843 844 // C++ 6.4p2: 845 // The declarator shall not specify a function or an array. 846 // The type-specifier-seq shall not contain typedef and shall not declare a 847 // new class or enumeration. 848 849 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 850 "Parser allowed 'typedef' as storage class of condition decl."); 851 852 // FIXME: Store DeclaratorInfo in the expression. 853 DeclaratorInfo *DInfo = 0; 854 TagDecl *OwnedTag = 0; 855 QualType Ty = GetTypeForDeclarator(D, S, &DInfo, /*Skip=*/0, &OwnedTag); 856 857 if (Ty->isFunctionType()) { // The declarator shall not specify a function... 858 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl 859 // would be created and CXXConditionDeclExpr wants a VarDecl. 860 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type) 861 << SourceRange(StartLoc, EqualLoc)); 862 } else if (Ty->isArrayType()) { // ...or an array. 863 Diag(StartLoc, diag::err_invalid_use_of_array_type) 864 << SourceRange(StartLoc, EqualLoc); 865 } else if (OwnedTag && OwnedTag->isDefinition()) { 866 // The type-specifier-seq shall not declare a new class or enumeration. 867 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition); 868 } 869 870 DeclPtrTy Dcl = ActOnDeclarator(S, D); 871 if (!Dcl) 872 return ExprError(); 873 AddInitializerToDecl(Dcl, move(AssignExprVal), /*DirectInit=*/false); 874 875 // Mark this variable as one that is declared within a conditional. 876 // We know that the decl had to be a VarDecl because that is the only type of 877 // decl that can be assigned and the grammar requires an '='. 878 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>()); 879 VD->setDeclaredInCondition(true); 880 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD)); 881} 882 883/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid. 884bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) { 885 // C++ 6.4p4: 886 // The value of a condition that is an initialized declaration in a statement 887 // other than a switch statement is the value of the declared variable 888 // implicitly converted to type bool. If that conversion is ill-formed, the 889 // program is ill-formed. 890 // The value of a condition that is an expression is the value of the 891 // expression, implicitly converted to bool. 892 // 893 return PerformContextuallyConvertToBool(CondExpr); 894} 895 896/// Helper function to determine whether this is the (deprecated) C++ 897/// conversion from a string literal to a pointer to non-const char or 898/// non-const wchar_t (for narrow and wide string literals, 899/// respectively). 900bool 901Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) { 902 // Look inside the implicit cast, if it exists. 903 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From)) 904 From = Cast->getSubExpr(); 905 906 // A string literal (2.13.4) that is not a wide string literal can 907 // be converted to an rvalue of type "pointer to char"; a wide 908 // string literal can be converted to an rvalue of type "pointer 909 // to wchar_t" (C++ 4.2p2). 910 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From)) 911 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) 912 if (const BuiltinType *ToPointeeType 913 = ToPtrType->getPointeeType()->getAsBuiltinType()) { 914 // This conversion is considered only when there is an 915 // explicit appropriate pointer target type (C++ 4.2p2). 916 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 && 917 ((StrLit->isWide() && ToPointeeType->isWideCharType()) || 918 (!StrLit->isWide() && 919 (ToPointeeType->getKind() == BuiltinType::Char_U || 920 ToPointeeType->getKind() == BuiltinType::Char_S)))) 921 return true; 922 } 923 924 return false; 925} 926 927/// PerformImplicitConversion - Perform an implicit conversion of the 928/// expression From to the type ToType. Returns true if there was an 929/// error, false otherwise. The expression From is replaced with the 930/// converted expression. Flavor is the kind of conversion we're 931/// performing, used in the error message. If @p AllowExplicit, 932/// explicit user-defined conversions are permitted. @p Elidable should be true 933/// when called for copies which may be elided (C++ 12.8p15). C++0x overload 934/// resolution works differently in that case. 935bool 936Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 937 const char *Flavor, bool AllowExplicit, 938 bool Elidable) { 939 ImplicitConversionSequence ICS; 940 ICS.ConversionKind = ImplicitConversionSequence::BadConversion; 941 if (Elidable && getLangOptions().CPlusPlus0x) { 942 ICS = TryImplicitConversion(From, ToType, 943 /*SuppressUserConversions=*/false, 944 AllowExplicit, 945 /*ForceRValue=*/true, 946 /*InOverloadResolution=*/false); 947 } 948 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) { 949 ICS = TryImplicitConversion(From, ToType, 950 /*SuppressUserConversions=*/false, 951 AllowExplicit, 952 /*ForceRValue=*/false, 953 /*InOverloadResolution=*/false); 954 } 955 return PerformImplicitConversion(From, ToType, ICS, Flavor); 956} 957 958/// PerformImplicitConversion - Perform an implicit conversion of the 959/// expression From to the type ToType using the pre-computed implicit 960/// conversion sequence ICS. Returns true if there was an error, false 961/// otherwise. The expression From is replaced with the converted 962/// expression. Flavor is the kind of conversion we're performing, 963/// used in the error message. 964bool 965Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 966 const ImplicitConversionSequence &ICS, 967 const char* Flavor) { 968 switch (ICS.ConversionKind) { 969 case ImplicitConversionSequence::StandardConversion: 970 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor)) 971 return true; 972 break; 973 974 case ImplicitConversionSequence::UserDefinedConversion: 975 { 976 FunctionDecl *FD = ICS.UserDefined.ConversionFunction; 977 CastExpr::CastKind CastKind = CastExpr::CK_Unknown; 978 if (isa<CXXConversionDecl>(FD)) 979 CastKind = CastExpr::CK_UserDefinedConversion; 980 else if (isa<CXXConstructorDecl>(FD)) 981 CastKind = CastExpr::CK_ConstructorConversion; 982 else 983 assert(0 && "Unknown conversion function kind!"); 984 985 OwningExprResult CastArg 986 = BuildCXXCastArgument(From->getLocStart(), 987 ToType.getNonReferenceType(), 988 CastKind, cast<CXXMethodDecl>(FD), 989 Owned(From)); 990 991 if (CastArg.isInvalid()) 992 return true; 993 994 From = new (Context) ImplicitCastExpr(ToType.getNonReferenceType(), 995 CastKind, CastArg.takeAs<Expr>(), 996 ToType->isLValueReferenceType()); 997 return false; 998 } 999 1000 case ImplicitConversionSequence::EllipsisConversion: 1001 assert(false && "Cannot perform an ellipsis conversion"); 1002 return false; 1003 1004 case ImplicitConversionSequence::BadConversion: 1005 return true; 1006 } 1007 1008 // Everything went well. 1009 return false; 1010} 1011 1012/// PerformImplicitConversion - Perform an implicit conversion of the 1013/// expression From to the type ToType by following the standard 1014/// conversion sequence SCS. Returns true if there was an error, false 1015/// otherwise. The expression From is replaced with the converted 1016/// expression. Flavor is the context in which we're performing this 1017/// conversion, for use in error messages. 1018bool 1019Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 1020 const StandardConversionSequence& SCS, 1021 const char *Flavor) { 1022 // Overall FIXME: we are recomputing too many types here and doing far too 1023 // much extra work. What this means is that we need to keep track of more 1024 // information that is computed when we try the implicit conversion initially, 1025 // so that we don't need to recompute anything here. 1026 QualType FromType = From->getType(); 1027 1028 if (SCS.CopyConstructor) { 1029 // FIXME: When can ToType be a reference type? 1030 assert(!ToType->isReferenceType()); 1031 1032 OwningExprResult FromResult = 1033 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(), 1034 ToType, SCS.CopyConstructor, 1035 MultiExprArg(*this, (void**)&From, 1)); 1036 1037 if (FromResult.isInvalid()) 1038 return true; 1039 1040 From = FromResult.takeAs<Expr>(); 1041 return false; 1042 } 1043 1044 // Perform the first implicit conversion. 1045 switch (SCS.First) { 1046 case ICK_Identity: 1047 case ICK_Lvalue_To_Rvalue: 1048 // Nothing to do. 1049 break; 1050 1051 case ICK_Array_To_Pointer: 1052 FromType = Context.getArrayDecayedType(FromType); 1053 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay); 1054 break; 1055 1056 case ICK_Function_To_Pointer: 1057 if (Context.getCanonicalType(FromType) == Context.OverloadTy) { 1058 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true); 1059 if (!Fn) 1060 return true; 1061 1062 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin())) 1063 return true; 1064 1065 FixOverloadedFunctionReference(From, Fn); 1066 FromType = From->getType(); 1067 } 1068 FromType = Context.getPointerType(FromType); 1069 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay); 1070 break; 1071 1072 default: 1073 assert(false && "Improper first standard conversion"); 1074 break; 1075 } 1076 1077 // Perform the second implicit conversion 1078 switch (SCS.Second) { 1079 case ICK_Identity: 1080 // Nothing to do. 1081 break; 1082 1083 case ICK_Integral_Promotion: 1084 case ICK_Floating_Promotion: 1085 case ICK_Complex_Promotion: 1086 case ICK_Integral_Conversion: 1087 case ICK_Floating_Conversion: 1088 case ICK_Complex_Conversion: 1089 case ICK_Floating_Integral: 1090 case ICK_Complex_Real: 1091 case ICK_Compatible_Conversion: 1092 // FIXME: Go deeper to get the unqualified type! 1093 FromType = ToType.getUnqualifiedType(); 1094 ImpCastExprToType(From, FromType); 1095 break; 1096 1097 case ICK_Pointer_Conversion: { 1098 if (SCS.IncompatibleObjC) { 1099 // Diagnose incompatible Objective-C conversions 1100 Diag(From->getSourceRange().getBegin(), 1101 diag::ext_typecheck_convert_incompatible_pointer) 1102 << From->getType() << ToType << Flavor 1103 << From->getSourceRange(); 1104 } 1105 1106 1107 CastExpr::CastKind Kind = CastExpr::CK_Unknown; 1108 if (CheckPointerConversion(From, ToType, Kind)) 1109 return true; 1110 ImpCastExprToType(From, ToType, Kind); 1111 break; 1112 } 1113 1114 case ICK_Pointer_Member: { 1115 CastExpr::CastKind Kind = CastExpr::CK_Unknown; 1116 if (CheckMemberPointerConversion(From, ToType, Kind)) 1117 return true; 1118 ImpCastExprToType(From, ToType, Kind); 1119 break; 1120 } 1121 case ICK_Boolean_Conversion: 1122 FromType = Context.BoolTy; 1123 ImpCastExprToType(From, FromType); 1124 break; 1125 1126 default: 1127 assert(false && "Improper second standard conversion"); 1128 break; 1129 } 1130 1131 switch (SCS.Third) { 1132 case ICK_Identity: 1133 // Nothing to do. 1134 break; 1135 1136 case ICK_Qualification: 1137 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue 1138 // references. 1139 ImpCastExprToType(From, ToType.getNonReferenceType(), 1140 CastExpr::CK_Unknown, 1141 ToType->isLValueReferenceType()); 1142 break; 1143 1144 default: 1145 assert(false && "Improper second standard conversion"); 1146 break; 1147 } 1148 1149 return false; 1150} 1151 1152Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT, 1153 SourceLocation KWLoc, 1154 SourceLocation LParen, 1155 TypeTy *Ty, 1156 SourceLocation RParen) { 1157 QualType T = GetTypeFromParser(Ty); 1158 1159 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html 1160 // all traits except __is_class, __is_enum and __is_union require a the type 1161 // to be complete. 1162 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) { 1163 if (RequireCompleteType(KWLoc, T, 1164 diag::err_incomplete_type_used_in_type_trait_expr)) 1165 return ExprError(); 1166 } 1167 1168 // There is no point in eagerly computing the value. The traits are designed 1169 // to be used from type trait templates, so Ty will be a template parameter 1170 // 99% of the time. 1171 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T, 1172 RParen, Context.BoolTy)); 1173} 1174 1175QualType Sema::CheckPointerToMemberOperands( 1176 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) { 1177 const char *OpSpelling = isIndirect ? "->*" : ".*"; 1178 // C++ 5.5p2 1179 // The binary operator .* [p3: ->*] binds its second operand, which shall 1180 // be of type "pointer to member of T" (where T is a completely-defined 1181 // class type) [...] 1182 QualType RType = rex->getType(); 1183 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>(); 1184 if (!MemPtr) { 1185 Diag(Loc, diag::err_bad_memptr_rhs) 1186 << OpSpelling << RType << rex->getSourceRange(); 1187 return QualType(); 1188 } 1189 1190 QualType Class(MemPtr->getClass(), 0); 1191 1192 // C++ 5.5p2 1193 // [...] to its first operand, which shall be of class T or of a class of 1194 // which T is an unambiguous and accessible base class. [p3: a pointer to 1195 // such a class] 1196 QualType LType = lex->getType(); 1197 if (isIndirect) { 1198 if (const PointerType *Ptr = LType->getAs<PointerType>()) 1199 LType = Ptr->getPointeeType().getNonReferenceType(); 1200 else { 1201 Diag(Loc, diag::err_bad_memptr_lhs) 1202 << OpSpelling << 1 << LType << lex->getSourceRange(); 1203 return QualType(); 1204 } 1205 } 1206 1207 if (Context.getCanonicalType(Class).getUnqualifiedType() != 1208 Context.getCanonicalType(LType).getUnqualifiedType()) { 1209 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 1210 /*DetectVirtual=*/false); 1211 // FIXME: Would it be useful to print full ambiguity paths, or is that 1212 // overkill? 1213 if (!IsDerivedFrom(LType, Class, Paths) || 1214 Paths.isAmbiguous(Context.getCanonicalType(Class))) { 1215 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling 1216 << (int)isIndirect << lex->getType() << lex->getSourceRange(); 1217 return QualType(); 1218 } 1219 } 1220 1221 // C++ 5.5p2 1222 // The result is an object or a function of the type specified by the 1223 // second operand. 1224 // The cv qualifiers are the union of those in the pointer and the left side, 1225 // in accordance with 5.5p5 and 5.2.5. 1226 // FIXME: This returns a dereferenced member function pointer as a normal 1227 // function type. However, the only operation valid on such functions is 1228 // calling them. There's also a GCC extension to get a function pointer to the 1229 // thing, which is another complication, because this type - unlike the type 1230 // that is the result of this expression - takes the class as the first 1231 // argument. 1232 // We probably need a "MemberFunctionClosureType" or something like that. 1233 QualType Result = MemPtr->getPointeeType(); 1234 if (LType.isConstQualified()) 1235 Result.addConst(); 1236 if (LType.isVolatileQualified()) 1237 Result.addVolatile(); 1238 return Result; 1239} 1240 1241/// \brief Get the target type of a standard or user-defined conversion. 1242static QualType TargetType(const ImplicitConversionSequence &ICS) { 1243 assert((ICS.ConversionKind == 1244 ImplicitConversionSequence::StandardConversion || 1245 ICS.ConversionKind == 1246 ImplicitConversionSequence::UserDefinedConversion) && 1247 "function only valid for standard or user-defined conversions"); 1248 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion) 1249 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr); 1250 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr); 1251} 1252 1253/// \brief Try to convert a type to another according to C++0x 5.16p3. 1254/// 1255/// This is part of the parameter validation for the ? operator. If either 1256/// value operand is a class type, the two operands are attempted to be 1257/// converted to each other. This function does the conversion in one direction. 1258/// It emits a diagnostic and returns true only if it finds an ambiguous 1259/// conversion. 1260static bool TryClassUnification(Sema &Self, Expr *From, Expr *To, 1261 SourceLocation QuestionLoc, 1262 ImplicitConversionSequence &ICS) { 1263 // C++0x 5.16p3 1264 // The process for determining whether an operand expression E1 of type T1 1265 // can be converted to match an operand expression E2 of type T2 is defined 1266 // as follows: 1267 // -- If E2 is an lvalue: 1268 if (To->isLvalue(Self.Context) == Expr::LV_Valid) { 1269 // E1 can be converted to match E2 if E1 can be implicitly converted to 1270 // type "lvalue reference to T2", subject to the constraint that in the 1271 // conversion the reference must bind directly to E1. 1272 if (!Self.CheckReferenceInit(From, 1273 Self.Context.getLValueReferenceType(To->getType()), 1274 /*SuppressUserConversions=*/false, 1275 /*AllowExplicit=*/false, 1276 /*ForceRValue=*/false, 1277 &ICS)) 1278 { 1279 assert((ICS.ConversionKind == 1280 ImplicitConversionSequence::StandardConversion || 1281 ICS.ConversionKind == 1282 ImplicitConversionSequence::UserDefinedConversion) && 1283 "expected a definite conversion"); 1284 bool DirectBinding = 1285 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ? 1286 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding; 1287 if (DirectBinding) 1288 return false; 1289 } 1290 } 1291 ICS.ConversionKind = ImplicitConversionSequence::BadConversion; 1292 // -- If E2 is an rvalue, or if the conversion above cannot be done: 1293 // -- if E1 and E2 have class type, and the underlying class types are 1294 // the same or one is a base class of the other: 1295 QualType FTy = From->getType(); 1296 QualType TTy = To->getType(); 1297 const RecordType *FRec = FTy->getAs<RecordType>(); 1298 const RecordType *TRec = TTy->getAs<RecordType>(); 1299 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy); 1300 if (FRec && TRec && (FRec == TRec || 1301 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) { 1302 // E1 can be converted to match E2 if the class of T2 is the 1303 // same type as, or a base class of, the class of T1, and 1304 // [cv2 > cv1]. 1305 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) { 1306 // Could still fail if there's no copy constructor. 1307 // FIXME: Is this a hard error then, or just a conversion failure? The 1308 // standard doesn't say. 1309 ICS = Self.TryCopyInitialization(From, TTy, 1310 /*SuppressUserConversions=*/false, 1311 /*ForceRValue=*/false, 1312 /*InOverloadResolution=*/false); 1313 } 1314 } else { 1315 // -- Otherwise: E1 can be converted to match E2 if E1 can be 1316 // implicitly converted to the type that expression E2 would have 1317 // if E2 were converted to an rvalue. 1318 // First find the decayed type. 1319 if (TTy->isFunctionType()) 1320 TTy = Self.Context.getPointerType(TTy); 1321 else if (TTy->isArrayType()) 1322 TTy = Self.Context.getArrayDecayedType(TTy); 1323 1324 // Now try the implicit conversion. 1325 // FIXME: This doesn't detect ambiguities. 1326 ICS = Self.TryImplicitConversion(From, TTy, 1327 /*SuppressUserConversions=*/false, 1328 /*AllowExplicit=*/false, 1329 /*ForceRValue=*/false, 1330 /*InOverloadResolution=*/false); 1331 } 1332 return false; 1333} 1334 1335/// \brief Try to find a common type for two according to C++0x 5.16p5. 1336/// 1337/// This is part of the parameter validation for the ? operator. If either 1338/// value operand is a class type, overload resolution is used to find a 1339/// conversion to a common type. 1340static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS, 1341 SourceLocation Loc) { 1342 Expr *Args[2] = { LHS, RHS }; 1343 OverloadCandidateSet CandidateSet; 1344 Self.AddBuiltinOperatorCandidates(OO_Conditional, Args, 2, CandidateSet); 1345 1346 OverloadCandidateSet::iterator Best; 1347 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) { 1348 case Sema::OR_Success: 1349 // We found a match. Perform the conversions on the arguments and move on. 1350 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0], 1351 Best->Conversions[0], "converting") || 1352 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1], 1353 Best->Conversions[1], "converting")) 1354 break; 1355 return false; 1356 1357 case Sema::OR_No_Viable_Function: 1358 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 1359 << LHS->getType() << RHS->getType() 1360 << LHS->getSourceRange() << RHS->getSourceRange(); 1361 return true; 1362 1363 case Sema::OR_Ambiguous: 1364 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl) 1365 << LHS->getType() << RHS->getType() 1366 << LHS->getSourceRange() << RHS->getSourceRange(); 1367 // FIXME: Print the possible common types by printing the return types of 1368 // the viable candidates. 1369 break; 1370 1371 case Sema::OR_Deleted: 1372 assert(false && "Conditional operator has only built-in overloads"); 1373 break; 1374 } 1375 return true; 1376} 1377 1378/// \brief Perform an "extended" implicit conversion as returned by 1379/// TryClassUnification. 1380/// 1381/// TryClassUnification generates ICSs that include reference bindings. 1382/// PerformImplicitConversion is not suitable for this; it chokes if the 1383/// second part of a standard conversion is ICK_DerivedToBase. This function 1384/// handles the reference binding specially. 1385static bool ConvertForConditional(Sema &Self, Expr *&E, 1386 const ImplicitConversionSequence &ICS) { 1387 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion && 1388 ICS.Standard.ReferenceBinding) { 1389 assert(ICS.Standard.DirectBinding && 1390 "TryClassUnification should never generate indirect ref bindings"); 1391 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of 1392 // redoing all the work. 1393 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType( 1394 TargetType(ICS)), 1395 /*SuppressUserConversions=*/false, 1396 /*AllowExplicit=*/false, 1397 /*ForceRValue=*/false); 1398 } 1399 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion && 1400 ICS.UserDefined.After.ReferenceBinding) { 1401 assert(ICS.UserDefined.After.DirectBinding && 1402 "TryClassUnification should never generate indirect ref bindings"); 1403 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType( 1404 TargetType(ICS)), 1405 /*SuppressUserConversions=*/false, 1406 /*AllowExplicit=*/false, 1407 /*ForceRValue=*/false); 1408 } 1409 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting")) 1410 return true; 1411 return false; 1412} 1413 1414/// \brief Check the operands of ?: under C++ semantics. 1415/// 1416/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y 1417/// extension. In this case, LHS == Cond. (But they're not aliases.) 1418QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS, 1419 SourceLocation QuestionLoc) { 1420 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++ 1421 // interface pointers. 1422 1423 // C++0x 5.16p1 1424 // The first expression is contextually converted to bool. 1425 if (!Cond->isTypeDependent()) { 1426 if (CheckCXXBooleanCondition(Cond)) 1427 return QualType(); 1428 } 1429 1430 // Either of the arguments dependent? 1431 if (LHS->isTypeDependent() || RHS->isTypeDependent()) 1432 return Context.DependentTy; 1433 1434 // C++0x 5.16p2 1435 // If either the second or the third operand has type (cv) void, ... 1436 QualType LTy = LHS->getType(); 1437 QualType RTy = RHS->getType(); 1438 bool LVoid = LTy->isVoidType(); 1439 bool RVoid = RTy->isVoidType(); 1440 if (LVoid || RVoid) { 1441 // ... then the [l2r] conversions are performed on the second and third 1442 // operands ... 1443 DefaultFunctionArrayConversion(LHS); 1444 DefaultFunctionArrayConversion(RHS); 1445 LTy = LHS->getType(); 1446 RTy = RHS->getType(); 1447 1448 // ... and one of the following shall hold: 1449 // -- The second or the third operand (but not both) is a throw- 1450 // expression; the result is of the type of the other and is an rvalue. 1451 bool LThrow = isa<CXXThrowExpr>(LHS); 1452 bool RThrow = isa<CXXThrowExpr>(RHS); 1453 if (LThrow && !RThrow) 1454 return RTy; 1455 if (RThrow && !LThrow) 1456 return LTy; 1457 1458 // -- Both the second and third operands have type void; the result is of 1459 // type void and is an rvalue. 1460 if (LVoid && RVoid) 1461 return Context.VoidTy; 1462 1463 // Neither holds, error. 1464 Diag(QuestionLoc, diag::err_conditional_void_nonvoid) 1465 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1) 1466 << LHS->getSourceRange() << RHS->getSourceRange(); 1467 return QualType(); 1468 } 1469 1470 // Neither is void. 1471 1472 // C++0x 5.16p3 1473 // Otherwise, if the second and third operand have different types, and 1474 // either has (cv) class type, and attempt is made to convert each of those 1475 // operands to the other. 1476 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) && 1477 (LTy->isRecordType() || RTy->isRecordType())) { 1478 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft; 1479 // These return true if a single direction is already ambiguous. 1480 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight)) 1481 return QualType(); 1482 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft)) 1483 return QualType(); 1484 1485 bool HaveL2R = ICSLeftToRight.ConversionKind != 1486 ImplicitConversionSequence::BadConversion; 1487 bool HaveR2L = ICSRightToLeft.ConversionKind != 1488 ImplicitConversionSequence::BadConversion; 1489 // If both can be converted, [...] the program is ill-formed. 1490 if (HaveL2R && HaveR2L) { 1491 Diag(QuestionLoc, diag::err_conditional_ambiguous) 1492 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange(); 1493 return QualType(); 1494 } 1495 1496 // If exactly one conversion is possible, that conversion is applied to 1497 // the chosen operand and the converted operands are used in place of the 1498 // original operands for the remainder of this section. 1499 if (HaveL2R) { 1500 if (ConvertForConditional(*this, LHS, ICSLeftToRight)) 1501 return QualType(); 1502 LTy = LHS->getType(); 1503 } else if (HaveR2L) { 1504 if (ConvertForConditional(*this, RHS, ICSRightToLeft)) 1505 return QualType(); 1506 RTy = RHS->getType(); 1507 } 1508 } 1509 1510 // C++0x 5.16p4 1511 // If the second and third operands are lvalues and have the same type, 1512 // the result is of that type [...] 1513 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy); 1514 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid && 1515 RHS->isLvalue(Context) == Expr::LV_Valid) 1516 return LTy; 1517 1518 // C++0x 5.16p5 1519 // Otherwise, the result is an rvalue. If the second and third operands 1520 // do not have the same type, and either has (cv) class type, ... 1521 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) { 1522 // ... overload resolution is used to determine the conversions (if any) 1523 // to be applied to the operands. If the overload resolution fails, the 1524 // program is ill-formed. 1525 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc)) 1526 return QualType(); 1527 } 1528 1529 // C++0x 5.16p6 1530 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard 1531 // conversions are performed on the second and third operands. 1532 DefaultFunctionArrayConversion(LHS); 1533 DefaultFunctionArrayConversion(RHS); 1534 LTy = LHS->getType(); 1535 RTy = RHS->getType(); 1536 1537 // After those conversions, one of the following shall hold: 1538 // -- The second and third operands have the same type; the result 1539 // is of that type. 1540 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) 1541 return LTy; 1542 1543 // -- The second and third operands have arithmetic or enumeration type; 1544 // the usual arithmetic conversions are performed to bring them to a 1545 // common type, and the result is of that type. 1546 if (LTy->isArithmeticType() && RTy->isArithmeticType()) { 1547 UsualArithmeticConversions(LHS, RHS); 1548 return LHS->getType(); 1549 } 1550 1551 // -- The second and third operands have pointer type, or one has pointer 1552 // type and the other is a null pointer constant; pointer conversions 1553 // and qualification conversions are performed to bring them to their 1554 // composite pointer type. The result is of the composite pointer type. 1555 QualType Composite = FindCompositePointerType(LHS, RHS); 1556 if (!Composite.isNull()) 1557 return Composite; 1558 1559 // Fourth bullet is same for pointers-to-member. However, the possible 1560 // conversions are far more limited: we have null-to-pointer, upcast of 1561 // containing class, and second-level cv-ness. 1562 // cv-ness is not a union, but must match one of the two operands. (Which, 1563 // frankly, is stupid.) 1564 const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>(); 1565 const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>(); 1566 if (LMemPtr && RHS->isNullPointerConstant(Context)) { 1567 ImpCastExprToType(RHS, LTy); 1568 return LTy; 1569 } 1570 if (RMemPtr && LHS->isNullPointerConstant(Context)) { 1571 ImpCastExprToType(LHS, RTy); 1572 return RTy; 1573 } 1574 if (LMemPtr && RMemPtr) { 1575 QualType LPointee = LMemPtr->getPointeeType(); 1576 QualType RPointee = RMemPtr->getPointeeType(); 1577 // First, we check that the unqualified pointee type is the same. If it's 1578 // not, there's no conversion that will unify the two pointers. 1579 if (Context.getCanonicalType(LPointee).getUnqualifiedType() == 1580 Context.getCanonicalType(RPointee).getUnqualifiedType()) { 1581 // Second, we take the greater of the two cv qualifications. If neither 1582 // is greater than the other, the conversion is not possible. 1583 unsigned Q = LPointee.getCVRQualifiers() | RPointee.getCVRQualifiers(); 1584 if (Q == LPointee.getCVRQualifiers() || Q == RPointee.getCVRQualifiers()){ 1585 // Third, we check if either of the container classes is derived from 1586 // the other. 1587 QualType LContainer(LMemPtr->getClass(), 0); 1588 QualType RContainer(RMemPtr->getClass(), 0); 1589 QualType MoreDerived; 1590 if (Context.getCanonicalType(LContainer) == 1591 Context.getCanonicalType(RContainer)) 1592 MoreDerived = LContainer; 1593 else if (IsDerivedFrom(LContainer, RContainer)) 1594 MoreDerived = LContainer; 1595 else if (IsDerivedFrom(RContainer, LContainer)) 1596 MoreDerived = RContainer; 1597 1598 if (!MoreDerived.isNull()) { 1599 // The type 'Q Pointee (MoreDerived::*)' is the common type. 1600 // We don't use ImpCastExprToType here because this could still fail 1601 // for ambiguous or inaccessible conversions. 1602 QualType Common = Context.getMemberPointerType( 1603 LPointee.getQualifiedType(Q), MoreDerived.getTypePtr()); 1604 if (PerformImplicitConversion(LHS, Common, "converting")) 1605 return QualType(); 1606 if (PerformImplicitConversion(RHS, Common, "converting")) 1607 return QualType(); 1608 return Common; 1609 } 1610 } 1611 } 1612 } 1613 1614 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 1615 << LHS->getType() << RHS->getType() 1616 << LHS->getSourceRange() << RHS->getSourceRange(); 1617 return QualType(); 1618} 1619 1620/// \brief Find a merged pointer type and convert the two expressions to it. 1621/// 1622/// This finds the composite pointer type (or member pointer type) for @p E1 1623/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this 1624/// type and returns it. 1625/// It does not emit diagnostics. 1626QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) { 1627 assert(getLangOptions().CPlusPlus && "This function assumes C++"); 1628 QualType T1 = E1->getType(), T2 = E2->getType(); 1629 1630 if (!T1->isPointerType() && !T1->isMemberPointerType() && 1631 !T2->isPointerType() && !T2->isMemberPointerType()) 1632 return QualType(); 1633 1634 // FIXME: Do we need to work on the canonical types? 1635 1636 // C++0x 5.9p2 1637 // Pointer conversions and qualification conversions are performed on 1638 // pointer operands to bring them to their composite pointer type. If 1639 // one operand is a null pointer constant, the composite pointer type is 1640 // the type of the other operand. 1641 if (E1->isNullPointerConstant(Context)) { 1642 ImpCastExprToType(E1, T2); 1643 return T2; 1644 } 1645 if (E2->isNullPointerConstant(Context)) { 1646 ImpCastExprToType(E2, T1); 1647 return T1; 1648 } 1649 1650 // Now both have to be pointers or member pointers. 1651 if (!T1->isPointerType() && !T1->isMemberPointerType() && 1652 !T2->isPointerType() && !T2->isMemberPointerType()) 1653 return QualType(); 1654 1655 // Otherwise, of one of the operands has type "pointer to cv1 void," then 1656 // the other has type "pointer to cv2 T" and the composite pointer type is 1657 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2. 1658 // Otherwise, the composite pointer type is a pointer type similar to the 1659 // type of one of the operands, with a cv-qualification signature that is 1660 // the union of the cv-qualification signatures of the operand types. 1661 // In practice, the first part here is redundant; it's subsumed by the second. 1662 // What we do here is, we build the two possible composite types, and try the 1663 // conversions in both directions. If only one works, or if the two composite 1664 // types are the same, we have succeeded. 1665 llvm::SmallVector<unsigned, 4> QualifierUnion; 1666 llvm::SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass; 1667 QualType Composite1 = T1, Composite2 = T2; 1668 do { 1669 const PointerType *Ptr1, *Ptr2; 1670 if ((Ptr1 = Composite1->getAs<PointerType>()) && 1671 (Ptr2 = Composite2->getAs<PointerType>())) { 1672 Composite1 = Ptr1->getPointeeType(); 1673 Composite2 = Ptr2->getPointeeType(); 1674 QualifierUnion.push_back( 1675 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); 1676 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0)); 1677 continue; 1678 } 1679 1680 const MemberPointerType *MemPtr1, *MemPtr2; 1681 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) && 1682 (MemPtr2 = Composite2->getAs<MemberPointerType>())) { 1683 Composite1 = MemPtr1->getPointeeType(); 1684 Composite2 = MemPtr2->getPointeeType(); 1685 QualifierUnion.push_back( 1686 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); 1687 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(), 1688 MemPtr2->getClass())); 1689 continue; 1690 } 1691 1692 // FIXME: block pointer types? 1693 1694 // Cannot unwrap any more types. 1695 break; 1696 } while (true); 1697 1698 // Rewrap the composites as pointers or member pointers with the union CVRs. 1699 llvm::SmallVector<std::pair<const Type *, const Type *>, 4>::iterator MOC 1700 = MemberOfClass.begin(); 1701 for (llvm::SmallVector<unsigned, 4>::iterator 1702 I = QualifierUnion.begin(), 1703 E = QualifierUnion.end(); 1704 I != E; (void)++I, ++MOC) { 1705 if (MOC->first && MOC->second) { 1706 // Rebuild member pointer type 1707 Composite1 = Context.getMemberPointerType(Composite1.getQualifiedType(*I), 1708 MOC->first); 1709 Composite2 = Context.getMemberPointerType(Composite2.getQualifiedType(*I), 1710 MOC->second); 1711 } else { 1712 // Rebuild pointer type 1713 Composite1 = Context.getPointerType(Composite1.getQualifiedType(*I)); 1714 Composite2 = Context.getPointerType(Composite2.getQualifiedType(*I)); 1715 } 1716 } 1717 1718 ImplicitConversionSequence E1ToC1 = 1719 TryImplicitConversion(E1, Composite1, 1720 /*SuppressUserConversions=*/false, 1721 /*AllowExplicit=*/false, 1722 /*ForceRValue=*/false, 1723 /*InOverloadResolution=*/false); 1724 ImplicitConversionSequence E2ToC1 = 1725 TryImplicitConversion(E2, Composite1, 1726 /*SuppressUserConversions=*/false, 1727 /*AllowExplicit=*/false, 1728 /*ForceRValue=*/false, 1729 /*InOverloadResolution=*/false); 1730 1731 ImplicitConversionSequence E1ToC2, E2ToC2; 1732 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion; 1733 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion; 1734 if (Context.getCanonicalType(Composite1) != 1735 Context.getCanonicalType(Composite2)) { 1736 E1ToC2 = TryImplicitConversion(E1, Composite2, 1737 /*SuppressUserConversions=*/false, 1738 /*AllowExplicit=*/false, 1739 /*ForceRValue=*/false, 1740 /*InOverloadResolution=*/false); 1741 E2ToC2 = TryImplicitConversion(E2, Composite2, 1742 /*SuppressUserConversions=*/false, 1743 /*AllowExplicit=*/false, 1744 /*ForceRValue=*/false, 1745 /*InOverloadResolution=*/false); 1746 } 1747 1748 bool ToC1Viable = E1ToC1.ConversionKind != 1749 ImplicitConversionSequence::BadConversion 1750 && E2ToC1.ConversionKind != 1751 ImplicitConversionSequence::BadConversion; 1752 bool ToC2Viable = E1ToC2.ConversionKind != 1753 ImplicitConversionSequence::BadConversion 1754 && E2ToC2.ConversionKind != 1755 ImplicitConversionSequence::BadConversion; 1756 if (ToC1Viable && !ToC2Viable) { 1757 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") && 1758 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting")) 1759 return Composite1; 1760 } 1761 if (ToC2Viable && !ToC1Viable) { 1762 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") && 1763 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting")) 1764 return Composite2; 1765 } 1766 return QualType(); 1767} 1768 1769Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) { 1770 if (!Context.getLangOptions().CPlusPlus) 1771 return Owned(E); 1772 1773 const RecordType *RT = E->getType()->getAs<RecordType>(); 1774 if (!RT) 1775 return Owned(E); 1776 1777 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 1778 if (RD->hasTrivialDestructor()) 1779 return Owned(E); 1780 1781 if (CallExpr *CE = dyn_cast<CallExpr>(E)) { 1782 QualType Ty = CE->getCallee()->getType(); 1783 if (const PointerType *PT = Ty->getAs<PointerType>()) 1784 Ty = PT->getPointeeType(); 1785 1786 const FunctionType *FTy = Ty->getAsFunctionType(); 1787 if (FTy->getResultType()->isReferenceType()) 1788 return Owned(E); 1789 } 1790 CXXTemporary *Temp = CXXTemporary::Create(Context, 1791 RD->getDestructor(Context)); 1792 ExprTemporaries.push_back(Temp); 1793 if (CXXDestructorDecl *Destructor = 1794 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context))) 1795 MarkDeclarationReferenced(E->getExprLoc(), Destructor); 1796 // FIXME: Add the temporary to the temporaries vector. 1797 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E)); 1798} 1799 1800Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr, 1801 bool ShouldDestroyTemps) { 1802 assert(SubExpr && "sub expression can't be null!"); 1803 1804 if (ExprTemporaries.empty()) 1805 return SubExpr; 1806 1807 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr, 1808 &ExprTemporaries[0], 1809 ExprTemporaries.size(), 1810 ShouldDestroyTemps); 1811 ExprTemporaries.clear(); 1812 1813 return E; 1814} 1815 1816Sema::OwningExprResult 1817Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc, 1818 tok::TokenKind OpKind, TypeTy *&ObjectType) { 1819 // Since this might be a postfix expression, get rid of ParenListExprs. 1820 Base = MaybeConvertParenListExprToParenExpr(S, move(Base)); 1821 1822 Expr *BaseExpr = (Expr*)Base.get(); 1823 assert(BaseExpr && "no record expansion"); 1824 1825 QualType BaseType = BaseExpr->getType(); 1826 if (BaseType->isDependentType()) { 1827 // FIXME: member of the current instantiation 1828 ObjectType = BaseType.getAsOpaquePtr(); 1829 return move(Base); 1830 } 1831 1832 // C++ [over.match.oper]p8: 1833 // [...] When operator->returns, the operator-> is applied to the value 1834 // returned, with the original second operand. 1835 if (OpKind == tok::arrow) { 1836 while (BaseType->isRecordType()) { 1837 Base = BuildOverloadedArrowExpr(S, move(Base), BaseExpr->getExprLoc()); 1838 BaseExpr = (Expr*)Base.get(); 1839 if (BaseExpr == NULL) 1840 return ExprError(); 1841 BaseType = BaseExpr->getType(); 1842 } 1843 } 1844 1845 if (BaseType->isPointerType()) 1846 BaseType = BaseType->getPointeeType(); 1847 1848 // We could end up with various non-record types here, such as extended 1849 // vector types or Objective-C interfaces. Just return early and let 1850 // ActOnMemberReferenceExpr do the work. 1851 if (!BaseType->isRecordType()) { 1852 // C++ [basic.lookup.classref]p2: 1853 // [...] If the type of the object expression is of pointer to scalar 1854 // type, the unqualified-id is looked up in the context of the complete 1855 // postfix-expression. 1856 ObjectType = 0; 1857 return move(Base); 1858 } 1859 1860 // C++ [basic.lookup.classref]p2: 1861 // If the id-expression in a class member access (5.2.5) is an 1862 // unqualified-id, and the type of the object expres- sion is of a class 1863 // type C (or of pointer to a class type C), the unqualified-id is looked 1864 // up in the scope of class C. [...] 1865 ObjectType = BaseType.getAsOpaquePtr(); 1866 return move(Base); 1867} 1868 1869Sema::OwningExprResult 1870Sema::ActOnDestructorReferenceExpr(Scope *S, ExprArg Base, 1871 SourceLocation OpLoc, 1872 tok::TokenKind OpKind, 1873 SourceLocation ClassNameLoc, 1874 IdentifierInfo *ClassName, 1875 const CXXScopeSpec &SS, 1876 bool HasTrailingLParen) { 1877 if (SS.isInvalid()) 1878 return ExprError(); 1879 1880 QualType BaseType; 1881 if (isUnknownSpecialization(SS)) 1882 BaseType = Context.getTypenameType((NestedNameSpecifier *)SS.getScopeRep(), 1883 ClassName); 1884 else { 1885 TypeTy *BaseTy = getTypeName(*ClassName, ClassNameLoc, S, &SS); 1886 if (!BaseTy) { 1887 Diag(ClassNameLoc, diag::err_ident_in_pseudo_dtor_not_a_type) 1888 << ClassName; 1889 return ExprError(); 1890 } 1891 1892 BaseType = GetTypeFromParser(BaseTy); 1893 } 1894 1895 CanQualType CanBaseType = Context.getCanonicalType(BaseType); 1896 DeclarationName DtorName = 1897 Context.DeclarationNames.getCXXDestructorName(CanBaseType); 1898 1899 OwningExprResult Result 1900 = BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc, 1901 DtorName, DeclPtrTy(), &SS); 1902 if (Result.isInvalid() || HasTrailingLParen) 1903 return move(Result); 1904 1905 // The only way a reference to a destructor can be used is to 1906 // immediately call them. Since the next token is not a '(', produce a 1907 // diagnostic and build the call now. 1908 Expr *E = (Expr *)Result.get(); 1909 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(E->getLocEnd()); 1910 Diag(E->getLocStart(), diag::err_dtor_expr_without_call) 1911 << isa<CXXPseudoDestructorExpr>(E) 1912 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()"); 1913 1914 return ActOnCallExpr(0, move(Result), ExpectedLParenLoc, 1915 MultiExprArg(*this, 0, 0), 0, ExpectedLParenLoc); 1916} 1917 1918Sema::OwningExprResult 1919Sema::ActOnOverloadedOperatorReferenceExpr(Scope *S, ExprArg Base, 1920 SourceLocation OpLoc, 1921 tok::TokenKind OpKind, 1922 SourceLocation ClassNameLoc, 1923 OverloadedOperatorKind OverOpKind, 1924 const CXXScopeSpec *SS) { 1925 if (SS && SS->isInvalid()) 1926 return ExprError(); 1927 1928 DeclarationName Name = 1929 Context.DeclarationNames.getCXXOperatorName(OverOpKind); 1930 1931 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc, 1932 Name, DeclPtrTy(), SS); 1933} 1934 1935Sema::OwningExprResult 1936Sema::ActOnConversionOperatorReferenceExpr(Scope *S, ExprArg Base, 1937 SourceLocation OpLoc, 1938 tok::TokenKind OpKind, 1939 SourceLocation ClassNameLoc, 1940 TypeTy *Ty, 1941 const CXXScopeSpec *SS) { 1942 if (SS && SS->isInvalid()) 1943 return ExprError(); 1944 1945 //FIXME: Preserve type source info. 1946 QualType ConvType = GetTypeFromParser(Ty); 1947 CanQualType ConvTypeCanon = Context.getCanonicalType(ConvType); 1948 DeclarationName ConvName = 1949 Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon); 1950 1951 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc, 1952 ConvName, DeclPtrTy(), SS); 1953} 1954 1955Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc, 1956 QualType Ty, 1957 CastExpr::CastKind Kind, 1958 CXXMethodDecl *Method, 1959 ExprArg Arg) { 1960 Expr *From = Arg.takeAs<Expr>(); 1961 1962 switch (Kind) { 1963 default: assert(0 && "Unhandled cast kind!"); 1964 case CastExpr::CK_ConstructorConversion: { 1965 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this); 1966 1967 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method), 1968 MultiExprArg(*this, (void **)&From, 1), 1969 CastLoc, ConstructorArgs)) 1970 return ExprError(); 1971 1972 return BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method), 1973 move_arg(ConstructorArgs)); 1974 } 1975 1976 case CastExpr::CK_UserDefinedConversion: { 1977 // Create an implicit member expr to refer to the conversion operator. 1978 MemberExpr *ME = 1979 new (Context) MemberExpr(From, From->getType()->isPointerType(), Method, 1980 SourceLocation(), Method->getType()); 1981 1982 1983 // And an implicit call expr that calls it. 1984 QualType ResultType = Method->getResultType().getNonReferenceType(); 1985 CXXMemberCallExpr *CE = 1986 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, 1987 ResultType, 1988 SourceLocation()); 1989 1990 return Owned(CE); 1991 } 1992 1993 } 1994} 1995 1996Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) { 1997 Expr *FullExpr = Arg.takeAs<Expr>(); 1998 if (FullExpr) 1999 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr, 2000 /*ShouldDestroyTemps=*/true); 2001 2002 2003 return Owned(FullExpr); 2004} 2005