SemaExprCXX.cpp revision 3b7ec4be3ab6a5f2c13fb22622456d13b43a1751
1//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements semantic analysis for C++ expressions. 11// 12//===----------------------------------------------------------------------===// 13 14#include "SemaInherit.h" 15#include "Sema.h" 16#include "clang/AST/ExprCXX.h" 17#include "clang/AST/ASTContext.h" 18#include "clang/Parse/DeclSpec.h" 19#include "clang/Lex/Preprocessor.h" 20#include "clang/Basic/TargetInfo.h" 21#include "llvm/ADT/STLExtras.h" 22using namespace clang; 23 24/// ActOnCXXConversionFunctionExpr - Parse a C++ conversion function 25/// name (e.g., operator void const *) as an expression. This is 26/// very similar to ActOnIdentifierExpr, except that instead of 27/// providing an identifier the parser provides the type of the 28/// conversion function. 29Sema::OwningExprResult 30Sema::ActOnCXXConversionFunctionExpr(Scope *S, SourceLocation OperatorLoc, 31 TypeTy *Ty, bool HasTrailingLParen, 32 const CXXScopeSpec &SS, 33 bool isAddressOfOperand) { 34 QualType ConvType = QualType::getFromOpaquePtr(Ty); 35 QualType ConvTypeCanon = Context.getCanonicalType(ConvType); 36 DeclarationName ConvName 37 = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon); 38 return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen, 39 &SS, isAddressOfOperand); 40} 41 42/// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator 43/// name (e.g., @c operator+ ) as an expression. This is very 44/// similar to ActOnIdentifierExpr, except that instead of providing 45/// an identifier the parser provides the kind of overloaded 46/// operator that was parsed. 47Sema::OwningExprResult 48Sema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc, 49 OverloadedOperatorKind Op, 50 bool HasTrailingLParen, 51 const CXXScopeSpec &SS, 52 bool isAddressOfOperand) { 53 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op); 54 return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS, 55 isAddressOfOperand); 56} 57 58/// ActOnCXXTypeidOfType - Parse typeid( type-id ). 59Action::ExprResult 60Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, 61 bool isType, void *TyOrExpr, SourceLocation RParenLoc) { 62 NamespaceDecl *StdNs = GetStdNamespace(); 63 if (!StdNs) 64 return Diag(OpLoc, diag::err_need_header_before_typeid); 65 66 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info"); 67 Decl *TypeInfoDecl = LookupQualifiedName(StdNs, TypeInfoII, LookupTagName); 68 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl); 69 if (!TypeInfoRecordDecl) 70 return Diag(OpLoc, diag::err_need_header_before_typeid); 71 72 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl); 73 74 return new (Context) CXXTypeidExpr(isType, TyOrExpr, TypeInfoType.withConst(), 75 SourceRange(OpLoc, RParenLoc)); 76} 77 78/// ActOnCXXBoolLiteral - Parse {true,false} literals. 79Action::ExprResult 80Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 81 assert((Kind == tok::kw_true || Kind == tok::kw_false) && 82 "Unknown C++ Boolean value!"); 83 return new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc); 84} 85 86/// ActOnCXXThrow - Parse throw expressions. 87Action::ExprResult 88Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprTy *E) { 89 return new (Context) CXXThrowExpr((Expr*)E, Context.VoidTy, OpLoc); 90} 91 92Action::ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) { 93 /// C++ 9.3.2: In the body of a non-static member function, the keyword this 94 /// is a non-lvalue expression whose value is the address of the object for 95 /// which the function is called. 96 97 if (!isa<FunctionDecl>(CurContext)) { 98 Diag(ThisLoc, diag::err_invalid_this_use); 99 return ExprResult(true); 100 } 101 102 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) 103 if (MD->isInstance()) 104 return new (Context) CXXThisExpr(ThisLoc, MD->getThisType(Context)); 105 106 return Diag(ThisLoc, diag::err_invalid_this_use); 107} 108 109/// ActOnCXXTypeConstructExpr - Parse construction of a specified type. 110/// Can be interpreted either as function-style casting ("int(x)") 111/// or class type construction ("ClassType(x,y,z)") 112/// or creation of a value-initialized type ("int()"). 113Action::ExprResult 114Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep, 115 SourceLocation LParenLoc, 116 ExprTy **ExprTys, unsigned NumExprs, 117 SourceLocation *CommaLocs, 118 SourceLocation RParenLoc) { 119 assert(TypeRep && "Missing type!"); 120 QualType Ty = QualType::getFromOpaquePtr(TypeRep); 121 Expr **Exprs = (Expr**)ExprTys; 122 SourceLocation TyBeginLoc = TypeRange.getBegin(); 123 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc); 124 125 // C++ [expr.type.conv]p1: 126 // If the expression list is a single expression, the type conversion 127 // expression is equivalent (in definedness, and if defined in meaning) to the 128 // corresponding cast expression. 129 // 130 if (NumExprs == 1) { 131 if (CheckCastTypes(TypeRange, Ty, Exprs[0])) 132 return true; 133 return new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(), Ty, 134 TyBeginLoc, Exprs[0], RParenLoc); 135 } 136 137 if (const RecordType *RT = Ty->getAsRecordType()) { 138 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl()); 139 140 if (NumExprs > 1 || Record->hasUserDeclaredConstructor()) { 141 CXXConstructorDecl *Constructor 142 = PerformInitializationByConstructor(Ty, Exprs, NumExprs, 143 TypeRange.getBegin(), 144 SourceRange(TypeRange.getBegin(), 145 RParenLoc), 146 DeclarationName(), 147 IK_Direct); 148 149 if (!Constructor) 150 return true; 151 152 return new (Context) CXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc, 153 Exprs, NumExprs, RParenLoc); 154 } 155 156 // Fall through to value-initialize an object of class type that 157 // doesn't have a user-declared default constructor. 158 } 159 160 // C++ [expr.type.conv]p1: 161 // If the expression list specifies more than a single value, the type shall 162 // be a class with a suitably declared constructor. 163 // 164 if (NumExprs > 1) 165 return Diag(CommaLocs[0], diag::err_builtin_func_cast_more_than_one_arg) 166 << FullRange; 167 168 assert(NumExprs == 0 && "Expected 0 expressions"); 169 170 // C++ [expr.type.conv]p2: 171 // The expression T(), where T is a simple-type-specifier for a non-array 172 // complete object type or the (possibly cv-qualified) void type, creates an 173 // rvalue of the specified type, which is value-initialized. 174 // 175 if (Ty->isArrayType()) 176 return Diag(TyBeginLoc, diag::err_value_init_for_array_type) << FullRange; 177 if (!Ty->isDependentType() && !Ty->isVoidType() && 178 DiagnoseIncompleteType(TyBeginLoc, Ty, 179 diag::err_invalid_incomplete_type_use, FullRange)) 180 return true; 181 182 return new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc); 183} 184 185 186/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.: 187/// @code new (memory) int[size][4] @endcode 188/// or 189/// @code ::new Foo(23, "hello") @endcode 190/// For the interpretation of this heap of arguments, consult the base version. 191Action::ExprResult 192Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 193 SourceLocation PlacementLParen, 194 ExprTy **PlacementArgs, unsigned NumPlaceArgs, 195 SourceLocation PlacementRParen, bool ParenTypeId, 196 Declarator &D, SourceLocation ConstructorLParen, 197 ExprTy **ConstructorArgs, unsigned NumConsArgs, 198 SourceLocation ConstructorRParen) 199{ 200 Expr *ArraySize = 0; 201 unsigned Skip = 0; 202 // If the specified type is an array, unwrap it and save the expression. 203 if (D.getNumTypeObjects() > 0 && 204 D.getTypeObject(0).Kind == DeclaratorChunk::Array) { 205 DeclaratorChunk &Chunk = D.getTypeObject(0); 206 if (Chunk.Arr.hasStatic) 207 return Diag(Chunk.Loc, diag::err_static_illegal_in_new) 208 << D.getSourceRange(); 209 if (!Chunk.Arr.NumElts) 210 return Diag(Chunk.Loc, diag::err_array_new_needs_size) 211 << D.getSourceRange(); 212 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts); 213 Skip = 1; 214 } 215 216 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, Skip); 217 if (D.getInvalidType()) 218 return true; 219 220 if (CheckAllocatedType(AllocType, D)) 221 return true; 222 223 QualType ResultType = Context.getPointerType(AllocType); 224 225 // That every array dimension except the first is constant was already 226 // checked by the type check above. 227 228 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral 229 // or enumeration type with a non-negative value." 230 if (ArraySize) { 231 QualType SizeType = ArraySize->getType(); 232 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType()) 233 return Diag(ArraySize->getSourceRange().getBegin(), 234 diag::err_array_size_not_integral) 235 << SizeType << ArraySize->getSourceRange(); 236 // Let's see if this is a constant < 0. If so, we reject it out of hand. 237 // We don't care about special rules, so we tell the machinery it's not 238 // evaluated - it gives us a result in more cases. 239 llvm::APSInt Value; 240 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) { 241 if (Value < llvm::APSInt( 242 llvm::APInt::getNullValue(Value.getBitWidth()), false)) 243 return Diag(ArraySize->getSourceRange().getBegin(), 244 diag::err_typecheck_negative_array_size) 245 << ArraySize->getSourceRange(); 246 } 247 } 248 249 FunctionDecl *OperatorNew = 0; 250 FunctionDecl *OperatorDelete = 0; 251 Expr **PlaceArgs = (Expr**)PlacementArgs; 252 if (FindAllocationFunctions(StartLoc, 253 SourceRange(PlacementLParen, PlacementRParen), 254 UseGlobal, AllocType, ArraySize, PlaceArgs, 255 NumPlaceArgs, OperatorNew, OperatorDelete)) 256 return true; 257 258 bool Init = ConstructorLParen.isValid(); 259 // --- Choosing a constructor --- 260 // C++ 5.3.4p15 261 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid) 262 // the object is not initialized. If the object, or any part of it, is 263 // const-qualified, it's an error. 264 // 2) If T is a POD and there's an empty initializer, the object is value- 265 // initialized. 266 // 3) If T is a POD and there's one initializer argument, the object is copy- 267 // constructed. 268 // 4) If T is a POD and there's more initializer arguments, it's an error. 269 // 5) If T is not a POD, the initializer arguments are used as constructor 270 // arguments. 271 // 272 // Or by the C++0x formulation: 273 // 1) If there's no initializer, the object is default-initialized according 274 // to C++0x rules. 275 // 2) Otherwise, the object is direct-initialized. 276 CXXConstructorDecl *Constructor = 0; 277 Expr **ConsArgs = (Expr**)ConstructorArgs; 278 // FIXME: Should check for primitive/aggregate here, not record. 279 if (const RecordType *RT = AllocType->getAsRecordType()) { 280 // FIXME: This is incorrect for when there is an empty initializer and 281 // no user-defined constructor. Must zero-initialize, not default-construct. 282 Constructor = PerformInitializationByConstructor( 283 AllocType, ConsArgs, NumConsArgs, 284 D.getSourceRange().getBegin(), 285 SourceRange(D.getSourceRange().getBegin(), 286 ConstructorRParen), 287 RT->getDecl()->getDeclName(), 288 NumConsArgs != 0 ? IK_Direct : IK_Default); 289 if (!Constructor) 290 return true; 291 } else { 292 if (!Init) { 293 // FIXME: Check that no subpart is const. 294 if (AllocType.isConstQualified()) { 295 Diag(StartLoc, diag::err_new_uninitialized_const) 296 << D.getSourceRange(); 297 return true; 298 } 299 } else if (NumConsArgs == 0) { 300 // Object is value-initialized. Do nothing. 301 } else if (NumConsArgs == 1) { 302 // Object is direct-initialized. 303 // FIXME: WHAT DeclarationName do we pass in here? 304 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc, 305 DeclarationName() /*AllocType.getAsString()*/, 306 /*DirectInit=*/true)) 307 return true; 308 } else { 309 Diag(StartLoc, diag::err_builtin_direct_init_more_than_one_arg) 310 << SourceRange(ConstructorLParen, ConstructorRParen); 311 } 312 } 313 314 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16) 315 316 return new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs, 317 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init, 318 ConsArgs, NumConsArgs, OperatorDelete, ResultType, 319 StartLoc, Init ? ConstructorRParen : SourceLocation()); 320} 321 322/// CheckAllocatedType - Checks that a type is suitable as the allocated type 323/// in a new-expression. 324/// dimension off and stores the size expression in ArraySize. 325bool Sema::CheckAllocatedType(QualType AllocType, const Declarator &D) 326{ 327 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an 328 // abstract class type or array thereof. 329 // FIXME: We don't have abstract types yet. 330 // FIXME: Under C++ semantics, an incomplete object type is still an object 331 // type. This code assumes the C semantics, where it's not. 332 if (!AllocType->isObjectType()) { 333 unsigned type; // For the select in the message. 334 if (AllocType->isFunctionType()) { 335 type = 0; 336 } else if(AllocType->isIncompleteType()) { 337 type = 1; 338 } else { 339 assert(AllocType->isReferenceType() && "Unhandled non-object type."); 340 type = 2; 341 } 342 Diag(D.getSourceRange().getBegin(), diag::err_bad_new_type) 343 << AllocType << type << D.getSourceRange(); 344 return true; 345 } 346 347 // Every dimension shall be of constant size. 348 unsigned i = 1; 349 while (const ArrayType *Array = Context.getAsArrayType(AllocType)) { 350 if (!Array->isConstantArrayType()) { 351 Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst) 352 << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange(); 353 return true; 354 } 355 AllocType = Array->getElementType(); 356 ++i; 357 } 358 359 return false; 360} 361 362/// FindAllocationFunctions - Finds the overloads of operator new and delete 363/// that are appropriate for the allocation. 364bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 365 bool UseGlobal, QualType AllocType, 366 bool IsArray, Expr **PlaceArgs, 367 unsigned NumPlaceArgs, 368 FunctionDecl *&OperatorNew, 369 FunctionDecl *&OperatorDelete) 370{ 371 // --- Choosing an allocation function --- 372 // C++ 5.3.4p8 - 14 & 18 373 // 1) If UseGlobal is true, only look in the global scope. Else, also look 374 // in the scope of the allocated class. 375 // 2) If an array size is given, look for operator new[], else look for 376 // operator new. 377 // 3) The first argument is always size_t. Append the arguments from the 378 // placement form. 379 // FIXME: Also find the appropriate delete operator. 380 381 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs); 382 // We don't care about the actual value of this argument. 383 // FIXME: Should the Sema create the expression and embed it in the syntax 384 // tree? Or should the consumer just recalculate the value? 385 AllocArgs[0] = new (Context) IntegerLiteral(llvm::APInt::getNullValue( 386 Context.Target.getPointerWidth(0)), 387 Context.getSizeType(), 388 SourceLocation()); 389 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1); 390 391 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName( 392 IsArray ? OO_Array_New : OO_New); 393 if (AllocType->isRecordType() && !UseGlobal) { 394 CXXRecordDecl *Record = cast<CXXRecordType>(AllocType->getAsRecordType()) 395 ->getDecl(); 396 // FIXME: We fail to find inherited overloads. 397 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0], 398 AllocArgs.size(), Record, /*AllowMissing=*/true, 399 OperatorNew)) 400 return true; 401 } 402 if (!OperatorNew) { 403 // Didn't find a member overload. Look for a global one. 404 DeclareGlobalNewDelete(); 405 DeclContext *TUDecl = Context.getTranslationUnitDecl(); 406 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0], 407 AllocArgs.size(), TUDecl, /*AllowMissing=*/false, 408 OperatorNew)) 409 return true; 410 } 411 412 // FIXME: This is leaked on error. But so much is currently in Sema that it's 413 // easier to clean it in one go. 414 AllocArgs[0]->Destroy(Context); 415 return false; 416} 417 418/// FindAllocationOverload - Find an fitting overload for the allocation 419/// function in the specified scope. 420bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range, 421 DeclarationName Name, Expr** Args, 422 unsigned NumArgs, DeclContext *Ctx, 423 bool AllowMissing, FunctionDecl *&Operator) 424{ 425 DeclContext::lookup_iterator Alloc, AllocEnd; 426 llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Name); 427 if (Alloc == AllocEnd) { 428 if (AllowMissing) 429 return false; 430 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) 431 << Name << 0 << Range; 432 } 433 434 OverloadCandidateSet Candidates; 435 for (; Alloc != AllocEnd; ++Alloc) { 436 // Even member operator new/delete are implicitly treated as 437 // static, so don't use AddMemberCandidate. 438 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc)) 439 AddOverloadCandidate(Fn, Args, NumArgs, Candidates, 440 /*SuppressUserConversions=*/false); 441 } 442 443 // Do the resolution. 444 OverloadCandidateSet::iterator Best; 445 switch(BestViableFunction(Candidates, Best)) { 446 case OR_Success: { 447 // Got one! 448 FunctionDecl *FnDecl = Best->Function; 449 // The first argument is size_t, and the first parameter must be size_t, 450 // too. This is checked on declaration and can be assumed. (It can't be 451 // asserted on, though, since invalid decls are left in there.) 452 for (unsigned i = 1; i < NumArgs; ++i) { 453 // FIXME: Passing word to diagnostic. 454 if (PerformCopyInitialization(Args[i-1], 455 FnDecl->getParamDecl(i)->getType(), 456 "passing")) 457 return true; 458 } 459 Operator = FnDecl; 460 return false; 461 } 462 463 case OR_No_Viable_Function: 464 if (AllowMissing) 465 return false; 466 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) 467 << Name << (unsigned)Candidates.size() << Range; 468 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false); 469 return true; 470 471 case OR_Ambiguous: 472 Diag(StartLoc, diag::err_ovl_ambiguous_call) 473 << Name << Range; 474 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true); 475 return true; 476 } 477 assert(false && "Unreachable, bad result from BestViableFunction"); 478 return true; 479} 480 481 482/// DeclareGlobalNewDelete - Declare the global forms of operator new and 483/// delete. These are: 484/// @code 485/// void* operator new(std::size_t) throw(std::bad_alloc); 486/// void* operator new[](std::size_t) throw(std::bad_alloc); 487/// void operator delete(void *) throw(); 488/// void operator delete[](void *) throw(); 489/// @endcode 490/// Note that the placement and nothrow forms of new are *not* implicitly 491/// declared. Their use requires including \<new\>. 492void Sema::DeclareGlobalNewDelete() 493{ 494 if (GlobalNewDeleteDeclared) 495 return; 496 GlobalNewDeleteDeclared = true; 497 498 QualType VoidPtr = Context.getPointerType(Context.VoidTy); 499 QualType SizeT = Context.getSizeType(); 500 501 // FIXME: Exception specifications are not added. 502 DeclareGlobalAllocationFunction( 503 Context.DeclarationNames.getCXXOperatorName(OO_New), 504 VoidPtr, SizeT); 505 DeclareGlobalAllocationFunction( 506 Context.DeclarationNames.getCXXOperatorName(OO_Array_New), 507 VoidPtr, SizeT); 508 DeclareGlobalAllocationFunction( 509 Context.DeclarationNames.getCXXOperatorName(OO_Delete), 510 Context.VoidTy, VoidPtr); 511 DeclareGlobalAllocationFunction( 512 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete), 513 Context.VoidTy, VoidPtr); 514} 515 516/// DeclareGlobalAllocationFunction - Declares a single implicit global 517/// allocation function if it doesn't already exist. 518void Sema::DeclareGlobalAllocationFunction(DeclarationName Name, 519 QualType Return, QualType Argument) 520{ 521 DeclContext *GlobalCtx = Context.getTranslationUnitDecl(); 522 523 // Check if this function is already declared. 524 { 525 DeclContext::lookup_iterator Alloc, AllocEnd; 526 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name); 527 Alloc != AllocEnd; ++Alloc) { 528 // FIXME: Do we need to check for default arguments here? 529 FunctionDecl *Func = cast<FunctionDecl>(*Alloc); 530 if (Func->getNumParams() == 1 && 531 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument) 532 return; 533 } 534 } 535 536 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0); 537 FunctionDecl *Alloc = 538 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name, 539 FnType, FunctionDecl::None, false, 540 SourceLocation()); 541 Alloc->setImplicit(); 542 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(), 543 0, Argument, VarDecl::None, 0); 544 Alloc->setParams(Context, &Param, 1); 545 546 // FIXME: Also add this declaration to the IdentifierResolver, but 547 // make sure it is at the end of the chain to coincide with the 548 // global scope. 549 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc); 550} 551 552/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in: 553/// @code ::delete ptr; @endcode 554/// or 555/// @code delete [] ptr; @endcode 556Action::ExprResult 557Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, 558 bool ArrayForm, ExprTy *Operand) 559{ 560 // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type 561 // having a single conversion function to a pointer type. The result has 562 // type void." 563 // DR599 amends "pointer type" to "pointer to object type" in both cases. 564 565 Expr *Ex = (Expr *)Operand; 566 QualType Type = Ex->getType(); 567 568 if (Type->isRecordType()) { 569 // FIXME: Find that one conversion function and amend the type. 570 } 571 572 if (!Type->isPointerType()) { 573 Diag(StartLoc, diag::err_delete_operand) << Type << Ex->getSourceRange(); 574 return true; 575 } 576 577 QualType Pointee = Type->getAsPointerType()->getPointeeType(); 578 if (!Pointee->isVoidType() && 579 DiagnoseIncompleteType(StartLoc, Pointee, diag::warn_delete_incomplete, 580 Ex->getSourceRange())) 581 return true; 582 else if (!Pointee->isObjectType()) { 583 Diag(StartLoc, diag::err_delete_operand) 584 << Type << Ex->getSourceRange(); 585 return true; 586 } 587 588 // FIXME: Look up the correct operator delete overload and pass a pointer 589 // along. 590 // FIXME: Check access and ambiguity of operator delete and destructor. 591 592 return new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm, 0, 593 Ex, StartLoc); 594} 595 596 597/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 598/// C++ if/switch/while/for statement. 599/// e.g: "if (int x = f()) {...}" 600Action::ExprResult 601Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc, 602 Declarator &D, 603 SourceLocation EqualLoc, 604 ExprTy *AssignExprVal) { 605 assert(AssignExprVal && "Null assignment expression"); 606 607 // C++ 6.4p2: 608 // The declarator shall not specify a function or an array. 609 // The type-specifier-seq shall not contain typedef and shall not declare a 610 // new class or enumeration. 611 612 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 613 "Parser allowed 'typedef' as storage class of condition decl."); 614 615 QualType Ty = GetTypeForDeclarator(D, S); 616 617 if (Ty->isFunctionType()) { // The declarator shall not specify a function... 618 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl 619 // would be created and CXXConditionDeclExpr wants a VarDecl. 620 return Diag(StartLoc, diag::err_invalid_use_of_function_type) 621 << SourceRange(StartLoc, EqualLoc); 622 } else if (Ty->isArrayType()) { // ...or an array. 623 Diag(StartLoc, diag::err_invalid_use_of_array_type) 624 << SourceRange(StartLoc, EqualLoc); 625 } else if (const RecordType *RT = Ty->getAsRecordType()) { 626 RecordDecl *RD = RT->getDecl(); 627 // The type-specifier-seq shall not declare a new class... 628 if (RD->isDefinition() && (RD->getIdentifier() == 0 || S->isDeclScope(RD))) 629 Diag(RD->getLocation(), diag::err_type_defined_in_condition); 630 } else if (const EnumType *ET = Ty->getAsEnumType()) { 631 EnumDecl *ED = ET->getDecl(); 632 // ...or enumeration. 633 if (ED->isDefinition() && (ED->getIdentifier() == 0 || S->isDeclScope(ED))) 634 Diag(ED->getLocation(), diag::err_type_defined_in_condition); 635 } 636 637 DeclTy *Dcl = ActOnDeclarator(S, D, 0); 638 if (!Dcl) 639 return true; 640 AddInitializerToDecl(Dcl, ExprArg(*this, AssignExprVal)); 641 642 // Mark this variable as one that is declared within a conditional. 643 if (VarDecl *VD = dyn_cast<VarDecl>((Decl *)Dcl)) 644 VD->setDeclaredInCondition(true); 645 646 return new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, 647 cast<VarDecl>(static_cast<Decl *>(Dcl))); 648} 649 650/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid. 651bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) { 652 // C++ 6.4p4: 653 // The value of a condition that is an initialized declaration in a statement 654 // other than a switch statement is the value of the declared variable 655 // implicitly converted to type bool. If that conversion is ill-formed, the 656 // program is ill-formed. 657 // The value of a condition that is an expression is the value of the 658 // expression, implicitly converted to bool. 659 // 660 return PerformContextuallyConvertToBool(CondExpr); 661} 662 663/// Helper function to determine whether this is the (deprecated) C++ 664/// conversion from a string literal to a pointer to non-const char or 665/// non-const wchar_t (for narrow and wide string literals, 666/// respectively). 667bool 668Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) { 669 // Look inside the implicit cast, if it exists. 670 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From)) 671 From = Cast->getSubExpr(); 672 673 // A string literal (2.13.4) that is not a wide string literal can 674 // be converted to an rvalue of type "pointer to char"; a wide 675 // string literal can be converted to an rvalue of type "pointer 676 // to wchar_t" (C++ 4.2p2). 677 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From)) 678 if (const PointerType *ToPtrType = ToType->getAsPointerType()) 679 if (const BuiltinType *ToPointeeType 680 = ToPtrType->getPointeeType()->getAsBuiltinType()) { 681 // This conversion is considered only when there is an 682 // explicit appropriate pointer target type (C++ 4.2p2). 683 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 && 684 ((StrLit->isWide() && ToPointeeType->isWideCharType()) || 685 (!StrLit->isWide() && 686 (ToPointeeType->getKind() == BuiltinType::Char_U || 687 ToPointeeType->getKind() == BuiltinType::Char_S)))) 688 return true; 689 } 690 691 return false; 692} 693 694/// PerformImplicitConversion - Perform an implicit conversion of the 695/// expression From to the type ToType. Returns true if there was an 696/// error, false otherwise. The expression From is replaced with the 697/// converted expression. Flavor is the kind of conversion we're 698/// performing, used in the error message. If @p AllowExplicit, 699/// explicit user-defined conversions are permitted. 700bool 701Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 702 const char *Flavor, bool AllowExplicit) 703{ 704 ImplicitConversionSequence ICS = TryImplicitConversion(From, ToType, false, 705 AllowExplicit); 706 return PerformImplicitConversion(From, ToType, ICS, Flavor); 707} 708 709/// PerformImplicitConversion - Perform an implicit conversion of the 710/// expression From to the type ToType using the pre-computed implicit 711/// conversion sequence ICS. Returns true if there was an error, false 712/// otherwise. The expression From is replaced with the converted 713/// expression. Flavor is the kind of conversion we're performing, 714/// used in the error message. 715bool 716Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 717 const ImplicitConversionSequence &ICS, 718 const char* Flavor) { 719 switch (ICS.ConversionKind) { 720 case ImplicitConversionSequence::StandardConversion: 721 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor)) 722 return true; 723 break; 724 725 case ImplicitConversionSequence::UserDefinedConversion: 726 // FIXME: This is, of course, wrong. We'll need to actually call 727 // the constructor or conversion operator, and then cope with the 728 // standard conversions. 729 ImpCastExprToType(From, ToType.getNonReferenceType(), 730 ToType->isReferenceType()); 731 return false; 732 733 case ImplicitConversionSequence::EllipsisConversion: 734 assert(false && "Cannot perform an ellipsis conversion"); 735 return false; 736 737 case ImplicitConversionSequence::BadConversion: 738 return true; 739 } 740 741 // Everything went well. 742 return false; 743} 744 745/// PerformImplicitConversion - Perform an implicit conversion of the 746/// expression From to the type ToType by following the standard 747/// conversion sequence SCS. Returns true if there was an error, false 748/// otherwise. The expression From is replaced with the converted 749/// expression. Flavor is the context in which we're performing this 750/// conversion, for use in error messages. 751bool 752Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 753 const StandardConversionSequence& SCS, 754 const char *Flavor) { 755 // Overall FIXME: we are recomputing too many types here and doing 756 // far too much extra work. What this means is that we need to keep 757 // track of more information that is computed when we try the 758 // implicit conversion initially, so that we don't need to recompute 759 // anything here. 760 QualType FromType = From->getType(); 761 762 if (SCS.CopyConstructor) { 763 // FIXME: Create a temporary object by calling the copy 764 // constructor. 765 ImpCastExprToType(From, ToType.getNonReferenceType(), 766 ToType->isReferenceType()); 767 return false; 768 } 769 770 // Perform the first implicit conversion. 771 switch (SCS.First) { 772 case ICK_Identity: 773 case ICK_Lvalue_To_Rvalue: 774 // Nothing to do. 775 break; 776 777 case ICK_Array_To_Pointer: 778 if (FromType->isOverloadType()) { 779 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true); 780 if (!Fn) 781 return true; 782 783 FixOverloadedFunctionReference(From, Fn); 784 FromType = From->getType(); 785 } else { 786 FromType = Context.getArrayDecayedType(FromType); 787 } 788 ImpCastExprToType(From, FromType); 789 break; 790 791 case ICK_Function_To_Pointer: 792 FromType = Context.getPointerType(FromType); 793 ImpCastExprToType(From, FromType); 794 break; 795 796 default: 797 assert(false && "Improper first standard conversion"); 798 break; 799 } 800 801 // Perform the second implicit conversion 802 switch (SCS.Second) { 803 case ICK_Identity: 804 // Nothing to do. 805 break; 806 807 case ICK_Integral_Promotion: 808 case ICK_Floating_Promotion: 809 case ICK_Integral_Conversion: 810 case ICK_Floating_Conversion: 811 case ICK_Floating_Integral: 812 FromType = ToType.getUnqualifiedType(); 813 ImpCastExprToType(From, FromType); 814 break; 815 816 case ICK_Pointer_Conversion: 817 if (SCS.IncompatibleObjC) { 818 // Diagnose incompatible Objective-C conversions 819 Diag(From->getSourceRange().getBegin(), 820 diag::ext_typecheck_convert_incompatible_pointer) 821 << From->getType() << ToType << Flavor 822 << From->getSourceRange(); 823 } 824 825 if (CheckPointerConversion(From, ToType)) 826 return true; 827 ImpCastExprToType(From, ToType); 828 break; 829 830 case ICK_Pointer_Member: 831 if (CheckMemberPointerConversion(From, ToType)) 832 return true; 833 ImpCastExprToType(From, ToType); 834 break; 835 836 case ICK_Boolean_Conversion: 837 FromType = Context.BoolTy; 838 ImpCastExprToType(From, FromType); 839 break; 840 841 default: 842 assert(false && "Improper second standard conversion"); 843 break; 844 } 845 846 switch (SCS.Third) { 847 case ICK_Identity: 848 // Nothing to do. 849 break; 850 851 case ICK_Qualification: 852 ImpCastExprToType(From, ToType.getNonReferenceType(), 853 ToType->isReferenceType()); 854 break; 855 856 default: 857 assert(false && "Improper second standard conversion"); 858 break; 859 } 860 861 return false; 862} 863 864Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT, 865 SourceLocation KWLoc, 866 SourceLocation LParen, 867 TypeTy *Ty, 868 SourceLocation RParen) { 869 // FIXME: Some of the type traits have requirements. Interestingly, only the 870 // __is_base_of requirement is explicitly stated to be diagnosed. Indeed, 871 // G++ accepts __is_pod(Incomplete) without complaints, and claims that the 872 // type is indeed a POD. 873 874 // There is no point in eagerly computing the value. The traits are designed 875 // to be used from type trait templates, so Ty will be a template parameter 876 // 99% of the time. 877 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, 878 QualType::getFromOpaquePtr(Ty), 879 RParen, Context.BoolTy)); 880} 881 882QualType Sema::CheckPointerToMemberOperands( 883 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) 884{ 885 const char *OpSpelling = isIndirect ? "->*" : ".*"; 886 // C++ 5.5p2 887 // The binary operator .* [p3: ->*] binds its second operand, which shall 888 // be of type "pointer to member of T" (where T is a completely-defined 889 // class type) [...] 890 QualType RType = rex->getType(); 891 const MemberPointerType *MemPtr = RType->getAsMemberPointerType(); 892 if (!MemPtr || MemPtr->getClass()->isIncompleteType()) { 893 Diag(Loc, diag::err_bad_memptr_rhs) 894 << OpSpelling << RType << rex->getSourceRange(); 895 return QualType(); 896 } 897 QualType Class(MemPtr->getClass(), 0); 898 899 // C++ 5.5p2 900 // [...] to its first operand, which shall be of class T or of a class of 901 // which T is an unambiguous and accessible base class. [p3: a pointer to 902 // such a class] 903 QualType LType = lex->getType(); 904 if (isIndirect) { 905 if (const PointerType *Ptr = LType->getAsPointerType()) 906 LType = Ptr->getPointeeType().getNonReferenceType(); 907 else { 908 Diag(Loc, diag::err_bad_memptr_lhs) 909 << OpSpelling << 1 << LType << lex->getSourceRange(); 910 return QualType(); 911 } 912 } 913 914 if (Context.getCanonicalType(Class).getUnqualifiedType() != 915 Context.getCanonicalType(LType).getUnqualifiedType()) { 916 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 917 /*DetectVirtual=*/false); 918 // FIXME: Would it be useful to print full ambiguity paths, 919 // or is that overkill? 920 if (!IsDerivedFrom(LType, Class, Paths) || 921 Paths.isAmbiguous(Context.getCanonicalType(Class))) { 922 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling 923 << (int)isIndirect << lex->getType() << lex->getSourceRange(); 924 return QualType(); 925 } 926 } 927 928 // C++ 5.5p2 929 // The result is an object or a function of the type specified by the 930 // second operand. 931 // The cv qualifiers are the union of those in the pointer and the left side, 932 // in accordance with 5.5p5 and 5.2.5. 933 // FIXME: This returns a dereferenced member function pointer as a normal 934 // function type. However, the only operation valid on such functions is 935 // calling them. There's also a GCC extension to get a function pointer to 936 // the thing, which is another complication, because this type - unlike the 937 // type that is the result of this expression - takes the class as the first 938 // argument. 939 // We probably need a "MemberFunctionClosureType" or something like that. 940 QualType Result = MemPtr->getPointeeType(); 941 if (LType.isConstQualified()) 942 Result.addConst(); 943 if (LType.isVolatileQualified()) 944 Result.addVolatile(); 945 return Result; 946} 947