SemaExprCXX.cpp revision 193576
1193326Sed//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===// 2193326Sed// 3193326Sed// The LLVM Compiler Infrastructure 4193326Sed// 5193326Sed// This file is distributed under the University of Illinois Open Source 6193326Sed// License. See LICENSE.TXT for details. 7193326Sed// 8193326Sed//===----------------------------------------------------------------------===// 9193326Sed// 10193326Sed// This file implements semantic analysis for C++ expressions. 11193326Sed// 12193326Sed//===----------------------------------------------------------------------===// 13193326Sed 14193326Sed#include "SemaInherit.h" 15193326Sed#include "Sema.h" 16193326Sed#include "clang/AST/ExprCXX.h" 17193326Sed#include "clang/AST/ASTContext.h" 18193326Sed#include "clang/Parse/DeclSpec.h" 19193326Sed#include "clang/Lex/Preprocessor.h" 20193326Sed#include "clang/Basic/TargetInfo.h" 21193326Sed#include "llvm/ADT/STLExtras.h" 22193326Sedusing namespace clang; 23193326Sed 24193326Sed/// ActOnCXXConversionFunctionExpr - Parse a C++ conversion function 25193326Sed/// name (e.g., operator void const *) as an expression. This is 26193326Sed/// very similar to ActOnIdentifierExpr, except that instead of 27193326Sed/// providing an identifier the parser provides the type of the 28193326Sed/// conversion function. 29193326SedSema::OwningExprResult 30193326SedSema::ActOnCXXConversionFunctionExpr(Scope *S, SourceLocation OperatorLoc, 31193326Sed TypeTy *Ty, bool HasTrailingLParen, 32193326Sed const CXXScopeSpec &SS, 33193326Sed bool isAddressOfOperand) { 34193326Sed QualType ConvType = QualType::getFromOpaquePtr(Ty); 35193326Sed QualType ConvTypeCanon = Context.getCanonicalType(ConvType); 36193326Sed DeclarationName ConvName 37193326Sed = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon); 38193326Sed return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen, 39193326Sed &SS, isAddressOfOperand); 40193326Sed} 41193326Sed 42193326Sed/// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator 43193326Sed/// name (e.g., @c operator+ ) as an expression. This is very 44193326Sed/// similar to ActOnIdentifierExpr, except that instead of providing 45193326Sed/// an identifier the parser provides the kind of overloaded 46193326Sed/// operator that was parsed. 47193326SedSema::OwningExprResult 48193326SedSema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc, 49193326Sed OverloadedOperatorKind Op, 50193326Sed bool HasTrailingLParen, 51193326Sed const CXXScopeSpec &SS, 52193326Sed bool isAddressOfOperand) { 53193326Sed DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op); 54193326Sed return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS, 55193326Sed isAddressOfOperand); 56193326Sed} 57193326Sed 58193326Sed/// ActOnCXXTypeidOfType - Parse typeid( type-id ). 59193326SedAction::OwningExprResult 60193326SedSema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, 61193326Sed bool isType, void *TyOrExpr, SourceLocation RParenLoc) { 62193326Sed NamespaceDecl *StdNs = GetStdNamespace(); 63193326Sed if (!StdNs) 64193326Sed return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); 65193326Sed 66193326Sed IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info"); 67193326Sed Decl *TypeInfoDecl = LookupQualifiedName(StdNs, TypeInfoII, LookupTagName); 68193326Sed RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl); 69193326Sed if (!TypeInfoRecordDecl) 70193326Sed return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); 71193326Sed 72193326Sed QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl); 73193326Sed 74193326Sed return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr, 75193326Sed TypeInfoType.withConst(), 76193326Sed SourceRange(OpLoc, RParenLoc))); 77193326Sed} 78193326Sed 79193326Sed/// ActOnCXXBoolLiteral - Parse {true,false} literals. 80193326SedAction::OwningExprResult 81193326SedSema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 82193326Sed assert((Kind == tok::kw_true || Kind == tok::kw_false) && 83193326Sed "Unknown C++ Boolean value!"); 84193326Sed return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true, 85193326Sed Context.BoolTy, OpLoc)); 86193326Sed} 87193326Sed 88193326Sed/// ActOnCXXNullPtrLiteral - Parse 'nullptr'. 89193326SedAction::OwningExprResult 90193326SedSema::ActOnCXXNullPtrLiteral(SourceLocation Loc) { 91193326Sed return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc)); 92193326Sed} 93193326Sed 94193326Sed/// ActOnCXXThrow - Parse throw expressions. 95193326SedAction::OwningExprResult 96193326SedSema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) { 97193326Sed Expr *Ex = E.takeAs<Expr>(); 98193326Sed if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex)) 99193326Sed return ExprError(); 100193326Sed return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc)); 101193326Sed} 102193326Sed 103193326Sed/// CheckCXXThrowOperand - Validate the operand of a throw. 104193326Sedbool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) { 105193326Sed // C++ [except.throw]p3: 106193326Sed // [...] adjusting the type from "array of T" or "function returning T" 107193326Sed // to "pointer to T" or "pointer to function returning T", [...] 108193326Sed DefaultFunctionArrayConversion(E); 109193326Sed 110193326Sed // If the type of the exception would be an incomplete type or a pointer 111193326Sed // to an incomplete type other than (cv) void the program is ill-formed. 112193326Sed QualType Ty = E->getType(); 113193326Sed int isPointer = 0; 114193326Sed if (const PointerType* Ptr = Ty->getAsPointerType()) { 115193326Sed Ty = Ptr->getPointeeType(); 116193326Sed isPointer = 1; 117193326Sed } 118193326Sed if (!isPointer || !Ty->isVoidType()) { 119193326Sed if (RequireCompleteType(ThrowLoc, Ty, 120193326Sed isPointer ? diag::err_throw_incomplete_ptr 121193326Sed : diag::err_throw_incomplete, 122193326Sed E->getSourceRange(), SourceRange(), QualType())) 123193326Sed return true; 124193326Sed } 125193326Sed 126193326Sed // FIXME: Construct a temporary here. 127193326Sed return false; 128193326Sed} 129193326Sed 130193326SedAction::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) { 131193326Sed /// C++ 9.3.2: In the body of a non-static member function, the keyword this 132193326Sed /// is a non-lvalue expression whose value is the address of the object for 133193326Sed /// which the function is called. 134193326Sed 135193326Sed if (!isa<FunctionDecl>(CurContext)) 136193326Sed return ExprError(Diag(ThisLoc, diag::err_invalid_this_use)); 137193326Sed 138193326Sed if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) 139193326Sed if (MD->isInstance()) 140193326Sed return Owned(new (Context) CXXThisExpr(ThisLoc, 141193326Sed MD->getThisType(Context))); 142193326Sed 143193326Sed return ExprError(Diag(ThisLoc, diag::err_invalid_this_use)); 144193326Sed} 145193326Sed 146193326Sed/// ActOnCXXTypeConstructExpr - Parse construction of a specified type. 147193326Sed/// Can be interpreted either as function-style casting ("int(x)") 148193326Sed/// or class type construction ("ClassType(x,y,z)") 149193326Sed/// or creation of a value-initialized type ("int()"). 150193326SedAction::OwningExprResult 151193326SedSema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep, 152193326Sed SourceLocation LParenLoc, 153193326Sed MultiExprArg exprs, 154193326Sed SourceLocation *CommaLocs, 155193326Sed SourceLocation RParenLoc) { 156193326Sed assert(TypeRep && "Missing type!"); 157193326Sed QualType Ty = QualType::getFromOpaquePtr(TypeRep); 158193326Sed unsigned NumExprs = exprs.size(); 159193326Sed Expr **Exprs = (Expr**)exprs.get(); 160193326Sed SourceLocation TyBeginLoc = TypeRange.getBegin(); 161193326Sed SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc); 162193326Sed 163193326Sed if (Ty->isDependentType() || 164193326Sed CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) { 165193326Sed exprs.release(); 166193326Sed 167193326Sed return Owned(CXXUnresolvedConstructExpr::Create(Context, 168193326Sed TypeRange.getBegin(), Ty, 169193326Sed LParenLoc, 170193326Sed Exprs, NumExprs, 171193326Sed RParenLoc)); 172193326Sed } 173193326Sed 174193326Sed 175193326Sed // C++ [expr.type.conv]p1: 176193326Sed // If the expression list is a single expression, the type conversion 177193326Sed // expression is equivalent (in definedness, and if defined in meaning) to the 178193326Sed // corresponding cast expression. 179193326Sed // 180193326Sed if (NumExprs == 1) { 181193326Sed if (CheckCastTypes(TypeRange, Ty, Exprs[0])) 182193326Sed return ExprError(); 183193326Sed exprs.release(); 184193326Sed return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(), 185193326Sed Ty, TyBeginLoc, Exprs[0], 186193326Sed RParenLoc)); 187193326Sed } 188193326Sed 189193326Sed if (const RecordType *RT = Ty->getAsRecordType()) { 190193326Sed CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl()); 191193326Sed 192193326Sed // FIXME: We should always create a CXXTemporaryObjectExpr here unless 193193326Sed // both the ctor and dtor are trivial. 194193326Sed if (NumExprs > 1 || Record->hasUserDeclaredConstructor()) { 195193326Sed CXXConstructorDecl *Constructor 196193326Sed = PerformInitializationByConstructor(Ty, Exprs, NumExprs, 197193326Sed TypeRange.getBegin(), 198193326Sed SourceRange(TypeRange.getBegin(), 199193326Sed RParenLoc), 200193326Sed DeclarationName(), 201193326Sed IK_Direct); 202193326Sed 203193326Sed if (!Constructor) 204193326Sed return ExprError(); 205193326Sed 206193326Sed exprs.release(); 207193326Sed Expr *E = new (Context) CXXTemporaryObjectExpr(Context, Constructor, 208193326Sed Ty, TyBeginLoc, Exprs, 209193326Sed NumExprs, RParenLoc); 210193326Sed return MaybeBindToTemporary(E); 211193326Sed } 212193326Sed 213193326Sed // Fall through to value-initialize an object of class type that 214193326Sed // doesn't have a user-declared default constructor. 215193326Sed } 216193326Sed 217193326Sed // C++ [expr.type.conv]p1: 218193326Sed // If the expression list specifies more than a single value, the type shall 219193326Sed // be a class with a suitably declared constructor. 220193326Sed // 221193326Sed if (NumExprs > 1) 222193326Sed return ExprError(Diag(CommaLocs[0], 223193326Sed diag::err_builtin_func_cast_more_than_one_arg) 224193326Sed << FullRange); 225193326Sed 226193326Sed assert(NumExprs == 0 && "Expected 0 expressions"); 227193326Sed 228193326Sed // C++ [expr.type.conv]p2: 229193326Sed // The expression T(), where T is a simple-type-specifier for a non-array 230193326Sed // complete object type or the (possibly cv-qualified) void type, creates an 231193326Sed // rvalue of the specified type, which is value-initialized. 232193326Sed // 233193326Sed if (Ty->isArrayType()) 234193326Sed return ExprError(Diag(TyBeginLoc, 235193326Sed diag::err_value_init_for_array_type) << FullRange); 236193326Sed if (!Ty->isDependentType() && !Ty->isVoidType() && 237193326Sed RequireCompleteType(TyBeginLoc, Ty, 238193326Sed diag::err_invalid_incomplete_type_use, FullRange)) 239193326Sed return ExprError(); 240193326Sed 241193326Sed if (RequireNonAbstractType(TyBeginLoc, Ty, 242193326Sed diag::err_allocation_of_abstract_type)) 243193326Sed return ExprError(); 244193326Sed 245193326Sed exprs.release(); 246193326Sed return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc)); 247193326Sed} 248193326Sed 249193326Sed 250193326Sed/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.: 251193326Sed/// @code new (memory) int[size][4] @endcode 252193326Sed/// or 253193326Sed/// @code ::new Foo(23, "hello") @endcode 254193326Sed/// For the interpretation of this heap of arguments, consult the base version. 255193326SedAction::OwningExprResult 256193326SedSema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 257193326Sed SourceLocation PlacementLParen, MultiExprArg PlacementArgs, 258193326Sed SourceLocation PlacementRParen, bool ParenTypeId, 259193326Sed Declarator &D, SourceLocation ConstructorLParen, 260193326Sed MultiExprArg ConstructorArgs, 261193326Sed SourceLocation ConstructorRParen) 262193326Sed{ 263193326Sed Expr *ArraySize = 0; 264193326Sed unsigned Skip = 0; 265193326Sed // If the specified type is an array, unwrap it and save the expression. 266193326Sed if (D.getNumTypeObjects() > 0 && 267193326Sed D.getTypeObject(0).Kind == DeclaratorChunk::Array) { 268193326Sed DeclaratorChunk &Chunk = D.getTypeObject(0); 269193326Sed if (Chunk.Arr.hasStatic) 270193326Sed return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new) 271193326Sed << D.getSourceRange()); 272193326Sed if (!Chunk.Arr.NumElts) 273193326Sed return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size) 274193326Sed << D.getSourceRange()); 275193326Sed ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts); 276193326Sed Skip = 1; 277193326Sed } 278193326Sed 279193326Sed QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, Skip); 280193326Sed if (D.isInvalidType()) 281193326Sed return ExprError(); 282193326Sed 283193326Sed // Every dimension shall be of constant size. 284193326Sed unsigned i = 1; 285193326Sed QualType ElementType = AllocType; 286193326Sed while (const ArrayType *Array = Context.getAsArrayType(ElementType)) { 287193326Sed if (!Array->isConstantArrayType()) { 288193326Sed Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst) 289193326Sed << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange(); 290193326Sed return ExprError(); 291193326Sed } 292193326Sed ElementType = Array->getElementType(); 293193326Sed ++i; 294193326Sed } 295193326Sed 296193326Sed return BuildCXXNew(StartLoc, UseGlobal, 297193326Sed PlacementLParen, 298193326Sed move(PlacementArgs), 299193326Sed PlacementRParen, 300193326Sed ParenTypeId, 301193326Sed AllocType, 302193326Sed D.getSourceRange().getBegin(), 303193326Sed D.getSourceRange(), 304193326Sed Owned(ArraySize), 305193326Sed ConstructorLParen, 306193326Sed move(ConstructorArgs), 307193326Sed ConstructorRParen); 308193326Sed} 309193326Sed 310193326SedSema::OwningExprResult 311193326SedSema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal, 312193326Sed SourceLocation PlacementLParen, 313193326Sed MultiExprArg PlacementArgs, 314193326Sed SourceLocation PlacementRParen, 315193326Sed bool ParenTypeId, 316193326Sed QualType AllocType, 317193326Sed SourceLocation TypeLoc, 318193326Sed SourceRange TypeRange, 319193326Sed ExprArg ArraySizeE, 320193326Sed SourceLocation ConstructorLParen, 321193326Sed MultiExprArg ConstructorArgs, 322193326Sed SourceLocation ConstructorRParen) { 323193326Sed if (CheckAllocatedType(AllocType, TypeLoc, TypeRange)) 324193326Sed return ExprError(); 325193326Sed 326193326Sed QualType ResultType = Context.getPointerType(AllocType); 327193326Sed 328193326Sed // That every array dimension except the first is constant was already 329193326Sed // checked by the type check above. 330193326Sed 331193326Sed // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral 332193326Sed // or enumeration type with a non-negative value." 333193326Sed Expr *ArraySize = (Expr *)ArraySizeE.get(); 334193326Sed if (ArraySize && !ArraySize->isTypeDependent()) { 335193326Sed QualType SizeType = ArraySize->getType(); 336193326Sed if (!SizeType->isIntegralType() && !SizeType->isEnumeralType()) 337193326Sed return ExprError(Diag(ArraySize->getSourceRange().getBegin(), 338193326Sed diag::err_array_size_not_integral) 339193326Sed << SizeType << ArraySize->getSourceRange()); 340193326Sed // Let's see if this is a constant < 0. If so, we reject it out of hand. 341193326Sed // We don't care about special rules, so we tell the machinery it's not 342193326Sed // evaluated - it gives us a result in more cases. 343193326Sed if (!ArraySize->isValueDependent()) { 344193326Sed llvm::APSInt Value; 345193326Sed if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) { 346193326Sed if (Value < llvm::APSInt( 347193326Sed llvm::APInt::getNullValue(Value.getBitWidth()), false)) 348193326Sed return ExprError(Diag(ArraySize->getSourceRange().getBegin(), 349193326Sed diag::err_typecheck_negative_array_size) 350193326Sed << ArraySize->getSourceRange()); 351193326Sed } 352193326Sed } 353193326Sed } 354193326Sed 355193326Sed FunctionDecl *OperatorNew = 0; 356193326Sed FunctionDecl *OperatorDelete = 0; 357193326Sed Expr **PlaceArgs = (Expr**)PlacementArgs.get(); 358193326Sed unsigned NumPlaceArgs = PlacementArgs.size(); 359193326Sed if (!AllocType->isDependentType() && 360193326Sed !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) && 361193326Sed FindAllocationFunctions(StartLoc, 362193326Sed SourceRange(PlacementLParen, PlacementRParen), 363193326Sed UseGlobal, AllocType, ArraySize, PlaceArgs, 364193326Sed NumPlaceArgs, OperatorNew, OperatorDelete)) 365193326Sed return ExprError(); 366193326Sed 367193326Sed bool Init = ConstructorLParen.isValid(); 368193326Sed // --- Choosing a constructor --- 369193326Sed // C++ 5.3.4p15 370193326Sed // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid) 371193326Sed // the object is not initialized. If the object, or any part of it, is 372193326Sed // const-qualified, it's an error. 373193326Sed // 2) If T is a POD and there's an empty initializer, the object is value- 374193326Sed // initialized. 375193326Sed // 3) If T is a POD and there's one initializer argument, the object is copy- 376193326Sed // constructed. 377193326Sed // 4) If T is a POD and there's more initializer arguments, it's an error. 378193326Sed // 5) If T is not a POD, the initializer arguments are used as constructor 379193326Sed // arguments. 380193326Sed // 381193326Sed // Or by the C++0x formulation: 382193326Sed // 1) If there's no initializer, the object is default-initialized according 383193326Sed // to C++0x rules. 384193326Sed // 2) Otherwise, the object is direct-initialized. 385193326Sed CXXConstructorDecl *Constructor = 0; 386193326Sed Expr **ConsArgs = (Expr**)ConstructorArgs.get(); 387193326Sed const RecordType *RT; 388193326Sed unsigned NumConsArgs = ConstructorArgs.size(); 389193326Sed if (AllocType->isDependentType()) { 390193326Sed // Skip all the checks. 391193326Sed } 392193326Sed else if ((RT = AllocType->getAsRecordType()) && 393193326Sed !AllocType->isAggregateType()) { 394193326Sed Constructor = PerformInitializationByConstructor( 395193326Sed AllocType, ConsArgs, NumConsArgs, 396193326Sed TypeLoc, 397193326Sed SourceRange(TypeLoc, ConstructorRParen), 398193326Sed RT->getDecl()->getDeclName(), 399193326Sed NumConsArgs != 0 ? IK_Direct : IK_Default); 400193326Sed if (!Constructor) 401193326Sed return ExprError(); 402193326Sed } else { 403193326Sed if (!Init) { 404193326Sed // FIXME: Check that no subpart is const. 405193326Sed if (AllocType.isConstQualified()) 406193326Sed return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const) 407193326Sed << TypeRange); 408193326Sed } else if (NumConsArgs == 0) { 409193326Sed // Object is value-initialized. Do nothing. 410193326Sed } else if (NumConsArgs == 1) { 411193326Sed // Object is direct-initialized. 412193326Sed // FIXME: What DeclarationName do we pass in here? 413193326Sed if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc, 414193326Sed DeclarationName() /*AllocType.getAsString()*/, 415193326Sed /*DirectInit=*/true)) 416193326Sed return ExprError(); 417193326Sed } else { 418193326Sed return ExprError(Diag(StartLoc, 419193326Sed diag::err_builtin_direct_init_more_than_one_arg) 420193326Sed << SourceRange(ConstructorLParen, ConstructorRParen)); 421193326Sed } 422193326Sed } 423193326Sed 424193326Sed // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16) 425193326Sed 426193326Sed PlacementArgs.release(); 427193326Sed ConstructorArgs.release(); 428193326Sed ArraySizeE.release(); 429193326Sed return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs, 430193326Sed NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init, 431193326Sed ConsArgs, NumConsArgs, OperatorDelete, ResultType, 432193326Sed StartLoc, Init ? ConstructorRParen : SourceLocation())); 433193326Sed} 434193326Sed 435193326Sed/// CheckAllocatedType - Checks that a type is suitable as the allocated type 436193326Sed/// in a new-expression. 437193326Sed/// dimension off and stores the size expression in ArraySize. 438193326Sedbool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc, 439193326Sed SourceRange R) 440193326Sed{ 441193326Sed // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an 442193326Sed // abstract class type or array thereof. 443193326Sed if (AllocType->isFunctionType()) 444193326Sed return Diag(Loc, diag::err_bad_new_type) 445193326Sed << AllocType << 0 << R; 446193326Sed else if (AllocType->isReferenceType()) 447193326Sed return Diag(Loc, diag::err_bad_new_type) 448193326Sed << AllocType << 1 << R; 449193326Sed else if (!AllocType->isDependentType() && 450193326Sed RequireCompleteType(Loc, AllocType, 451193326Sed diag::err_new_incomplete_type, 452193326Sed R)) 453193326Sed return true; 454193326Sed else if (RequireNonAbstractType(Loc, AllocType, 455193326Sed diag::err_allocation_of_abstract_type)) 456193326Sed return true; 457193326Sed 458193326Sed return false; 459193326Sed} 460193326Sed 461193326Sed/// FindAllocationFunctions - Finds the overloads of operator new and delete 462193326Sed/// that are appropriate for the allocation. 463193326Sedbool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 464193326Sed bool UseGlobal, QualType AllocType, 465193326Sed bool IsArray, Expr **PlaceArgs, 466193326Sed unsigned NumPlaceArgs, 467193326Sed FunctionDecl *&OperatorNew, 468193326Sed FunctionDecl *&OperatorDelete) 469193326Sed{ 470193326Sed // --- Choosing an allocation function --- 471193326Sed // C++ 5.3.4p8 - 14 & 18 472193326Sed // 1) If UseGlobal is true, only look in the global scope. Else, also look 473193326Sed // in the scope of the allocated class. 474193326Sed // 2) If an array size is given, look for operator new[], else look for 475193326Sed // operator new. 476193326Sed // 3) The first argument is always size_t. Append the arguments from the 477193326Sed // placement form. 478193326Sed // FIXME: Also find the appropriate delete operator. 479193326Sed 480193326Sed llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs); 481193326Sed // We don't care about the actual value of this argument. 482193326Sed // FIXME: Should the Sema create the expression and embed it in the syntax 483193326Sed // tree? Or should the consumer just recalculate the value? 484193326Sed AllocArgs[0] = new (Context) IntegerLiteral(llvm::APInt::getNullValue( 485193326Sed Context.Target.getPointerWidth(0)), 486193326Sed Context.getSizeType(), 487193326Sed SourceLocation()); 488193326Sed std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1); 489193326Sed 490193326Sed DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName( 491193326Sed IsArray ? OO_Array_New : OO_New); 492193326Sed if (AllocType->isRecordType() && !UseGlobal) { 493193326Sed CXXRecordDecl *Record 494193326Sed = cast<CXXRecordDecl>(AllocType->getAsRecordType()->getDecl()); 495193326Sed // FIXME: We fail to find inherited overloads. 496193326Sed if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0], 497193326Sed AllocArgs.size(), Record, /*AllowMissing=*/true, 498193326Sed OperatorNew)) 499193326Sed return true; 500193326Sed } 501193326Sed if (!OperatorNew) { 502193326Sed // Didn't find a member overload. Look for a global one. 503193326Sed DeclareGlobalNewDelete(); 504193326Sed DeclContext *TUDecl = Context.getTranslationUnitDecl(); 505193326Sed if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0], 506193326Sed AllocArgs.size(), TUDecl, /*AllowMissing=*/false, 507193326Sed OperatorNew)) 508193326Sed return true; 509193326Sed } 510193326Sed 511193326Sed // FindAllocationOverload can change the passed in arguments, so we need to 512193326Sed // copy them back. 513193326Sed if (NumPlaceArgs > 0) 514193326Sed std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs); 515193326Sed 516193326Sed // FIXME: This is leaked on error. But so much is currently in Sema that it's 517193326Sed // easier to clean it in one go. 518193326Sed AllocArgs[0]->Destroy(Context); 519193326Sed return false; 520193326Sed} 521193326Sed 522193326Sed/// FindAllocationOverload - Find an fitting overload for the allocation 523193326Sed/// function in the specified scope. 524193326Sedbool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range, 525193326Sed DeclarationName Name, Expr** Args, 526193326Sed unsigned NumArgs, DeclContext *Ctx, 527193326Sed bool AllowMissing, FunctionDecl *&Operator) 528193326Sed{ 529193326Sed DeclContext::lookup_iterator Alloc, AllocEnd; 530193326Sed llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Context, Name); 531193326Sed if (Alloc == AllocEnd) { 532193326Sed if (AllowMissing) 533193326Sed return false; 534193326Sed return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) 535193326Sed << Name << Range; 536193326Sed } 537193326Sed 538193326Sed OverloadCandidateSet Candidates; 539193326Sed for (; Alloc != AllocEnd; ++Alloc) { 540193326Sed // Even member operator new/delete are implicitly treated as 541193326Sed // static, so don't use AddMemberCandidate. 542193326Sed if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc)) 543193326Sed AddOverloadCandidate(Fn, Args, NumArgs, Candidates, 544193326Sed /*SuppressUserConversions=*/false); 545193326Sed } 546193326Sed 547193326Sed // Do the resolution. 548193326Sed OverloadCandidateSet::iterator Best; 549193326Sed switch(BestViableFunction(Candidates, Best)) { 550193326Sed case OR_Success: { 551193326Sed // Got one! 552193326Sed FunctionDecl *FnDecl = Best->Function; 553193326Sed // The first argument is size_t, and the first parameter must be size_t, 554193326Sed // too. This is checked on declaration and can be assumed. (It can't be 555193326Sed // asserted on, though, since invalid decls are left in there.) 556193326Sed for (unsigned i = 1; i < NumArgs; ++i) { 557193326Sed // FIXME: Passing word to diagnostic. 558193326Sed if (PerformCopyInitialization(Args[i], 559193326Sed FnDecl->getParamDecl(i)->getType(), 560193326Sed "passing")) 561193326Sed return true; 562193326Sed } 563193326Sed Operator = FnDecl; 564193326Sed return false; 565193326Sed } 566193326Sed 567193326Sed case OR_No_Viable_Function: 568193326Sed Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) 569193326Sed << Name << Range; 570193326Sed PrintOverloadCandidates(Candidates, /*OnlyViable=*/false); 571193326Sed return true; 572193326Sed 573193326Sed case OR_Ambiguous: 574193326Sed Diag(StartLoc, diag::err_ovl_ambiguous_call) 575193326Sed << Name << Range; 576193326Sed PrintOverloadCandidates(Candidates, /*OnlyViable=*/true); 577193326Sed return true; 578193326Sed 579193326Sed case OR_Deleted: 580193326Sed Diag(StartLoc, diag::err_ovl_deleted_call) 581193326Sed << Best->Function->isDeleted() 582193326Sed << Name << Range; 583193326Sed PrintOverloadCandidates(Candidates, /*OnlyViable=*/true); 584193326Sed return true; 585193326Sed } 586193326Sed assert(false && "Unreachable, bad result from BestViableFunction"); 587193326Sed return true; 588193326Sed} 589193326Sed 590193326Sed 591193326Sed/// DeclareGlobalNewDelete - Declare the global forms of operator new and 592193326Sed/// delete. These are: 593193326Sed/// @code 594193326Sed/// void* operator new(std::size_t) throw(std::bad_alloc); 595193326Sed/// void* operator new[](std::size_t) throw(std::bad_alloc); 596193326Sed/// void operator delete(void *) throw(); 597193326Sed/// void operator delete[](void *) throw(); 598193326Sed/// @endcode 599193326Sed/// Note that the placement and nothrow forms of new are *not* implicitly 600193326Sed/// declared. Their use requires including \<new\>. 601193326Sedvoid Sema::DeclareGlobalNewDelete() 602193326Sed{ 603193326Sed if (GlobalNewDeleteDeclared) 604193326Sed return; 605193326Sed GlobalNewDeleteDeclared = true; 606193326Sed 607193326Sed QualType VoidPtr = Context.getPointerType(Context.VoidTy); 608193326Sed QualType SizeT = Context.getSizeType(); 609193326Sed 610193326Sed // FIXME: Exception specifications are not added. 611193326Sed DeclareGlobalAllocationFunction( 612193326Sed Context.DeclarationNames.getCXXOperatorName(OO_New), 613193326Sed VoidPtr, SizeT); 614193326Sed DeclareGlobalAllocationFunction( 615193326Sed Context.DeclarationNames.getCXXOperatorName(OO_Array_New), 616193326Sed VoidPtr, SizeT); 617193326Sed DeclareGlobalAllocationFunction( 618193326Sed Context.DeclarationNames.getCXXOperatorName(OO_Delete), 619193326Sed Context.VoidTy, VoidPtr); 620193326Sed DeclareGlobalAllocationFunction( 621193326Sed Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete), 622193326Sed Context.VoidTy, VoidPtr); 623193326Sed} 624193326Sed 625193326Sed/// DeclareGlobalAllocationFunction - Declares a single implicit global 626193326Sed/// allocation function if it doesn't already exist. 627193326Sedvoid Sema::DeclareGlobalAllocationFunction(DeclarationName Name, 628193326Sed QualType Return, QualType Argument) 629193326Sed{ 630193326Sed DeclContext *GlobalCtx = Context.getTranslationUnitDecl(); 631193326Sed 632193326Sed // Check if this function is already declared. 633193326Sed { 634193326Sed DeclContext::lookup_iterator Alloc, AllocEnd; 635193326Sed for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Context, Name); 636193326Sed Alloc != AllocEnd; ++Alloc) { 637193326Sed // FIXME: Do we need to check for default arguments here? 638193326Sed FunctionDecl *Func = cast<FunctionDecl>(*Alloc); 639193326Sed if (Func->getNumParams() == 1 && 640193326Sed Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument) 641193326Sed return; 642193326Sed } 643193326Sed } 644193326Sed 645193326Sed QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0); 646193326Sed FunctionDecl *Alloc = 647193326Sed FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name, 648193326Sed FnType, FunctionDecl::None, false, true, 649193326Sed SourceLocation()); 650193326Sed Alloc->setImplicit(); 651193326Sed ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(), 652193326Sed 0, Argument, VarDecl::None, 0); 653193326Sed Alloc->setParams(Context, &Param, 1); 654193326Sed 655193326Sed // FIXME: Also add this declaration to the IdentifierResolver, but 656193326Sed // make sure it is at the end of the chain to coincide with the 657193326Sed // global scope. 658193326Sed ((DeclContext *)TUScope->getEntity())->addDecl(Context, Alloc); 659193326Sed} 660193326Sed 661193326Sed/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in: 662193326Sed/// @code ::delete ptr; @endcode 663193326Sed/// or 664193326Sed/// @code delete [] ptr; @endcode 665193326SedAction::OwningExprResult 666193326SedSema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, 667193326Sed bool ArrayForm, ExprArg Operand) 668193326Sed{ 669193326Sed // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type 670193326Sed // having a single conversion function to a pointer type. The result has 671193326Sed // type void." 672193326Sed // DR599 amends "pointer type" to "pointer to object type" in both cases. 673193326Sed 674193326Sed Expr *Ex = (Expr *)Operand.get(); 675193326Sed if (!Ex->isTypeDependent()) { 676193326Sed QualType Type = Ex->getType(); 677193326Sed 678193326Sed if (Type->isRecordType()) { 679193326Sed // FIXME: Find that one conversion function and amend the type. 680193326Sed } 681193326Sed 682193326Sed if (!Type->isPointerType()) 683193326Sed return ExprError(Diag(StartLoc, diag::err_delete_operand) 684193326Sed << Type << Ex->getSourceRange()); 685193326Sed 686193326Sed QualType Pointee = Type->getAsPointerType()->getPointeeType(); 687193326Sed if (Pointee->isFunctionType() || Pointee->isVoidType()) 688193326Sed return ExprError(Diag(StartLoc, diag::err_delete_operand) 689193326Sed << Type << Ex->getSourceRange()); 690193326Sed else if (!Pointee->isDependentType() && 691193326Sed RequireCompleteType(StartLoc, Pointee, 692193326Sed diag::warn_delete_incomplete, 693193326Sed Ex->getSourceRange())) 694193326Sed return ExprError(); 695193326Sed 696193326Sed // FIXME: Look up the correct operator delete overload and pass a pointer 697193326Sed // along. 698193326Sed // FIXME: Check access and ambiguity of operator delete and destructor. 699193326Sed } 700193326Sed 701193326Sed Operand.release(); 702193326Sed return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm, 703193326Sed 0, Ex, StartLoc)); 704193326Sed} 705193326Sed 706193326Sed 707193326Sed/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 708193326Sed/// C++ if/switch/while/for statement. 709193326Sed/// e.g: "if (int x = f()) {...}" 710193326SedAction::OwningExprResult 711193326SedSema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc, 712193326Sed Declarator &D, 713193326Sed SourceLocation EqualLoc, 714193326Sed ExprArg AssignExprVal) { 715193326Sed assert(AssignExprVal.get() && "Null assignment expression"); 716193326Sed 717193326Sed // C++ 6.4p2: 718193326Sed // The declarator shall not specify a function or an array. 719193326Sed // The type-specifier-seq shall not contain typedef and shall not declare a 720193326Sed // new class or enumeration. 721193326Sed 722193326Sed assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 723193326Sed "Parser allowed 'typedef' as storage class of condition decl."); 724193326Sed 725193326Sed QualType Ty = GetTypeForDeclarator(D, S); 726193326Sed 727193326Sed if (Ty->isFunctionType()) { // The declarator shall not specify a function... 728193326Sed // We exit without creating a CXXConditionDeclExpr because a FunctionDecl 729193326Sed // would be created and CXXConditionDeclExpr wants a VarDecl. 730193326Sed return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type) 731193326Sed << SourceRange(StartLoc, EqualLoc)); 732193326Sed } else if (Ty->isArrayType()) { // ...or an array. 733193326Sed Diag(StartLoc, diag::err_invalid_use_of_array_type) 734193326Sed << SourceRange(StartLoc, EqualLoc); 735193326Sed } else if (const RecordType *RT = Ty->getAsRecordType()) { 736193326Sed RecordDecl *RD = RT->getDecl(); 737193326Sed // The type-specifier-seq shall not declare a new class... 738193326Sed if (RD->isDefinition() && 739193326Sed (RD->getIdentifier() == 0 || S->isDeclScope(DeclPtrTy::make(RD)))) 740193326Sed Diag(RD->getLocation(), diag::err_type_defined_in_condition); 741193326Sed } else if (const EnumType *ET = Ty->getAsEnumType()) { 742193326Sed EnumDecl *ED = ET->getDecl(); 743193326Sed // ...or enumeration. 744193326Sed if (ED->isDefinition() && 745193326Sed (ED->getIdentifier() == 0 || S->isDeclScope(DeclPtrTy::make(ED)))) 746193326Sed Diag(ED->getLocation(), diag::err_type_defined_in_condition); 747193326Sed } 748193326Sed 749193326Sed DeclPtrTy Dcl = ActOnDeclarator(S, D, DeclPtrTy()); 750193326Sed if (!Dcl) 751193326Sed return ExprError(); 752193326Sed AddInitializerToDecl(Dcl, move(AssignExprVal), /*DirectInit=*/false); 753193326Sed 754193326Sed // Mark this variable as one that is declared within a conditional. 755193326Sed // We know that the decl had to be a VarDecl because that is the only type of 756193326Sed // decl that can be assigned and the grammar requires an '='. 757193326Sed VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>()); 758193326Sed VD->setDeclaredInCondition(true); 759193326Sed return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD)); 760193326Sed} 761193326Sed 762193326Sed/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid. 763193326Sedbool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) { 764193326Sed // C++ 6.4p4: 765193326Sed // The value of a condition that is an initialized declaration in a statement 766193326Sed // other than a switch statement is the value of the declared variable 767193326Sed // implicitly converted to type bool. If that conversion is ill-formed, the 768193326Sed // program is ill-formed. 769193326Sed // The value of a condition that is an expression is the value of the 770193326Sed // expression, implicitly converted to bool. 771193326Sed // 772193326Sed return PerformContextuallyConvertToBool(CondExpr); 773193326Sed} 774193326Sed 775193326Sed/// Helper function to determine whether this is the (deprecated) C++ 776193326Sed/// conversion from a string literal to a pointer to non-const char or 777193326Sed/// non-const wchar_t (for narrow and wide string literals, 778193326Sed/// respectively). 779193326Sedbool 780193326SedSema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) { 781193326Sed // Look inside the implicit cast, if it exists. 782193326Sed if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From)) 783193326Sed From = Cast->getSubExpr(); 784193326Sed 785193326Sed // A string literal (2.13.4) that is not a wide string literal can 786193326Sed // be converted to an rvalue of type "pointer to char"; a wide 787193326Sed // string literal can be converted to an rvalue of type "pointer 788193326Sed // to wchar_t" (C++ 4.2p2). 789193326Sed if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From)) 790193326Sed if (const PointerType *ToPtrType = ToType->getAsPointerType()) 791193326Sed if (const BuiltinType *ToPointeeType 792193326Sed = ToPtrType->getPointeeType()->getAsBuiltinType()) { 793193326Sed // This conversion is considered only when there is an 794193326Sed // explicit appropriate pointer target type (C++ 4.2p2). 795193326Sed if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 && 796193326Sed ((StrLit->isWide() && ToPointeeType->isWideCharType()) || 797193326Sed (!StrLit->isWide() && 798193326Sed (ToPointeeType->getKind() == BuiltinType::Char_U || 799193326Sed ToPointeeType->getKind() == BuiltinType::Char_S)))) 800193326Sed return true; 801193326Sed } 802193326Sed 803193326Sed return false; 804193326Sed} 805193326Sed 806193326Sed/// PerformImplicitConversion - Perform an implicit conversion of the 807193326Sed/// expression From to the type ToType. Returns true if there was an 808193326Sed/// error, false otherwise. The expression From is replaced with the 809193326Sed/// converted expression. Flavor is the kind of conversion we're 810193326Sed/// performing, used in the error message. If @p AllowExplicit, 811193326Sed/// explicit user-defined conversions are permitted. @p Elidable should be true 812193326Sed/// when called for copies which may be elided (C++ 12.8p15). C++0x overload 813193326Sed/// resolution works differently in that case. 814193326Sedbool 815193326SedSema::PerformImplicitConversion(Expr *&From, QualType ToType, 816193326Sed const char *Flavor, bool AllowExplicit, 817193326Sed bool Elidable) 818193326Sed{ 819193326Sed ImplicitConversionSequence ICS; 820193326Sed ICS.ConversionKind = ImplicitConversionSequence::BadConversion; 821193326Sed if (Elidable && getLangOptions().CPlusPlus0x) { 822193326Sed ICS = TryImplicitConversion(From, ToType, /*SuppressUserConversions*/false, 823193326Sed AllowExplicit, /*ForceRValue*/true); 824193326Sed } 825193326Sed if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) { 826193326Sed ICS = TryImplicitConversion(From, ToType, false, AllowExplicit); 827193326Sed } 828193326Sed return PerformImplicitConversion(From, ToType, ICS, Flavor); 829193326Sed} 830193326Sed 831193326Sed/// PerformImplicitConversion - Perform an implicit conversion of the 832193326Sed/// expression From to the type ToType using the pre-computed implicit 833193326Sed/// conversion sequence ICS. Returns true if there was an error, false 834193326Sed/// otherwise. The expression From is replaced with the converted 835193326Sed/// expression. Flavor is the kind of conversion we're performing, 836193326Sed/// used in the error message. 837193326Sedbool 838193326SedSema::PerformImplicitConversion(Expr *&From, QualType ToType, 839193326Sed const ImplicitConversionSequence &ICS, 840193326Sed const char* Flavor) { 841193326Sed switch (ICS.ConversionKind) { 842193326Sed case ImplicitConversionSequence::StandardConversion: 843193326Sed if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor)) 844193326Sed return true; 845193326Sed break; 846193326Sed 847193326Sed case ImplicitConversionSequence::UserDefinedConversion: 848193326Sed // FIXME: This is, of course, wrong. We'll need to actually call the 849193326Sed // constructor or conversion operator, and then cope with the standard 850193326Sed // conversions. 851193326Sed ImpCastExprToType(From, ToType.getNonReferenceType(), 852193326Sed ToType->isLValueReferenceType()); 853193326Sed return false; 854193326Sed 855193326Sed case ImplicitConversionSequence::EllipsisConversion: 856193326Sed assert(false && "Cannot perform an ellipsis conversion"); 857193326Sed return false; 858193326Sed 859193326Sed case ImplicitConversionSequence::BadConversion: 860193326Sed return true; 861193326Sed } 862193326Sed 863193326Sed // Everything went well. 864193326Sed return false; 865193326Sed} 866193326Sed 867193326Sed/// PerformImplicitConversion - Perform an implicit conversion of the 868193326Sed/// expression From to the type ToType by following the standard 869193326Sed/// conversion sequence SCS. Returns true if there was an error, false 870193326Sed/// otherwise. The expression From is replaced with the converted 871193326Sed/// expression. Flavor is the context in which we're performing this 872193326Sed/// conversion, for use in error messages. 873193326Sedbool 874193326SedSema::PerformImplicitConversion(Expr *&From, QualType ToType, 875193326Sed const StandardConversionSequence& SCS, 876193326Sed const char *Flavor) { 877193326Sed // Overall FIXME: we are recomputing too many types here and doing far too 878193326Sed // much extra work. What this means is that we need to keep track of more 879193326Sed // information that is computed when we try the implicit conversion initially, 880193326Sed // so that we don't need to recompute anything here. 881193326Sed QualType FromType = From->getType(); 882193326Sed 883193326Sed if (SCS.CopyConstructor) { 884193326Sed // FIXME: When can ToType be a reference type? 885193326Sed assert(!ToType->isReferenceType()); 886193326Sed 887193326Sed // FIXME: Keep track of whether the copy constructor is elidable or not. 888193326Sed From = CXXConstructExpr::Create(Context, ToType, 889193326Sed SCS.CopyConstructor, false, &From, 1); 890193326Sed return false; 891193326Sed } 892193326Sed 893193326Sed // Perform the first implicit conversion. 894193326Sed switch (SCS.First) { 895193326Sed case ICK_Identity: 896193326Sed case ICK_Lvalue_To_Rvalue: 897193326Sed // Nothing to do. 898193326Sed break; 899193326Sed 900193326Sed case ICK_Array_To_Pointer: 901193326Sed FromType = Context.getArrayDecayedType(FromType); 902193326Sed ImpCastExprToType(From, FromType); 903193326Sed break; 904193326Sed 905193326Sed case ICK_Function_To_Pointer: 906193326Sed if (Context.getCanonicalType(FromType) == Context.OverloadTy) { 907193326Sed FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true); 908193326Sed if (!Fn) 909193326Sed return true; 910193326Sed 911193326Sed if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin())) 912193326Sed return true; 913193326Sed 914193326Sed FixOverloadedFunctionReference(From, Fn); 915193326Sed FromType = From->getType(); 916193326Sed } 917193326Sed FromType = Context.getPointerType(FromType); 918193326Sed ImpCastExprToType(From, FromType); 919193326Sed break; 920193326Sed 921193326Sed default: 922193326Sed assert(false && "Improper first standard conversion"); 923193326Sed break; 924193326Sed } 925193326Sed 926193326Sed // Perform the second implicit conversion 927193326Sed switch (SCS.Second) { 928193326Sed case ICK_Identity: 929193326Sed // Nothing to do. 930193326Sed break; 931193326Sed 932193326Sed case ICK_Integral_Promotion: 933193326Sed case ICK_Floating_Promotion: 934193326Sed case ICK_Complex_Promotion: 935193326Sed case ICK_Integral_Conversion: 936193326Sed case ICK_Floating_Conversion: 937193326Sed case ICK_Complex_Conversion: 938193326Sed case ICK_Floating_Integral: 939193326Sed case ICK_Complex_Real: 940193326Sed case ICK_Compatible_Conversion: 941193326Sed // FIXME: Go deeper to get the unqualified type! 942193326Sed FromType = ToType.getUnqualifiedType(); 943193326Sed ImpCastExprToType(From, FromType); 944193326Sed break; 945193326Sed 946193326Sed case ICK_Pointer_Conversion: 947193326Sed if (SCS.IncompatibleObjC) { 948193326Sed // Diagnose incompatible Objective-C conversions 949193326Sed Diag(From->getSourceRange().getBegin(), 950193326Sed diag::ext_typecheck_convert_incompatible_pointer) 951193326Sed << From->getType() << ToType << Flavor 952193326Sed << From->getSourceRange(); 953193326Sed } 954193326Sed 955193326Sed if (CheckPointerConversion(From, ToType)) 956193326Sed return true; 957193326Sed ImpCastExprToType(From, ToType); 958193326Sed break; 959193326Sed 960193326Sed case ICK_Pointer_Member: 961193326Sed if (CheckMemberPointerConversion(From, ToType)) 962193326Sed return true; 963193326Sed ImpCastExprToType(From, ToType); 964193326Sed break; 965193326Sed 966193326Sed case ICK_Boolean_Conversion: 967193326Sed FromType = Context.BoolTy; 968193326Sed ImpCastExprToType(From, FromType); 969193326Sed break; 970193326Sed 971193326Sed default: 972193326Sed assert(false && "Improper second standard conversion"); 973193326Sed break; 974193326Sed } 975193326Sed 976193326Sed switch (SCS.Third) { 977193326Sed case ICK_Identity: 978193326Sed // Nothing to do. 979193326Sed break; 980193326Sed 981193326Sed case ICK_Qualification: 982193326Sed // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue 983193326Sed // references. 984193326Sed ImpCastExprToType(From, ToType.getNonReferenceType(), 985193326Sed ToType->isLValueReferenceType()); 986193326Sed break; 987193326Sed 988193326Sed default: 989193326Sed assert(false && "Improper second standard conversion"); 990193326Sed break; 991193326Sed } 992193326Sed 993193326Sed return false; 994193326Sed} 995193326Sed 996193326SedSema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT, 997193326Sed SourceLocation KWLoc, 998193326Sed SourceLocation LParen, 999193326Sed TypeTy *Ty, 1000193326Sed SourceLocation RParen) { 1001193326Sed // FIXME: Some of the type traits have requirements. Interestingly, only the 1002193326Sed // __is_base_of requirement is explicitly stated to be diagnosed. Indeed, G++ 1003193326Sed // accepts __is_pod(Incomplete) without complaints, and claims that the type 1004193326Sed // is indeed a POD. 1005193326Sed 1006193326Sed // There is no point in eagerly computing the value. The traits are designed 1007193326Sed // to be used from type trait templates, so Ty will be a template parameter 1008193326Sed // 99% of the time. 1009193326Sed return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, 1010193326Sed QualType::getFromOpaquePtr(Ty), 1011193326Sed RParen, Context.BoolTy)); 1012193326Sed} 1013193326Sed 1014193326SedQualType Sema::CheckPointerToMemberOperands( 1015193326Sed Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) 1016193326Sed{ 1017193326Sed const char *OpSpelling = isIndirect ? "->*" : ".*"; 1018193326Sed // C++ 5.5p2 1019193326Sed // The binary operator .* [p3: ->*] binds its second operand, which shall 1020193326Sed // be of type "pointer to member of T" (where T is a completely-defined 1021193326Sed // class type) [...] 1022193326Sed QualType RType = rex->getType(); 1023193326Sed const MemberPointerType *MemPtr = RType->getAsMemberPointerType(); 1024193326Sed if (!MemPtr) { 1025193326Sed Diag(Loc, diag::err_bad_memptr_rhs) 1026193326Sed << OpSpelling << RType << rex->getSourceRange(); 1027193326Sed return QualType(); 1028193326Sed } 1029193326Sed 1030193326Sed QualType Class(MemPtr->getClass(), 0); 1031193326Sed 1032193326Sed // C++ 5.5p2 1033193326Sed // [...] to its first operand, which shall be of class T or of a class of 1034193326Sed // which T is an unambiguous and accessible base class. [p3: a pointer to 1035193326Sed // such a class] 1036193326Sed QualType LType = lex->getType(); 1037193326Sed if (isIndirect) { 1038193326Sed if (const PointerType *Ptr = LType->getAsPointerType()) 1039193326Sed LType = Ptr->getPointeeType().getNonReferenceType(); 1040193326Sed else { 1041193326Sed Diag(Loc, diag::err_bad_memptr_lhs) 1042193326Sed << OpSpelling << 1 << LType << lex->getSourceRange(); 1043193326Sed return QualType(); 1044193326Sed } 1045193326Sed } 1046193326Sed 1047193326Sed if (Context.getCanonicalType(Class).getUnqualifiedType() != 1048193326Sed Context.getCanonicalType(LType).getUnqualifiedType()) { 1049193326Sed BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 1050193326Sed /*DetectVirtual=*/false); 1051193326Sed // FIXME: Would it be useful to print full ambiguity paths, or is that 1052193326Sed // overkill? 1053193326Sed if (!IsDerivedFrom(LType, Class, Paths) || 1054193326Sed Paths.isAmbiguous(Context.getCanonicalType(Class))) { 1055193326Sed Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling 1056193326Sed << (int)isIndirect << lex->getType() << lex->getSourceRange(); 1057193326Sed return QualType(); 1058193326Sed } 1059193326Sed } 1060193326Sed 1061193326Sed // C++ 5.5p2 1062193326Sed // The result is an object or a function of the type specified by the 1063193326Sed // second operand. 1064193326Sed // The cv qualifiers are the union of those in the pointer and the left side, 1065193326Sed // in accordance with 5.5p5 and 5.2.5. 1066193326Sed // FIXME: This returns a dereferenced member function pointer as a normal 1067193326Sed // function type. However, the only operation valid on such functions is 1068193326Sed // calling them. There's also a GCC extension to get a function pointer to the 1069193326Sed // thing, which is another complication, because this type - unlike the type 1070193326Sed // that is the result of this expression - takes the class as the first 1071193326Sed // argument. 1072193326Sed // We probably need a "MemberFunctionClosureType" or something like that. 1073193326Sed QualType Result = MemPtr->getPointeeType(); 1074193326Sed if (LType.isConstQualified()) 1075193326Sed Result.addConst(); 1076193326Sed if (LType.isVolatileQualified()) 1077193326Sed Result.addVolatile(); 1078193326Sed return Result; 1079193326Sed} 1080193326Sed 1081193326Sed/// \brief Get the target type of a standard or user-defined conversion. 1082193326Sedstatic QualType TargetType(const ImplicitConversionSequence &ICS) { 1083193326Sed assert((ICS.ConversionKind == 1084193326Sed ImplicitConversionSequence::StandardConversion || 1085193326Sed ICS.ConversionKind == 1086193326Sed ImplicitConversionSequence::UserDefinedConversion) && 1087193326Sed "function only valid for standard or user-defined conversions"); 1088193326Sed if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion) 1089193326Sed return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr); 1090193326Sed return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr); 1091193326Sed} 1092193326Sed 1093193326Sed/// \brief Try to convert a type to another according to C++0x 5.16p3. 1094193326Sed/// 1095193326Sed/// This is part of the parameter validation for the ? operator. If either 1096193326Sed/// value operand is a class type, the two operands are attempted to be 1097193326Sed/// converted to each other. This function does the conversion in one direction. 1098193326Sed/// It emits a diagnostic and returns true only if it finds an ambiguous 1099193326Sed/// conversion. 1100193326Sedstatic bool TryClassUnification(Sema &Self, Expr *From, Expr *To, 1101193326Sed SourceLocation QuestionLoc, 1102193326Sed ImplicitConversionSequence &ICS) 1103193326Sed{ 1104193326Sed // C++0x 5.16p3 1105193326Sed // The process for determining whether an operand expression E1 of type T1 1106193326Sed // can be converted to match an operand expression E2 of type T2 is defined 1107193326Sed // as follows: 1108193326Sed // -- If E2 is an lvalue: 1109193326Sed if (To->isLvalue(Self.Context) == Expr::LV_Valid) { 1110193326Sed // E1 can be converted to match E2 if E1 can be implicitly converted to 1111193326Sed // type "lvalue reference to T2", subject to the constraint that in the 1112193326Sed // conversion the reference must bind directly to E1. 1113193326Sed if (!Self.CheckReferenceInit(From, 1114193326Sed Self.Context.getLValueReferenceType(To->getType()), 1115193326Sed &ICS)) 1116193326Sed { 1117193326Sed assert((ICS.ConversionKind == 1118193326Sed ImplicitConversionSequence::StandardConversion || 1119193326Sed ICS.ConversionKind == 1120193326Sed ImplicitConversionSequence::UserDefinedConversion) && 1121193326Sed "expected a definite conversion"); 1122193326Sed bool DirectBinding = 1123193326Sed ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ? 1124193326Sed ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding; 1125193326Sed if (DirectBinding) 1126193326Sed return false; 1127193326Sed } 1128193326Sed } 1129193326Sed ICS.ConversionKind = ImplicitConversionSequence::BadConversion; 1130193326Sed // -- If E2 is an rvalue, or if the conversion above cannot be done: 1131193326Sed // -- if E1 and E2 have class type, and the underlying class types are 1132193326Sed // the same or one is a base class of the other: 1133193326Sed QualType FTy = From->getType(); 1134193326Sed QualType TTy = To->getType(); 1135193326Sed const RecordType *FRec = FTy->getAsRecordType(); 1136193326Sed const RecordType *TRec = TTy->getAsRecordType(); 1137193326Sed bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy); 1138193326Sed if (FRec && TRec && (FRec == TRec || 1139193326Sed FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) { 1140193326Sed // E1 can be converted to match E2 if the class of T2 is the 1141193326Sed // same type as, or a base class of, the class of T1, and 1142193326Sed // [cv2 > cv1]. 1143193326Sed if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) { 1144193326Sed // Could still fail if there's no copy constructor. 1145193326Sed // FIXME: Is this a hard error then, or just a conversion failure? The 1146193326Sed // standard doesn't say. 1147193326Sed ICS = Self.TryCopyInitialization(From, TTy); 1148193326Sed } 1149193326Sed } else { 1150193326Sed // -- Otherwise: E1 can be converted to match E2 if E1 can be 1151193326Sed // implicitly converted to the type that expression E2 would have 1152193326Sed // if E2 were converted to an rvalue. 1153193326Sed // First find the decayed type. 1154193326Sed if (TTy->isFunctionType()) 1155193326Sed TTy = Self.Context.getPointerType(TTy); 1156193326Sed else if(TTy->isArrayType()) 1157193326Sed TTy = Self.Context.getArrayDecayedType(TTy); 1158193326Sed 1159193326Sed // Now try the implicit conversion. 1160193326Sed // FIXME: This doesn't detect ambiguities. 1161193326Sed ICS = Self.TryImplicitConversion(From, TTy); 1162193326Sed } 1163193326Sed return false; 1164193326Sed} 1165193326Sed 1166193326Sed/// \brief Try to find a common type for two according to C++0x 5.16p5. 1167193326Sed/// 1168193326Sed/// This is part of the parameter validation for the ? operator. If either 1169193326Sed/// value operand is a class type, overload resolution is used to find a 1170193326Sed/// conversion to a common type. 1171193326Sedstatic bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS, 1172193326Sed SourceLocation Loc) { 1173193326Sed Expr *Args[2] = { LHS, RHS }; 1174193326Sed OverloadCandidateSet CandidateSet; 1175193326Sed Self.AddBuiltinOperatorCandidates(OO_Conditional, Args, 2, CandidateSet); 1176193326Sed 1177193326Sed OverloadCandidateSet::iterator Best; 1178193326Sed switch (Self.BestViableFunction(CandidateSet, Best)) { 1179193326Sed case Sema::OR_Success: 1180193326Sed // We found a match. Perform the conversions on the arguments and move on. 1181193326Sed if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0], 1182193326Sed Best->Conversions[0], "converting") || 1183193326Sed Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1], 1184193326Sed Best->Conversions[1], "converting")) 1185193326Sed break; 1186193326Sed return false; 1187193326Sed 1188193326Sed case Sema::OR_No_Viable_Function: 1189193326Sed Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 1190193326Sed << LHS->getType() << RHS->getType() 1191193326Sed << LHS->getSourceRange() << RHS->getSourceRange(); 1192193326Sed return true; 1193193326Sed 1194193326Sed case Sema::OR_Ambiguous: 1195193326Sed Self.Diag(Loc, diag::err_conditional_ambiguous_ovl) 1196193326Sed << LHS->getType() << RHS->getType() 1197193326Sed << LHS->getSourceRange() << RHS->getSourceRange(); 1198193326Sed // FIXME: Print the possible common types by printing the return types of 1199193326Sed // the viable candidates. 1200193326Sed break; 1201193326Sed 1202193326Sed case Sema::OR_Deleted: 1203193326Sed assert(false && "Conditional operator has only built-in overloads"); 1204193326Sed break; 1205193326Sed } 1206193326Sed return true; 1207193326Sed} 1208193326Sed 1209193326Sed/// \brief Perform an "extended" implicit conversion as returned by 1210193326Sed/// TryClassUnification. 1211193326Sed/// 1212193326Sed/// TryClassUnification generates ICSs that include reference bindings. 1213193326Sed/// PerformImplicitConversion is not suitable for this; it chokes if the 1214193326Sed/// second part of a standard conversion is ICK_DerivedToBase. This function 1215193326Sed/// handles the reference binding specially. 1216193326Sedstatic bool ConvertForConditional(Sema &Self, Expr *&E, 1217193326Sed const ImplicitConversionSequence &ICS) 1218193326Sed{ 1219193326Sed if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion && 1220193326Sed ICS.Standard.ReferenceBinding) { 1221193326Sed assert(ICS.Standard.DirectBinding && 1222193326Sed "TryClassUnification should never generate indirect ref bindings"); 1223193326Sed // FIXME: CheckReferenceInit should be able to reuse the ICS instead of 1224193326Sed // redoing all the work. 1225193326Sed return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType( 1226193326Sed TargetType(ICS))); 1227193326Sed } 1228193326Sed if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion && 1229193326Sed ICS.UserDefined.After.ReferenceBinding) { 1230193326Sed assert(ICS.UserDefined.After.DirectBinding && 1231193326Sed "TryClassUnification should never generate indirect ref bindings"); 1232193326Sed return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType( 1233193326Sed TargetType(ICS))); 1234193326Sed } 1235193326Sed if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting")) 1236193326Sed return true; 1237193326Sed return false; 1238193326Sed} 1239193326Sed 1240193326Sed/// \brief Check the operands of ?: under C++ semantics. 1241193326Sed/// 1242193326Sed/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y 1243193326Sed/// extension. In this case, LHS == Cond. (But they're not aliases.) 1244193326SedQualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS, 1245193326Sed SourceLocation QuestionLoc) { 1246193326Sed // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++ 1247193326Sed // interface pointers. 1248193326Sed 1249193326Sed // C++0x 5.16p1 1250193326Sed // The first expression is contextually converted to bool. 1251193326Sed if (!Cond->isTypeDependent()) { 1252193326Sed if (CheckCXXBooleanCondition(Cond)) 1253193326Sed return QualType(); 1254193326Sed } 1255193326Sed 1256193326Sed // Either of the arguments dependent? 1257193326Sed if (LHS->isTypeDependent() || RHS->isTypeDependent()) 1258193326Sed return Context.DependentTy; 1259193326Sed 1260193326Sed // C++0x 5.16p2 1261193326Sed // If either the second or the third operand has type (cv) void, ... 1262193326Sed QualType LTy = LHS->getType(); 1263193326Sed QualType RTy = RHS->getType(); 1264193326Sed bool LVoid = LTy->isVoidType(); 1265193326Sed bool RVoid = RTy->isVoidType(); 1266193326Sed if (LVoid || RVoid) { 1267193326Sed // ... then the [l2r] conversions are performed on the second and third 1268193326Sed // operands ... 1269193326Sed DefaultFunctionArrayConversion(LHS); 1270193326Sed DefaultFunctionArrayConversion(RHS); 1271193326Sed LTy = LHS->getType(); 1272193326Sed RTy = RHS->getType(); 1273193326Sed 1274193326Sed // ... and one of the following shall hold: 1275193326Sed // -- The second or the third operand (but not both) is a throw- 1276193326Sed // expression; the result is of the type of the other and is an rvalue. 1277193326Sed bool LThrow = isa<CXXThrowExpr>(LHS); 1278193326Sed bool RThrow = isa<CXXThrowExpr>(RHS); 1279193326Sed if (LThrow && !RThrow) 1280193326Sed return RTy; 1281193326Sed if (RThrow && !LThrow) 1282193326Sed return LTy; 1283193326Sed 1284193326Sed // -- Both the second and third operands have type void; the result is of 1285193326Sed // type void and is an rvalue. 1286193326Sed if (LVoid && RVoid) 1287193326Sed return Context.VoidTy; 1288193326Sed 1289193326Sed // Neither holds, error. 1290193326Sed Diag(QuestionLoc, diag::err_conditional_void_nonvoid) 1291193326Sed << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1) 1292193326Sed << LHS->getSourceRange() << RHS->getSourceRange(); 1293193326Sed return QualType(); 1294193326Sed } 1295193326Sed 1296193326Sed // Neither is void. 1297193326Sed 1298193326Sed // C++0x 5.16p3 1299193326Sed // Otherwise, if the second and third operand have different types, and 1300193326Sed // either has (cv) class type, and attempt is made to convert each of those 1301193326Sed // operands to the other. 1302193326Sed if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) && 1303193326Sed (LTy->isRecordType() || RTy->isRecordType())) { 1304193326Sed ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft; 1305193326Sed // These return true if a single direction is already ambiguous. 1306193326Sed if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight)) 1307193326Sed return QualType(); 1308193326Sed if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft)) 1309193326Sed return QualType(); 1310193326Sed 1311193326Sed bool HaveL2R = ICSLeftToRight.ConversionKind != 1312193326Sed ImplicitConversionSequence::BadConversion; 1313193326Sed bool HaveR2L = ICSRightToLeft.ConversionKind != 1314193326Sed ImplicitConversionSequence::BadConversion; 1315193326Sed // If both can be converted, [...] the program is ill-formed. 1316193326Sed if (HaveL2R && HaveR2L) { 1317193326Sed Diag(QuestionLoc, diag::err_conditional_ambiguous) 1318193326Sed << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange(); 1319193326Sed return QualType(); 1320193326Sed } 1321193326Sed 1322193326Sed // If exactly one conversion is possible, that conversion is applied to 1323193326Sed // the chosen operand and the converted operands are used in place of the 1324193326Sed // original operands for the remainder of this section. 1325193326Sed if (HaveL2R) { 1326193326Sed if (ConvertForConditional(*this, LHS, ICSLeftToRight)) 1327193326Sed return QualType(); 1328193326Sed LTy = LHS->getType(); 1329193326Sed } else if (HaveR2L) { 1330193326Sed if (ConvertForConditional(*this, RHS, ICSRightToLeft)) 1331193326Sed return QualType(); 1332193326Sed RTy = RHS->getType(); 1333193326Sed } 1334193326Sed } 1335193326Sed 1336193326Sed // C++0x 5.16p4 1337193326Sed // If the second and third operands are lvalues and have the same type, 1338193326Sed // the result is of that type [...] 1339193326Sed bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy); 1340193326Sed if (Same && LHS->isLvalue(Context) == Expr::LV_Valid && 1341193326Sed RHS->isLvalue(Context) == Expr::LV_Valid) 1342193326Sed return LTy; 1343193326Sed 1344193326Sed // C++0x 5.16p5 1345193326Sed // Otherwise, the result is an rvalue. If the second and third operands 1346193326Sed // do not have the same type, and either has (cv) class type, ... 1347193326Sed if (!Same && (LTy->isRecordType() || RTy->isRecordType())) { 1348193326Sed // ... overload resolution is used to determine the conversions (if any) 1349193326Sed // to be applied to the operands. If the overload resolution fails, the 1350193326Sed // program is ill-formed. 1351193326Sed if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc)) 1352193326Sed return QualType(); 1353193326Sed } 1354193326Sed 1355193326Sed // C++0x 5.16p6 1356193326Sed // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard 1357193326Sed // conversions are performed on the second and third operands. 1358193326Sed DefaultFunctionArrayConversion(LHS); 1359193326Sed DefaultFunctionArrayConversion(RHS); 1360193326Sed LTy = LHS->getType(); 1361193326Sed RTy = RHS->getType(); 1362193326Sed 1363193326Sed // After those conversions, one of the following shall hold: 1364193326Sed // -- The second and third operands have the same type; the result 1365193326Sed // is of that type. 1366193326Sed if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) 1367193326Sed return LTy; 1368193326Sed 1369193326Sed // -- The second and third operands have arithmetic or enumeration type; 1370193326Sed // the usual arithmetic conversions are performed to bring them to a 1371193326Sed // common type, and the result is of that type. 1372193326Sed if (LTy->isArithmeticType() && RTy->isArithmeticType()) { 1373193326Sed UsualArithmeticConversions(LHS, RHS); 1374193326Sed return LHS->getType(); 1375193326Sed } 1376193326Sed 1377193326Sed // -- The second and third operands have pointer type, or one has pointer 1378193326Sed // type and the other is a null pointer constant; pointer conversions 1379193326Sed // and qualification conversions are performed to bring them to their 1380193326Sed // composite pointer type. The result is of the composite pointer type. 1381193326Sed QualType Composite = FindCompositePointerType(LHS, RHS); 1382193326Sed if (!Composite.isNull()) 1383193326Sed return Composite; 1384193326Sed 1385193326Sed // Fourth bullet is same for pointers-to-member. However, the possible 1386193326Sed // conversions are far more limited: we have null-to-pointer, upcast of 1387193326Sed // containing class, and second-level cv-ness. 1388193326Sed // cv-ness is not a union, but must match one of the two operands. (Which, 1389193326Sed // frankly, is stupid.) 1390193326Sed const MemberPointerType *LMemPtr = LTy->getAsMemberPointerType(); 1391193326Sed const MemberPointerType *RMemPtr = RTy->getAsMemberPointerType(); 1392193326Sed if (LMemPtr && RHS->isNullPointerConstant(Context)) { 1393193326Sed ImpCastExprToType(RHS, LTy); 1394193326Sed return LTy; 1395193326Sed } 1396193326Sed if (RMemPtr && LHS->isNullPointerConstant(Context)) { 1397193326Sed ImpCastExprToType(LHS, RTy); 1398193326Sed return RTy; 1399193326Sed } 1400193326Sed if (LMemPtr && RMemPtr) { 1401193326Sed QualType LPointee = LMemPtr->getPointeeType(); 1402193326Sed QualType RPointee = RMemPtr->getPointeeType(); 1403193326Sed // First, we check that the unqualified pointee type is the same. If it's 1404193326Sed // not, there's no conversion that will unify the two pointers. 1405193326Sed if (Context.getCanonicalType(LPointee).getUnqualifiedType() == 1406193326Sed Context.getCanonicalType(RPointee).getUnqualifiedType()) { 1407193326Sed // Second, we take the greater of the two cv qualifications. If neither 1408193326Sed // is greater than the other, the conversion is not possible. 1409193326Sed unsigned Q = LPointee.getCVRQualifiers() | RPointee.getCVRQualifiers(); 1410193326Sed if (Q == LPointee.getCVRQualifiers() || Q == RPointee.getCVRQualifiers()){ 1411193326Sed // Third, we check if either of the container classes is derived from 1412193326Sed // the other. 1413193326Sed QualType LContainer(LMemPtr->getClass(), 0); 1414193326Sed QualType RContainer(RMemPtr->getClass(), 0); 1415193326Sed QualType MoreDerived; 1416193326Sed if (Context.getCanonicalType(LContainer) == 1417193326Sed Context.getCanonicalType(RContainer)) 1418193326Sed MoreDerived = LContainer; 1419193326Sed else if (IsDerivedFrom(LContainer, RContainer)) 1420193326Sed MoreDerived = LContainer; 1421193326Sed else if (IsDerivedFrom(RContainer, LContainer)) 1422193326Sed MoreDerived = RContainer; 1423193326Sed 1424193326Sed if (!MoreDerived.isNull()) { 1425193326Sed // The type 'Q Pointee (MoreDerived::*)' is the common type. 1426193326Sed // We don't use ImpCastExprToType here because this could still fail 1427193326Sed // for ambiguous or inaccessible conversions. 1428193326Sed QualType Common = Context.getMemberPointerType( 1429193326Sed LPointee.getQualifiedType(Q), MoreDerived.getTypePtr()); 1430193326Sed if (PerformImplicitConversion(LHS, Common, "converting")) 1431193326Sed return QualType(); 1432193326Sed if (PerformImplicitConversion(RHS, Common, "converting")) 1433193326Sed return QualType(); 1434193326Sed return Common; 1435193326Sed } 1436193326Sed } 1437193326Sed } 1438193326Sed } 1439193326Sed 1440193326Sed Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 1441193326Sed << LHS->getType() << RHS->getType() 1442193326Sed << LHS->getSourceRange() << RHS->getSourceRange(); 1443193326Sed return QualType(); 1444193326Sed} 1445193326Sed 1446193326Sed/// \brief Find a merged pointer type and convert the two expressions to it. 1447193326Sed/// 1448193326Sed/// This finds the composite pointer type for @p E1 and @p E2 according to 1449193326Sed/// C++0x 5.9p2. It converts both expressions to this type and returns it. 1450193326Sed/// It does not emit diagnostics. 1451193326SedQualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) { 1452193326Sed assert(getLangOptions().CPlusPlus && "This function assumes C++"); 1453193326Sed QualType T1 = E1->getType(), T2 = E2->getType(); 1454193326Sed if(!T1->isPointerType() && !T2->isPointerType()) 1455193326Sed return QualType(); 1456193326Sed 1457193326Sed // C++0x 5.9p2 1458193326Sed // Pointer conversions and qualification conversions are performed on 1459193326Sed // pointer operands to bring them to their composite pointer type. If 1460193326Sed // one operand is a null pointer constant, the composite pointer type is 1461193326Sed // the type of the other operand. 1462193326Sed if (E1->isNullPointerConstant(Context)) { 1463193326Sed ImpCastExprToType(E1, T2); 1464193326Sed return T2; 1465193326Sed } 1466193326Sed if (E2->isNullPointerConstant(Context)) { 1467193326Sed ImpCastExprToType(E2, T1); 1468193326Sed return T1; 1469193326Sed } 1470193326Sed // Now both have to be pointers. 1471193326Sed if(!T1->isPointerType() || !T2->isPointerType()) 1472193326Sed return QualType(); 1473193326Sed 1474193326Sed // Otherwise, of one of the operands has type "pointer to cv1 void," then 1475193326Sed // the other has type "pointer to cv2 T" and the composite pointer type is 1476193326Sed // "pointer to cv12 void," where cv12 is the union of cv1 and cv2. 1477193326Sed // Otherwise, the composite pointer type is a pointer type similar to the 1478193326Sed // type of one of the operands, with a cv-qualification signature that is 1479193326Sed // the union of the cv-qualification signatures of the operand types. 1480193326Sed // In practice, the first part here is redundant; it's subsumed by the second. 1481193326Sed // What we do here is, we build the two possible composite types, and try the 1482193326Sed // conversions in both directions. If only one works, or if the two composite 1483193326Sed // types are the same, we have succeeded. 1484193326Sed llvm::SmallVector<unsigned, 4> QualifierUnion; 1485193326Sed QualType Composite1 = T1, Composite2 = T2; 1486193326Sed const PointerType *Ptr1, *Ptr2; 1487193326Sed while ((Ptr1 = Composite1->getAsPointerType()) && 1488193326Sed (Ptr2 = Composite2->getAsPointerType())) { 1489193326Sed Composite1 = Ptr1->getPointeeType(); 1490193326Sed Composite2 = Ptr2->getPointeeType(); 1491193326Sed QualifierUnion.push_back( 1492193326Sed Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); 1493193326Sed } 1494193326Sed // Rewrap the composites as pointers with the union CVRs. 1495193326Sed for (llvm::SmallVector<unsigned, 4>::iterator I = QualifierUnion.begin(), 1496193326Sed E = QualifierUnion.end(); I != E; ++I) { 1497193326Sed Composite1 = Context.getPointerType(Composite1.getQualifiedType(*I)); 1498193326Sed Composite2 = Context.getPointerType(Composite2.getQualifiedType(*I)); 1499193326Sed } 1500193326Sed 1501193326Sed ImplicitConversionSequence E1ToC1 = TryImplicitConversion(E1, Composite1); 1502193326Sed ImplicitConversionSequence E2ToC1 = TryImplicitConversion(E2, Composite1); 1503193326Sed ImplicitConversionSequence E1ToC2, E2ToC2; 1504193326Sed E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion; 1505193326Sed E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion; 1506193326Sed if (Context.getCanonicalType(Composite1) != 1507193326Sed Context.getCanonicalType(Composite2)) { 1508193326Sed E1ToC2 = TryImplicitConversion(E1, Composite2); 1509193326Sed E2ToC2 = TryImplicitConversion(E2, Composite2); 1510193326Sed } 1511193326Sed 1512193326Sed bool ToC1Viable = E1ToC1.ConversionKind != 1513193326Sed ImplicitConversionSequence::BadConversion 1514193326Sed && E2ToC1.ConversionKind != 1515193326Sed ImplicitConversionSequence::BadConversion; 1516193326Sed bool ToC2Viable = E1ToC2.ConversionKind != 1517193326Sed ImplicitConversionSequence::BadConversion 1518193326Sed && E2ToC2.ConversionKind != 1519193326Sed ImplicitConversionSequence::BadConversion; 1520193326Sed if (ToC1Viable && !ToC2Viable) { 1521193326Sed if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") && 1522193326Sed !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting")) 1523193326Sed return Composite1; 1524193326Sed } 1525193326Sed if (ToC2Viable && !ToC1Viable) { 1526193326Sed if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") && 1527193326Sed !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting")) 1528193326Sed return Composite2; 1529193326Sed } 1530193326Sed return QualType(); 1531193326Sed} 1532193326Sed 1533193326SedSema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) { 1534193326Sed const RecordType *RT = E->getType()->getAsRecordType(); 1535193326Sed if (!RT) 1536193326Sed return Owned(E); 1537193326Sed 1538193326Sed CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 1539193326Sed if (RD->hasTrivialDestructor()) 1540193326Sed return Owned(E); 1541193326Sed 1542193326Sed CXXTemporary *Temp = CXXTemporary::Create(Context, 1543193326Sed RD->getDestructor(Context)); 1544193326Sed ExprTemporaries.push_back(Temp); 1545193326Sed 1546193326Sed // FIXME: Add the temporary to the temporaries vector. 1547193326Sed return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E)); 1548193326Sed} 1549193326Sed 1550193326Sed// FIXME: This doesn't handle casts yet. 1551193326SedExpr *Sema::RemoveOutermostTemporaryBinding(Expr *E) { 1552193326Sed const RecordType *RT = E->getType()->getAsRecordType(); 1553193326Sed if (!RT) 1554193326Sed return E; 1555193326Sed 1556193326Sed CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 1557193326Sed if (RD->hasTrivialDestructor()) 1558193326Sed return E; 1559193326Sed 1560193326Sed /// The expr passed in must be a CXXExprWithTemporaries. 1561193326Sed CXXExprWithTemporaries *TempExpr = dyn_cast<CXXExprWithTemporaries>(E); 1562193326Sed if (!TempExpr) 1563193326Sed return E; 1564193326Sed 1565193326Sed Expr *SubExpr = TempExpr->getSubExpr(); 1566193326Sed if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubExpr)) { 1567193326Sed assert(BE->getTemporary() == 1568193326Sed TempExpr->getTemporary(TempExpr->getNumTemporaries() - 1) && 1569193326Sed "Found temporary is not last in list!"); 1570193326Sed 1571193326Sed Expr *BindSubExpr = BE->getSubExpr(); 1572193326Sed BE->setSubExpr(0); 1573193326Sed 1574193326Sed if (TempExpr->getNumTemporaries() == 1) { 1575193326Sed // There's just one temporary left, so we don't need the TempExpr node. 1576193326Sed TempExpr->Destroy(Context); 1577193326Sed return BindSubExpr; 1578193326Sed } else { 1579193326Sed TempExpr->removeLastTemporary(); 1580193326Sed TempExpr->setSubExpr(BindSubExpr); 1581193326Sed BE->Destroy(Context); 1582193326Sed } 1583193326Sed 1584193326Sed return E; 1585193326Sed } 1586193326Sed 1587193326Sed // FIXME: We might need to handle other expressions here. 1588193326Sed return E; 1589193326Sed} 1590193326Sed 1591193576SedExpr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr, 1592193576Sed bool DestroyTemps) { 1593193576Sed assert(SubExpr && "sub expression can't be null!"); 1594193576Sed 1595193576Sed if (ExprTemporaries.empty()) 1596193576Sed return SubExpr; 1597193576Sed 1598193576Sed Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr, 1599193576Sed &ExprTemporaries[0], 1600193576Sed ExprTemporaries.size(), 1601193576Sed DestroyTemps); 1602193576Sed ExprTemporaries.clear(); 1603193576Sed 1604193576Sed return E; 1605193576Sed} 1606193576Sed 1607193326SedSema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) { 1608193326Sed Expr *FullExpr = Arg.takeAs<Expr>(); 1609193576Sed if (FullExpr) 1610193576Sed FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr); 1611193326Sed 1612193326Sed return Owned(FullExpr); 1613193326Sed} 1614