SemaExpr.cpp revision 6994e1a96ebc69f63b92df433d30f578f3d92f1d
1//===--- SemaExpr.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 expressions. 11// 12//===----------------------------------------------------------------------===// 13 14#include "Sema.h" 15#include "SemaInit.h" 16#include "Lookup.h" 17#include "clang/Analysis/AnalysisContext.h" 18#include "clang/AST/ASTContext.h" 19#include "clang/AST/DeclObjC.h" 20#include "clang/AST/DeclTemplate.h" 21#include "clang/AST/ExprCXX.h" 22#include "clang/AST/ExprObjC.h" 23#include "clang/Basic/PartialDiagnostic.h" 24#include "clang/Basic/SourceManager.h" 25#include "clang/Basic/TargetInfo.h" 26#include "clang/Lex/LiteralSupport.h" 27#include "clang/Lex/Preprocessor.h" 28#include "clang/Parse/DeclSpec.h" 29#include "clang/Parse/Designator.h" 30#include "clang/Parse/Scope.h" 31#include "clang/Parse/Template.h" 32using namespace clang; 33 34 35/// \brief Determine whether the use of this declaration is valid, and 36/// emit any corresponding diagnostics. 37/// 38/// This routine diagnoses various problems with referencing 39/// declarations that can occur when using a declaration. For example, 40/// it might warn if a deprecated or unavailable declaration is being 41/// used, or produce an error (and return true) if a C++0x deleted 42/// function is being used. 43/// 44/// If IgnoreDeprecated is set to true, this should not want about deprecated 45/// decls. 46/// 47/// \returns true if there was an error (this declaration cannot be 48/// referenced), false otherwise. 49/// 50bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) { 51 // See if the decl is deprecated. 52 if (D->getAttr<DeprecatedAttr>()) { 53 EmitDeprecationWarning(D, Loc); 54 } 55 56 // See if the decl is unavailable 57 if (D->getAttr<UnavailableAttr>()) { 58 Diag(Loc, diag::warn_unavailable) << D->getDeclName(); 59 Diag(D->getLocation(), diag::note_unavailable_here) << 0; 60 } 61 62 // See if this is a deleted function. 63 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 64 if (FD->isDeleted()) { 65 Diag(Loc, diag::err_deleted_function_use); 66 Diag(D->getLocation(), diag::note_unavailable_here) << true; 67 return true; 68 } 69 } 70 71 return false; 72} 73 74/// DiagnoseSentinelCalls - This routine checks on method dispatch calls 75/// (and other functions in future), which have been declared with sentinel 76/// attribute. It warns if call does not have the sentinel argument. 77/// 78void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 79 Expr **Args, unsigned NumArgs) { 80 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 81 if (!attr) 82 return; 83 int sentinelPos = attr->getSentinel(); 84 int nullPos = attr->getNullPos(); 85 86 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common 87 // base class. Then we won't be needing two versions of the same code. 88 unsigned int i = 0; 89 bool warnNotEnoughArgs = false; 90 int isMethod = 0; 91 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 92 // skip over named parameters. 93 ObjCMethodDecl::param_iterator P, E = MD->param_end(); 94 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) { 95 if (nullPos) 96 --nullPos; 97 else 98 ++i; 99 } 100 warnNotEnoughArgs = (P != E || i >= NumArgs); 101 isMethod = 1; 102 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 103 // skip over named parameters. 104 ObjCMethodDecl::param_iterator P, E = FD->param_end(); 105 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) { 106 if (nullPos) 107 --nullPos; 108 else 109 ++i; 110 } 111 warnNotEnoughArgs = (P != E || i >= NumArgs); 112 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) { 113 // block or function pointer call. 114 QualType Ty = V->getType(); 115 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) { 116 const FunctionType *FT = Ty->isFunctionPointerType() 117 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>() 118 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>(); 119 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) { 120 unsigned NumArgsInProto = Proto->getNumArgs(); 121 unsigned k; 122 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) { 123 if (nullPos) 124 --nullPos; 125 else 126 ++i; 127 } 128 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs); 129 } 130 if (Ty->isBlockPointerType()) 131 isMethod = 2; 132 } else 133 return; 134 } else 135 return; 136 137 if (warnNotEnoughArgs) { 138 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 139 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod; 140 return; 141 } 142 int sentinel = i; 143 while (sentinelPos > 0 && i < NumArgs-1) { 144 --sentinelPos; 145 ++i; 146 } 147 if (sentinelPos > 0) { 148 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 149 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod; 150 return; 151 } 152 while (i < NumArgs-1) { 153 ++i; 154 ++sentinel; 155 } 156 Expr *sentinelExpr = Args[sentinel]; 157 if (sentinelExpr && (!isa<GNUNullExpr>(sentinelExpr) && 158 (!sentinelExpr->getType()->isPointerType() || 159 !sentinelExpr->isNullPointerConstant(Context, 160 Expr::NPC_ValueDependentIsNull)))) { 161 Diag(Loc, diag::warn_missing_sentinel) << isMethod; 162 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod; 163 } 164 return; 165} 166 167SourceRange Sema::getExprRange(ExprTy *E) const { 168 Expr *Ex = (Expr *)E; 169 return Ex? Ex->getSourceRange() : SourceRange(); 170} 171 172//===----------------------------------------------------------------------===// 173// Standard Promotions and Conversions 174//===----------------------------------------------------------------------===// 175 176/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 177void Sema::DefaultFunctionArrayConversion(Expr *&E) { 178 QualType Ty = E->getType(); 179 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 180 181 if (Ty->isFunctionType()) 182 ImpCastExprToType(E, Context.getPointerType(Ty), 183 CastExpr::CK_FunctionToPointerDecay); 184 else if (Ty->isArrayType()) { 185 // In C90 mode, arrays only promote to pointers if the array expression is 186 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 187 // type 'array of type' is converted to an expression that has type 'pointer 188 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 189 // that has type 'array of type' ...". The relevant change is "an lvalue" 190 // (C90) to "an expression" (C99). 191 // 192 // C++ 4.2p1: 193 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 194 // T" can be converted to an rvalue of type "pointer to T". 195 // 196 if (getLangOptions().C99 || getLangOptions().CPlusPlus || 197 E->isLvalue(Context) == Expr::LV_Valid) 198 ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 199 CastExpr::CK_ArrayToPointerDecay); 200 } 201} 202 203/// UsualUnaryConversions - Performs various conversions that are common to most 204/// operators (C99 6.3). The conversions of array and function types are 205/// sometimes surpressed. For example, the array->pointer conversion doesn't 206/// apply if the array is an argument to the sizeof or address (&) operators. 207/// In these instances, this routine should *not* be called. 208Expr *Sema::UsualUnaryConversions(Expr *&Expr) { 209 QualType Ty = Expr->getType(); 210 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 211 212 // C99 6.3.1.1p2: 213 // 214 // The following may be used in an expression wherever an int or 215 // unsigned int may be used: 216 // - an object or expression with an integer type whose integer 217 // conversion rank is less than or equal to the rank of int 218 // and unsigned int. 219 // - A bit-field of type _Bool, int, signed int, or unsigned int. 220 // 221 // If an int can represent all values of the original type, the 222 // value is converted to an int; otherwise, it is converted to an 223 // unsigned int. These are called the integer promotions. All 224 // other types are unchanged by the integer promotions. 225 QualType PTy = Context.isPromotableBitField(Expr); 226 if (!PTy.isNull()) { 227 ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast); 228 return Expr; 229 } 230 if (Ty->isPromotableIntegerType()) { 231 QualType PT = Context.getPromotedIntegerType(Ty); 232 ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast); 233 return Expr; 234 } 235 236 DefaultFunctionArrayConversion(Expr); 237 return Expr; 238} 239 240/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 241/// do not have a prototype. Arguments that have type float are promoted to 242/// double. All other argument types are converted by UsualUnaryConversions(). 243void Sema::DefaultArgumentPromotion(Expr *&Expr) { 244 QualType Ty = Expr->getType(); 245 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 246 247 // If this is a 'float' (CVR qualified or typedef) promote to double. 248 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 249 if (BT->getKind() == BuiltinType::Float) 250 return ImpCastExprToType(Expr, Context.DoubleTy, 251 CastExpr::CK_FloatingCast); 252 253 UsualUnaryConversions(Expr); 254} 255 256/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 257/// will warn if the resulting type is not a POD type, and rejects ObjC 258/// interfaces passed by value. This returns true if the argument type is 259/// completely illegal. 260bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) { 261 DefaultArgumentPromotion(Expr); 262 263 if (Expr->getType()->isObjCInterfaceType() && 264 DiagRuntimeBehavior(Expr->getLocStart(), 265 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 266 << Expr->getType() << CT)) 267 return true; 268 269 if (!Expr->getType()->isPODType() && 270 DiagRuntimeBehavior(Expr->getLocStart(), 271 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 272 << Expr->getType() << CT)) 273 return true; 274 275 return false; 276} 277 278 279/// UsualArithmeticConversions - Performs various conversions that are common to 280/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 281/// routine returns the first non-arithmetic type found. The client is 282/// responsible for emitting appropriate error diagnostics. 283/// FIXME: verify the conversion rules for "complex int" are consistent with 284/// GCC. 285QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr, 286 bool isCompAssign) { 287 if (!isCompAssign) 288 UsualUnaryConversions(lhsExpr); 289 290 UsualUnaryConversions(rhsExpr); 291 292 // For conversion purposes, we ignore any qualifiers. 293 // For example, "const float" and "float" are equivalent. 294 QualType lhs = 295 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType(); 296 QualType rhs = 297 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType(); 298 299 // If both types are identical, no conversion is needed. 300 if (lhs == rhs) 301 return lhs; 302 303 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 304 // The caller can deal with this (e.g. pointer + int). 305 if (!lhs->isArithmeticType() || !rhs->isArithmeticType()) 306 return lhs; 307 308 // Perform bitfield promotions. 309 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr); 310 if (!LHSBitfieldPromoteTy.isNull()) 311 lhs = LHSBitfieldPromoteTy; 312 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr); 313 if (!RHSBitfieldPromoteTy.isNull()) 314 rhs = RHSBitfieldPromoteTy; 315 316 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs); 317 if (!isCompAssign) 318 ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown); 319 ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown); 320 return destType; 321} 322 323//===----------------------------------------------------------------------===// 324// Semantic Analysis for various Expression Types 325//===----------------------------------------------------------------------===// 326 327 328/// ActOnStringLiteral - The specified tokens were lexed as pasted string 329/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 330/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 331/// multiple tokens. However, the common case is that StringToks points to one 332/// string. 333/// 334Action::OwningExprResult 335Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) { 336 assert(NumStringToks && "Must have at least one string!"); 337 338 StringLiteralParser Literal(StringToks, NumStringToks, PP); 339 if (Literal.hadError) 340 return ExprError(); 341 342 llvm::SmallVector<SourceLocation, 4> StringTokLocs; 343 for (unsigned i = 0; i != NumStringToks; ++i) 344 StringTokLocs.push_back(StringToks[i].getLocation()); 345 346 QualType StrTy = Context.CharTy; 347 if (Literal.AnyWide) StrTy = Context.getWCharType(); 348 if (Literal.Pascal) StrTy = Context.UnsignedCharTy; 349 350 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 351 if (getLangOptions().CPlusPlus) 352 StrTy.addConst(); 353 354 // Get an array type for the string, according to C99 6.4.5. This includes 355 // the nul terminator character as well as the string length for pascal 356 // strings. 357 StrTy = Context.getConstantArrayType(StrTy, 358 llvm::APInt(32, Literal.GetNumStringChars()+1), 359 ArrayType::Normal, 0); 360 361 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 362 return Owned(StringLiteral::Create(Context, Literal.GetString(), 363 Literal.GetStringLength(), 364 Literal.AnyWide, StrTy, 365 &StringTokLocs[0], 366 StringTokLocs.size())); 367} 368 369/// ShouldSnapshotBlockValueReference - Return true if a reference inside of 370/// CurBlock to VD should cause it to be snapshotted (as we do for auto 371/// variables defined outside the block) or false if this is not needed (e.g. 372/// for values inside the block or for globals). 373/// 374/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records 375/// up-to-date. 376/// 377static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock, 378 ValueDecl *VD) { 379 // If the value is defined inside the block, we couldn't snapshot it even if 380 // we wanted to. 381 if (CurBlock->TheDecl == VD->getDeclContext()) 382 return false; 383 384 // If this is an enum constant or function, it is constant, don't snapshot. 385 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD)) 386 return false; 387 388 // If this is a reference to an extern, static, or global variable, no need to 389 // snapshot it. 390 // FIXME: What about 'const' variables in C++? 391 if (const VarDecl *Var = dyn_cast<VarDecl>(VD)) 392 if (!Var->hasLocalStorage()) 393 return false; 394 395 // Blocks that have these can't be constant. 396 CurBlock->hasBlockDeclRefExprs = true; 397 398 // If we have nested blocks, the decl may be declared in an outer block (in 399 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may 400 // be defined outside all of the current blocks (in which case the blocks do 401 // all get the bit). Walk the nesting chain. 402 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock; 403 NextBlock = NextBlock->PrevBlockInfo) { 404 // If we found the defining block for the variable, don't mark the block as 405 // having a reference outside it. 406 if (NextBlock->TheDecl == VD->getDeclContext()) 407 break; 408 409 // Otherwise, the DeclRef from the inner block causes the outer one to need 410 // a snapshot as well. 411 NextBlock->hasBlockDeclRefExprs = true; 412 } 413 414 return true; 415} 416 417 418 419/// BuildDeclRefExpr - Build a DeclRefExpr. 420Sema::OwningExprResult 421Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, SourceLocation Loc, 422 const CXXScopeSpec *SS) { 423 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) { 424 Diag(Loc, 425 diag::err_auto_variable_cannot_appear_in_own_initializer) 426 << D->getDeclName(); 427 return ExprError(); 428 } 429 430 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 431 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) { 432 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) { 433 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) { 434 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function) 435 << D->getIdentifier() << FD->getDeclName(); 436 Diag(D->getLocation(), diag::note_local_variable_declared_here) 437 << D->getIdentifier(); 438 return ExprError(); 439 } 440 } 441 } 442 } 443 444 MarkDeclarationReferenced(Loc, D); 445 446 return Owned(DeclRefExpr::Create(Context, 447 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0, 448 SS? SS->getRange() : SourceRange(), 449 D, Loc, Ty)); 450} 451 452/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or 453/// variable corresponding to the anonymous union or struct whose type 454/// is Record. 455static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context, 456 RecordDecl *Record) { 457 assert(Record->isAnonymousStructOrUnion() && 458 "Record must be an anonymous struct or union!"); 459 460 // FIXME: Once Decls are directly linked together, this will be an O(1) 461 // operation rather than a slow walk through DeclContext's vector (which 462 // itself will be eliminated). DeclGroups might make this even better. 463 DeclContext *Ctx = Record->getDeclContext(); 464 for (DeclContext::decl_iterator D = Ctx->decls_begin(), 465 DEnd = Ctx->decls_end(); 466 D != DEnd; ++D) { 467 if (*D == Record) { 468 // The object for the anonymous struct/union directly 469 // follows its type in the list of declarations. 470 ++D; 471 assert(D != DEnd && "Missing object for anonymous record"); 472 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed"); 473 return *D; 474 } 475 } 476 477 assert(false && "Missing object for anonymous record"); 478 return 0; 479} 480 481/// \brief Given a field that represents a member of an anonymous 482/// struct/union, build the path from that field's context to the 483/// actual member. 484/// 485/// Construct the sequence of field member references we'll have to 486/// perform to get to the field in the anonymous union/struct. The 487/// list of members is built from the field outward, so traverse it 488/// backwards to go from an object in the current context to the field 489/// we found. 490/// 491/// \returns The variable from which the field access should begin, 492/// for an anonymous struct/union that is not a member of another 493/// class. Otherwise, returns NULL. 494VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field, 495 llvm::SmallVectorImpl<FieldDecl *> &Path) { 496 assert(Field->getDeclContext()->isRecord() && 497 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion() 498 && "Field must be stored inside an anonymous struct or union"); 499 500 Path.push_back(Field); 501 VarDecl *BaseObject = 0; 502 DeclContext *Ctx = Field->getDeclContext(); 503 do { 504 RecordDecl *Record = cast<RecordDecl>(Ctx); 505 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record); 506 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject)) 507 Path.push_back(AnonField); 508 else { 509 BaseObject = cast<VarDecl>(AnonObject); 510 break; 511 } 512 Ctx = Ctx->getParent(); 513 } while (Ctx->isRecord() && 514 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()); 515 516 return BaseObject; 517} 518 519Sema::OwningExprResult 520Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc, 521 FieldDecl *Field, 522 Expr *BaseObjectExpr, 523 SourceLocation OpLoc) { 524 llvm::SmallVector<FieldDecl *, 4> AnonFields; 525 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field, 526 AnonFields); 527 528 // Build the expression that refers to the base object, from 529 // which we will build a sequence of member references to each 530 // of the anonymous union objects and, eventually, the field we 531 // found via name lookup. 532 bool BaseObjectIsPointer = false; 533 Qualifiers BaseQuals; 534 if (BaseObject) { 535 // BaseObject is an anonymous struct/union variable (and is, 536 // therefore, not part of another non-anonymous record). 537 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context); 538 MarkDeclarationReferenced(Loc, BaseObject); 539 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(), 540 SourceLocation()); 541 BaseQuals 542 = Context.getCanonicalType(BaseObject->getType()).getQualifiers(); 543 } else if (BaseObjectExpr) { 544 // The caller provided the base object expression. Determine 545 // whether its a pointer and whether it adds any qualifiers to the 546 // anonymous struct/union fields we're looking into. 547 QualType ObjectType = BaseObjectExpr->getType(); 548 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) { 549 BaseObjectIsPointer = true; 550 ObjectType = ObjectPtr->getPointeeType(); 551 } 552 BaseQuals 553 = Context.getCanonicalType(ObjectType).getQualifiers(); 554 } else { 555 // We've found a member of an anonymous struct/union that is 556 // inside a non-anonymous struct/union, so in a well-formed 557 // program our base object expression is "this". 558 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) { 559 if (!MD->isStatic()) { 560 QualType AnonFieldType 561 = Context.getTagDeclType( 562 cast<RecordDecl>(AnonFields.back()->getDeclContext())); 563 QualType ThisType = Context.getTagDeclType(MD->getParent()); 564 if ((Context.getCanonicalType(AnonFieldType) 565 == Context.getCanonicalType(ThisType)) || 566 IsDerivedFrom(ThisType, AnonFieldType)) { 567 // Our base object expression is "this". 568 BaseObjectExpr = new (Context) CXXThisExpr(Loc, 569 MD->getThisType(Context), 570 /*isImplicit=*/true); 571 BaseObjectIsPointer = true; 572 } 573 } else { 574 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method) 575 << Field->getDeclName()); 576 } 577 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers()); 578 } 579 580 if (!BaseObjectExpr) 581 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use) 582 << Field->getDeclName()); 583 } 584 585 // Build the implicit member references to the field of the 586 // anonymous struct/union. 587 Expr *Result = BaseObjectExpr; 588 Qualifiers ResultQuals = BaseQuals; 589 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator 590 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend(); 591 FI != FIEnd; ++FI) { 592 QualType MemberType = (*FI)->getType(); 593 Qualifiers MemberTypeQuals = 594 Context.getCanonicalType(MemberType).getQualifiers(); 595 596 // CVR attributes from the base are picked up by members, 597 // except that 'mutable' members don't pick up 'const'. 598 if ((*FI)->isMutable()) 599 ResultQuals.removeConst(); 600 601 // GC attributes are never picked up by members. 602 ResultQuals.removeObjCGCAttr(); 603 604 // TR 18037 does not allow fields to be declared with address spaces. 605 assert(!MemberTypeQuals.hasAddressSpace()); 606 607 Qualifiers NewQuals = ResultQuals + MemberTypeQuals; 608 if (NewQuals != MemberTypeQuals) 609 MemberType = Context.getQualifiedType(MemberType, NewQuals); 610 611 MarkDeclarationReferenced(Loc, *FI); 612 PerformObjectMemberConversion(Result, *FI); 613 // FIXME: Might this end up being a qualified name? 614 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI, 615 OpLoc, MemberType); 616 BaseObjectIsPointer = false; 617 ResultQuals = NewQuals; 618 } 619 620 return Owned(Result); 621} 622 623/// Decomposes the given name into a DeclarationName, its location, and 624/// possibly a list of template arguments. 625/// 626/// If this produces template arguments, it is permitted to call 627/// DecomposeTemplateName. 628/// 629/// This actually loses a lot of source location information for 630/// non-standard name kinds; we should consider preserving that in 631/// some way. 632static void DecomposeUnqualifiedId(Sema &SemaRef, 633 const UnqualifiedId &Id, 634 TemplateArgumentListInfo &Buffer, 635 DeclarationName &Name, 636 SourceLocation &NameLoc, 637 const TemplateArgumentListInfo *&TemplateArgs) { 638 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 639 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 640 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 641 642 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef, 643 Id.TemplateId->getTemplateArgs(), 644 Id.TemplateId->NumArgs); 645 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer); 646 TemplateArgsPtr.release(); 647 648 TemplateName TName = 649 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>(); 650 651 Name = SemaRef.Context.getNameForTemplate(TName); 652 NameLoc = Id.TemplateId->TemplateNameLoc; 653 TemplateArgs = &Buffer; 654 } else { 655 Name = SemaRef.GetNameFromUnqualifiedId(Id); 656 NameLoc = Id.StartLocation; 657 TemplateArgs = 0; 658 } 659} 660 661/// Decompose the given template name into a list of lookup results. 662/// 663/// The unqualified ID must name a non-dependent template, which can 664/// be more easily tested by checking whether DecomposeUnqualifiedId 665/// found template arguments. 666static void DecomposeTemplateName(LookupResult &R, const UnqualifiedId &Id) { 667 assert(Id.getKind() == UnqualifiedId::IK_TemplateId); 668 TemplateName TName = 669 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>(); 670 671 if (TemplateDecl *TD = TName.getAsTemplateDecl()) 672 R.addDecl(TD); 673 else if (OverloadedTemplateStorage *OT = TName.getAsOverloadedTemplate()) 674 for (OverloadedTemplateStorage::iterator I = OT->begin(), E = OT->end(); 675 I != E; ++I) 676 R.addDecl(*I); 677 678 R.resolveKind(); 679} 680 681static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) { 682 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(), 683 E = Record->bases_end(); I != E; ++I) { 684 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType()); 685 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>(); 686 if (!BaseRT) return false; 687 688 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl()); 689 if (!BaseRecord->isDefinition() || 690 !IsFullyFormedScope(SemaRef, BaseRecord)) 691 return false; 692 } 693 694 return true; 695} 696 697/// Determines whether we can lookup this id-expression now or whether 698/// we have to wait until template instantiation is complete. 699static bool IsDependentIdExpression(Sema &SemaRef, const CXXScopeSpec &SS) { 700 DeclContext *DC = SemaRef.computeDeclContext(SS, false); 701 702 // If the qualifier scope isn't computable, it's definitely dependent. 703 if (!DC) return true; 704 705 // If the qualifier scope doesn't name a record, we can always look into it. 706 if (!isa<CXXRecordDecl>(DC)) return false; 707 708 // We can't look into record types unless they're fully-formed. 709 if (!IsFullyFormedScope(SemaRef, cast<CXXRecordDecl>(DC))) return true; 710 711 return false; 712} 713 714/// Determines if the given class is provably not derived from all of 715/// the prospective base classes. 716static bool IsProvablyNotDerivedFrom(Sema &SemaRef, 717 CXXRecordDecl *Record, 718 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) { 719 if (Bases.count(Record->getCanonicalDecl())) 720 return false; 721 722 RecordDecl *RD = Record->getDefinition(SemaRef.Context); 723 if (!RD) return false; 724 Record = cast<CXXRecordDecl>(RD); 725 726 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(), 727 E = Record->bases_end(); I != E; ++I) { 728 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType()); 729 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>(); 730 if (!BaseRT) return false; 731 732 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl()); 733 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases)) 734 return false; 735 } 736 737 return true; 738} 739 740/// Determines if this is an instance member of a class. 741static bool IsInstanceMember(NamedDecl *D) { 742 assert(D->isCXXClassMember() && 743 "checking whether non-member is instance member"); 744 745 if (isa<FieldDecl>(D)) return true; 746 747 if (isa<CXXMethodDecl>(D)) 748 return !cast<CXXMethodDecl>(D)->isStatic(); 749 750 if (isa<FunctionTemplateDecl>(D)) { 751 D = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 752 return !cast<CXXMethodDecl>(D)->isStatic(); 753 } 754 755 return false; 756} 757 758enum IMAKind { 759 /// The reference is definitely not an instance member access. 760 IMA_Static, 761 762 /// The reference may be an implicit instance member access. 763 IMA_Mixed, 764 765 /// The reference may be to an instance member, but it is invalid if 766 /// so, because the context is not an instance method. 767 IMA_Mixed_StaticContext, 768 769 /// The reference may be to an instance member, but it is invalid if 770 /// so, because the context is from an unrelated class. 771 IMA_Mixed_Unrelated, 772 773 /// The reference is definitely an implicit instance member access. 774 IMA_Instance, 775 776 /// The reference may be to an unresolved using declaration. 777 IMA_Unresolved, 778 779 /// The reference may be to an unresolved using declaration and the 780 /// context is not an instance method. 781 IMA_Unresolved_StaticContext, 782 783 /// The reference is to a member of an anonymous structure in a 784 /// non-class context. 785 IMA_AnonymousMember, 786 787 /// All possible referrents are instance members and the current 788 /// context is not an instance method. 789 IMA_Error_StaticContext, 790 791 /// All possible referrents are instance members of an unrelated 792 /// class. 793 IMA_Error_Unrelated 794}; 795 796/// The given lookup names class member(s) and is not being used for 797/// an address-of-member expression. Classify the type of access 798/// according to whether it's possible that this reference names an 799/// instance member. This is best-effort; it is okay to 800/// conservatively answer "yes", in which case some errors will simply 801/// not be caught until template-instantiation. 802static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef, 803 const LookupResult &R) { 804 assert(!R.empty() && (*R.begin())->isCXXClassMember()); 805 806 bool isStaticContext = 807 (!isa<CXXMethodDecl>(SemaRef.CurContext) || 808 cast<CXXMethodDecl>(SemaRef.CurContext)->isStatic()); 809 810 if (R.isUnresolvableResult()) 811 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved; 812 813 // Collect all the declaring classes of instance members we find. 814 bool hasNonInstance = false; 815 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes; 816 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 817 NamedDecl *D = (*I)->getUnderlyingDecl(); 818 if (IsInstanceMember(D)) { 819 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext()); 820 821 // If this is a member of an anonymous record, move out to the 822 // innermost non-anonymous struct or union. If there isn't one, 823 // that's a special case. 824 while (R->isAnonymousStructOrUnion()) { 825 R = dyn_cast<CXXRecordDecl>(R->getParent()); 826 if (!R) return IMA_AnonymousMember; 827 } 828 Classes.insert(R->getCanonicalDecl()); 829 } 830 else 831 hasNonInstance = true; 832 } 833 834 // If we didn't find any instance members, it can't be an implicit 835 // member reference. 836 if (Classes.empty()) 837 return IMA_Static; 838 839 // If the current context is not an instance method, it can't be 840 // an implicit member reference. 841 if (isStaticContext) 842 return (hasNonInstance ? IMA_Mixed_StaticContext : IMA_Error_StaticContext); 843 844 // If we can prove that the current context is unrelated to all the 845 // declaring classes, it can't be an implicit member reference (in 846 // which case it's an error if any of those members are selected). 847 if (IsProvablyNotDerivedFrom(SemaRef, 848 cast<CXXMethodDecl>(SemaRef.CurContext)->getParent(), 849 Classes)) 850 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated); 851 852 return (hasNonInstance ? IMA_Mixed : IMA_Instance); 853} 854 855/// Diagnose a reference to a field with no object available. 856static void DiagnoseInstanceReference(Sema &SemaRef, 857 const CXXScopeSpec &SS, 858 const LookupResult &R) { 859 SourceLocation Loc = R.getNameLoc(); 860 SourceRange Range(Loc); 861 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin()); 862 863 if (R.getAsSingle<FieldDecl>()) { 864 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) { 865 if (MD->isStatic()) { 866 // "invalid use of member 'x' in static member function" 867 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method) 868 << Range << R.getLookupName(); 869 return; 870 } 871 } 872 873 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use) 874 << R.getLookupName() << Range; 875 return; 876 } 877 878 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range; 879} 880 881/// Diagnose an empty lookup. 882/// 883/// \return false if new lookup candidates were found 884bool Sema::DiagnoseEmptyLookup(Scope *S, const CXXScopeSpec &SS, 885 LookupResult &R) { 886 DeclarationName Name = R.getLookupName(); 887 888 unsigned diagnostic = diag::err_undeclared_var_use; 889 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 890 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 891 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 892 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 893 diagnostic = diag::err_undeclared_use; 894 diagnostic_suggest = diag::err_undeclared_use_suggest; 895 } 896 897 // If the original lookup was an unqualified lookup, fake an 898 // unqualified lookup. This is useful when (for example) the 899 // original lookup would not have found something because it was a 900 // dependent name. 901 for (DeclContext *DC = SS.isEmpty()? CurContext : 0; 902 DC; DC = DC->getParent()) { 903 if (isa<CXXRecordDecl>(DC)) { 904 LookupQualifiedName(R, DC); 905 906 if (!R.empty()) { 907 // Don't give errors about ambiguities in this lookup. 908 R.suppressDiagnostics(); 909 910 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 911 bool isInstance = CurMethod && 912 CurMethod->isInstance() && 913 DC == CurMethod->getParent(); 914 915 // Give a code modification hint to insert 'this->'. 916 // TODO: fixit for inserting 'Base<T>::' in the other cases. 917 // Actually quite difficult! 918 if (isInstance) 919 Diag(R.getNameLoc(), diagnostic) << Name 920 << CodeModificationHint::CreateInsertion(R.getNameLoc(), 921 "this->"); 922 else 923 Diag(R.getNameLoc(), diagnostic) << Name; 924 925 // Do we really want to note all of these? 926 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 927 Diag((*I)->getLocation(), diag::note_dependent_var_use); 928 929 // Tell the callee to try to recover. 930 return false; 931 } 932 } 933 } 934 935 // We didn't find anything, so try to correct for a typo. 936 if (S && CorrectTypo(R, S, &SS)) { 937 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) { 938 if (SS.isEmpty()) 939 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName() 940 << CodeModificationHint::CreateReplacement(R.getNameLoc(), 941 R.getLookupName().getAsString()); 942 else 943 Diag(R.getNameLoc(), diag::err_no_member_suggest) 944 << Name << computeDeclContext(SS, false) << R.getLookupName() 945 << SS.getRange() 946 << CodeModificationHint::CreateReplacement(R.getNameLoc(), 947 R.getLookupName().getAsString()); 948 if (NamedDecl *ND = R.getAsSingle<NamedDecl>()) 949 Diag(ND->getLocation(), diag::note_previous_decl) 950 << ND->getDeclName(); 951 952 // Tell the callee to try to recover. 953 return false; 954 } 955 956 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) { 957 // FIXME: If we ended up with a typo for a type name or 958 // Objective-C class name, we're in trouble because the parser 959 // is in the wrong place to recover. Suggest the typo 960 // correction, but don't make it a fix-it since we're not going 961 // to recover well anyway. 962 if (SS.isEmpty()) 963 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName(); 964 else 965 Diag(R.getNameLoc(), diag::err_no_member_suggest) 966 << Name << computeDeclContext(SS, false) << R.getLookupName() 967 << SS.getRange(); 968 969 // Don't try to recover; it won't work. 970 return true; 971 } 972 973 R.clear(); 974 } 975 976 // Emit a special diagnostic for failed member lookups. 977 // FIXME: computing the declaration context might fail here (?) 978 if (!SS.isEmpty()) { 979 Diag(R.getNameLoc(), diag::err_no_member) 980 << Name << computeDeclContext(SS, false) 981 << SS.getRange(); 982 return true; 983 } 984 985 // Give up, we can't recover. 986 Diag(R.getNameLoc(), diagnostic) << Name; 987 return true; 988} 989 990Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S, 991 const CXXScopeSpec &SS, 992 UnqualifiedId &Id, 993 bool HasTrailingLParen, 994 bool isAddressOfOperand) { 995 assert(!(isAddressOfOperand && HasTrailingLParen) && 996 "cannot be direct & operand and have a trailing lparen"); 997 998 if (SS.isInvalid()) 999 return ExprError(); 1000 1001 TemplateArgumentListInfo TemplateArgsBuffer; 1002 1003 // Decompose the UnqualifiedId into the following data. 1004 DeclarationName Name; 1005 SourceLocation NameLoc; 1006 const TemplateArgumentListInfo *TemplateArgs; 1007 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, 1008 Name, NameLoc, TemplateArgs); 1009 1010 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1011 1012 // C++ [temp.dep.expr]p3: 1013 // An id-expression is type-dependent if it contains: 1014 // -- an identifier that was declared with a dependent type, 1015 // (note: handled after lookup) 1016 // -- a template-id that is dependent, 1017 // (note: handled in BuildTemplateIdExpr) 1018 // -- a conversion-function-id that specifies a dependent type, 1019 // -- a nested-name-specifier that contains a class-name that 1020 // names a dependent type. 1021 // Determine whether this is a member of an unknown specialization; 1022 // we need to handle these differently. 1023 if ((Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 1024 Name.getCXXNameType()->isDependentType()) || 1025 (SS.isSet() && IsDependentIdExpression(*this, SS))) { 1026 return ActOnDependentIdExpression(SS, Name, NameLoc, 1027 isAddressOfOperand, 1028 TemplateArgs); 1029 } 1030 1031 // Perform the required lookup. 1032 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName); 1033 if (TemplateArgs) { 1034 // Just re-use the lookup done by isTemplateName. 1035 DecomposeTemplateName(R, Id); 1036 } else { 1037 bool IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl()); 1038 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 1039 1040 // If this reference is in an Objective-C method, then we need to do 1041 // some special Objective-C lookup, too. 1042 if (IvarLookupFollowUp) { 1043 OwningExprResult E(LookupInObjCMethod(R, S, II, true)); 1044 if (E.isInvalid()) 1045 return ExprError(); 1046 1047 Expr *Ex = E.takeAs<Expr>(); 1048 if (Ex) return Owned(Ex); 1049 } 1050 } 1051 1052 if (R.isAmbiguous()) 1053 return ExprError(); 1054 1055 // Determine whether this name might be a candidate for 1056 // argument-dependent lookup. 1057 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 1058 1059 if (R.empty() && !ADL) { 1060 // Otherwise, this could be an implicitly declared function reference (legal 1061 // in C90, extension in C99, forbidden in C++). 1062 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) { 1063 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 1064 if (D) R.addDecl(D); 1065 } 1066 1067 // If this name wasn't predeclared and if this is not a function 1068 // call, diagnose the problem. 1069 if (R.empty()) { 1070 if (DiagnoseEmptyLookup(S, SS, R)) 1071 return ExprError(); 1072 1073 assert(!R.empty() && 1074 "DiagnoseEmptyLookup returned false but added no results"); 1075 1076 // If we found an Objective-C instance variable, let 1077 // LookupInObjCMethod build the appropriate expression to 1078 // reference the ivar. 1079 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 1080 R.clear(); 1081 OwningExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 1082 assert(E.isInvalid() || E.get()); 1083 return move(E); 1084 } 1085 } 1086 } 1087 1088 // This is guaranteed from this point on. 1089 assert(!R.empty() || ADL); 1090 1091 if (VarDecl *Var = R.getAsSingle<VarDecl>()) { 1092 // Warn about constructs like: 1093 // if (void *X = foo()) { ... } else { X }. 1094 // In the else block, the pointer is always false. 1095 1096 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) { 1097 Scope *CheckS = S; 1098 while (CheckS && CheckS->getControlParent()) { 1099 if (CheckS->isWithinElse() && 1100 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) { 1101 ExprError(Diag(NameLoc, diag::warn_value_always_zero) 1102 << Var->getDeclName() 1103 << (Var->getType()->isPointerType()? 2 : 1104 Var->getType()->isBooleanType()? 1 : 0)); 1105 break; 1106 } 1107 1108 // Move to the parent of this scope. 1109 CheckS = CheckS->getParent(); 1110 } 1111 } 1112 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) { 1113 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) { 1114 // C99 DR 316 says that, if a function type comes from a 1115 // function definition (without a prototype), that type is only 1116 // used for checking compatibility. Therefore, when referencing 1117 // the function, we pretend that we don't have the full function 1118 // type. 1119 if (DiagnoseUseOfDecl(Func, NameLoc)) 1120 return ExprError(); 1121 1122 QualType T = Func->getType(); 1123 QualType NoProtoType = T; 1124 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>()) 1125 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType()); 1126 return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS); 1127 } 1128 } 1129 1130 // Check whether this might be a C++ implicit instance member access. 1131 // C++ [expr.prim.general]p6: 1132 // Within the definition of a non-static member function, an 1133 // identifier that names a non-static member is transformed to a 1134 // class member access expression. 1135 // But note that &SomeClass::foo is grammatically distinct, even 1136 // though we don't parse it that way. 1137 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 1138 bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty()); 1139 if (!isAbstractMemberPointer) 1140 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs); 1141 } 1142 1143 if (TemplateArgs) 1144 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs); 1145 1146 return BuildDeclarationNameExpr(SS, R, ADL); 1147} 1148 1149/// Builds an expression which might be an implicit member expression. 1150Sema::OwningExprResult 1151Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, 1152 LookupResult &R, 1153 const TemplateArgumentListInfo *TemplateArgs) { 1154 switch (ClassifyImplicitMemberAccess(*this, R)) { 1155 case IMA_Instance: 1156 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true); 1157 1158 case IMA_AnonymousMember: 1159 assert(R.isSingleResult()); 1160 return BuildAnonymousStructUnionMemberReference(R.getNameLoc(), 1161 R.getAsSingle<FieldDecl>()); 1162 1163 case IMA_Mixed: 1164 case IMA_Mixed_Unrelated: 1165 case IMA_Unresolved: 1166 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false); 1167 1168 case IMA_Static: 1169 case IMA_Mixed_StaticContext: 1170 case IMA_Unresolved_StaticContext: 1171 if (TemplateArgs) 1172 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs); 1173 return BuildDeclarationNameExpr(SS, R, false); 1174 1175 case IMA_Error_StaticContext: 1176 case IMA_Error_Unrelated: 1177 DiagnoseInstanceReference(*this, SS, R); 1178 return ExprError(); 1179 } 1180 1181 llvm_unreachable("unexpected instance member access kind"); 1182 return ExprError(); 1183} 1184 1185/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 1186/// declaration name, generally during template instantiation. 1187/// There's a large number of things which don't need to be done along 1188/// this path. 1189Sema::OwningExprResult 1190Sema::BuildQualifiedDeclarationNameExpr(const CXXScopeSpec &SS, 1191 DeclarationName Name, 1192 SourceLocation NameLoc) { 1193 DeclContext *DC; 1194 if (!(DC = computeDeclContext(SS, false)) || 1195 DC->isDependentContext() || 1196 RequireCompleteDeclContext(SS)) 1197 return BuildDependentDeclRefExpr(SS, Name, NameLoc, 0); 1198 1199 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName); 1200 LookupQualifiedName(R, DC); 1201 1202 if (R.isAmbiguous()) 1203 return ExprError(); 1204 1205 if (R.empty()) { 1206 Diag(NameLoc, diag::err_no_member) << Name << DC << SS.getRange(); 1207 return ExprError(); 1208 } 1209 1210 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false); 1211} 1212 1213/// LookupInObjCMethod - The parser has read a name in, and Sema has 1214/// detected that we're currently inside an ObjC method. Perform some 1215/// additional lookup. 1216/// 1217/// Ideally, most of this would be done by lookup, but there's 1218/// actually quite a lot of extra work involved. 1219/// 1220/// Returns a null sentinel to indicate trivial success. 1221Sema::OwningExprResult 1222Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 1223 IdentifierInfo *II, 1224 bool AllowBuiltinCreation) { 1225 SourceLocation Loc = Lookup.getNameLoc(); 1226 1227 // There are two cases to handle here. 1) scoped lookup could have failed, 1228 // in which case we should look for an ivar. 2) scoped lookup could have 1229 // found a decl, but that decl is outside the current instance method (i.e. 1230 // a global variable). In these two cases, we do a lookup for an ivar with 1231 // this name, if the lookup sucedes, we replace it our current decl. 1232 1233 // If we're in a class method, we don't normally want to look for 1234 // ivars. But if we don't find anything else, and there's an 1235 // ivar, that's an error. 1236 bool IsClassMethod = getCurMethodDecl()->isClassMethod(); 1237 1238 bool LookForIvars; 1239 if (Lookup.empty()) 1240 LookForIvars = true; 1241 else if (IsClassMethod) 1242 LookForIvars = false; 1243 else 1244 LookForIvars = (Lookup.isSingleResult() && 1245 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 1246 1247 if (LookForIvars) { 1248 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface(); 1249 ObjCInterfaceDecl *ClassDeclared; 1250 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 1251 // Diagnose using an ivar in a class method. 1252 if (IsClassMethod) 1253 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 1254 << IV->getDeclName()); 1255 1256 // If we're referencing an invalid decl, just return this as a silent 1257 // error node. The error diagnostic was already emitted on the decl. 1258 if (IV->isInvalidDecl()) 1259 return ExprError(); 1260 1261 // Check if referencing a field with __attribute__((deprecated)). 1262 if (DiagnoseUseOfDecl(IV, Loc)) 1263 return ExprError(); 1264 1265 // Diagnose the use of an ivar outside of the declaring class. 1266 if (IV->getAccessControl() == ObjCIvarDecl::Private && 1267 ClassDeclared != IFace) 1268 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 1269 1270 // FIXME: This should use a new expr for a direct reference, don't 1271 // turn this into Self->ivar, just return a BareIVarExpr or something. 1272 IdentifierInfo &II = Context.Idents.get("self"); 1273 UnqualifiedId SelfName; 1274 SelfName.setIdentifier(&II, SourceLocation()); 1275 CXXScopeSpec SelfScopeSpec; 1276 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, 1277 SelfName, false, false); 1278 MarkDeclarationReferenced(Loc, IV); 1279 return Owned(new (Context) 1280 ObjCIvarRefExpr(IV, IV->getType(), Loc, 1281 SelfExpr.takeAs<Expr>(), true, true)); 1282 } 1283 } else if (getCurMethodDecl()->isInstanceMethod()) { 1284 // We should warn if a local variable hides an ivar. 1285 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface(); 1286 ObjCInterfaceDecl *ClassDeclared; 1287 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 1288 if (IV->getAccessControl() != ObjCIvarDecl::Private || 1289 IFace == ClassDeclared) 1290 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 1291 } 1292 } 1293 1294 // Needed to implement property "super.method" notation. 1295 if (Lookup.empty() && II->isStr("super")) { 1296 QualType T; 1297 1298 if (getCurMethodDecl()->isInstanceMethod()) 1299 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType( 1300 getCurMethodDecl()->getClassInterface())); 1301 else 1302 T = Context.getObjCClassType(); 1303 return Owned(new (Context) ObjCSuperExpr(Loc, T)); 1304 } 1305 if (Lookup.empty() && II && AllowBuiltinCreation) { 1306 // FIXME. Consolidate this with similar code in LookupName. 1307 if (unsigned BuiltinID = II->getBuiltinID()) { 1308 if (!(getLangOptions().CPlusPlus && 1309 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 1310 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 1311 S, Lookup.isForRedeclaration(), 1312 Lookup.getNameLoc()); 1313 if (D) Lookup.addDecl(D); 1314 } 1315 } 1316 } 1317 // Sentinel value saying that we didn't do anything special. 1318 return Owned((Expr*) 0); 1319} 1320 1321/// \brief Cast member's object to its own class if necessary. 1322bool 1323Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) { 1324 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member)) 1325 if (CXXRecordDecl *RD = 1326 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) { 1327 QualType DestType = 1328 Context.getCanonicalType(Context.getTypeDeclType(RD)); 1329 if (DestType->isDependentType() || From->getType()->isDependentType()) 1330 return false; 1331 QualType FromRecordType = From->getType(); 1332 QualType DestRecordType = DestType; 1333 if (FromRecordType->getAs<PointerType>()) { 1334 DestType = Context.getPointerType(DestType); 1335 FromRecordType = FromRecordType->getPointeeType(); 1336 } 1337 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) && 1338 CheckDerivedToBaseConversion(FromRecordType, 1339 DestRecordType, 1340 From->getSourceRange().getBegin(), 1341 From->getSourceRange())) 1342 return true; 1343 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase, 1344 /*isLvalue=*/true); 1345 } 1346 return false; 1347} 1348 1349/// \brief Build a MemberExpr AST node. 1350static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow, 1351 const CXXScopeSpec &SS, ValueDecl *Member, 1352 SourceLocation Loc, QualType Ty, 1353 const TemplateArgumentListInfo *TemplateArgs = 0) { 1354 NestedNameSpecifier *Qualifier = 0; 1355 SourceRange QualifierRange; 1356 if (SS.isSet()) { 1357 Qualifier = (NestedNameSpecifier *) SS.getScopeRep(); 1358 QualifierRange = SS.getRange(); 1359 } 1360 1361 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange, 1362 Member, Loc, TemplateArgs, Ty); 1363} 1364 1365/// Builds an implicit member access expression. The current context 1366/// is known to be an instance method, and the given unqualified lookup 1367/// set is known to contain only instance members, at least one of which 1368/// is from an appropriate type. 1369Sema::OwningExprResult 1370Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS, 1371 LookupResult &R, 1372 const TemplateArgumentListInfo *TemplateArgs, 1373 bool IsKnownInstance) { 1374 assert(!R.empty() && !R.isAmbiguous()); 1375 1376 SourceLocation Loc = R.getNameLoc(); 1377 1378 // We may have found a field within an anonymous union or struct 1379 // (C++ [class.union]). 1380 // FIXME: This needs to happen post-isImplicitMemberReference? 1381 // FIXME: template-ids inside anonymous structs? 1382 if (FieldDecl *FD = R.getAsSingle<FieldDecl>()) 1383 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion()) 1384 return BuildAnonymousStructUnionMemberReference(Loc, FD); 1385 1386 // If this is known to be an instance access, go ahead and build a 1387 // 'this' expression now. 1388 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context); 1389 Expr *This = 0; // null signifies implicit access 1390 if (IsKnownInstance) { 1391 SourceLocation Loc = R.getNameLoc(); 1392 if (SS.getRange().isValid()) 1393 Loc = SS.getRange().getBegin(); 1394 This = new (Context) CXXThisExpr(Loc, ThisType, /*isImplicit=*/true); 1395 } 1396 1397 return BuildMemberReferenceExpr(ExprArg(*this, This), ThisType, 1398 /*OpLoc*/ SourceLocation(), 1399 /*IsArrow*/ true, 1400 SS, 1401 /*FirstQualifierInScope*/ 0, 1402 R, TemplateArgs); 1403} 1404 1405bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 1406 const LookupResult &R, 1407 bool HasTrailingLParen) { 1408 // Only when used directly as the postfix-expression of a call. 1409 if (!HasTrailingLParen) 1410 return false; 1411 1412 // Never if a scope specifier was provided. 1413 if (SS.isSet()) 1414 return false; 1415 1416 // Only in C++ or ObjC++. 1417 if (!getLangOptions().CPlusPlus) 1418 return false; 1419 1420 // Turn off ADL when we find certain kinds of declarations during 1421 // normal lookup: 1422 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 1423 NamedDecl *D = *I; 1424 1425 // C++0x [basic.lookup.argdep]p3: 1426 // -- a declaration of a class member 1427 // Since using decls preserve this property, we check this on the 1428 // original decl. 1429 if (D->isCXXClassMember()) 1430 return false; 1431 1432 // C++0x [basic.lookup.argdep]p3: 1433 // -- a block-scope function declaration that is not a 1434 // using-declaration 1435 // NOTE: we also trigger this for function templates (in fact, we 1436 // don't check the decl type at all, since all other decl types 1437 // turn off ADL anyway). 1438 if (isa<UsingShadowDecl>(D)) 1439 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 1440 else if (D->getDeclContext()->isFunctionOrMethod()) 1441 return false; 1442 1443 // C++0x [basic.lookup.argdep]p3: 1444 // -- a declaration that is neither a function or a function 1445 // template 1446 // And also for builtin functions. 1447 if (isa<FunctionDecl>(D)) { 1448 FunctionDecl *FDecl = cast<FunctionDecl>(D); 1449 1450 // But also builtin functions. 1451 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 1452 return false; 1453 } else if (!isa<FunctionTemplateDecl>(D)) 1454 return false; 1455 } 1456 1457 return true; 1458} 1459 1460 1461/// Diagnoses obvious problems with the use of the given declaration 1462/// as an expression. This is only actually called for lookups that 1463/// were not overloaded, and it doesn't promise that the declaration 1464/// will in fact be used. 1465static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 1466 if (isa<TypedefDecl>(D)) { 1467 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 1468 return true; 1469 } 1470 1471 if (isa<ObjCInterfaceDecl>(D)) { 1472 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 1473 return true; 1474 } 1475 1476 if (isa<NamespaceDecl>(D)) { 1477 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 1478 return true; 1479 } 1480 1481 return false; 1482} 1483 1484Sema::OwningExprResult 1485Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 1486 LookupResult &R, 1487 bool NeedsADL) { 1488 // If this is a single, fully-resolved result and we don't need ADL, 1489 // just build an ordinary singleton decl ref. 1490 if (!NeedsADL && R.isSingleResult()) 1491 return BuildDeclarationNameExpr(SS, R.getNameLoc(), R.getFoundDecl()); 1492 1493 // We only need to check the declaration if there's exactly one 1494 // result, because in the overloaded case the results can only be 1495 // functions and function templates. 1496 if (R.isSingleResult() && 1497 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 1498 return ExprError(); 1499 1500 // Otherwise, just build an unresolved lookup expression. Suppress 1501 // any lookup-related diagnostics; we'll hash these out later, when 1502 // we've picked a target. 1503 R.suppressDiagnostics(); 1504 1505 bool Dependent 1506 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0); 1507 UnresolvedLookupExpr *ULE 1508 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(), 1509 (NestedNameSpecifier*) SS.getScopeRep(), 1510 SS.getRange(), 1511 R.getLookupName(), R.getNameLoc(), 1512 NeedsADL, R.isOverloadedResult()); 1513 ULE->addDecls(R.begin(), R.end()); 1514 1515 return Owned(ULE); 1516} 1517 1518 1519/// \brief Complete semantic analysis for a reference to the given declaration. 1520Sema::OwningExprResult 1521Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 1522 SourceLocation Loc, NamedDecl *D) { 1523 assert(D && "Cannot refer to a NULL declaration"); 1524 assert(!isa<FunctionTemplateDecl>(D) && 1525 "Cannot refer unambiguously to a function template"); 1526 1527 if (CheckDeclInExpr(*this, Loc, D)) 1528 return ExprError(); 1529 1530 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 1531 // Specifically diagnose references to class templates that are missing 1532 // a template argument list. 1533 Diag(Loc, diag::err_template_decl_ref) 1534 << Template << SS.getRange(); 1535 Diag(Template->getLocation(), diag::note_template_decl_here); 1536 return ExprError(); 1537 } 1538 1539 // Make sure that we're referring to a value. 1540 ValueDecl *VD = dyn_cast<ValueDecl>(D); 1541 if (!VD) { 1542 Diag(Loc, diag::err_ref_non_value) 1543 << D << SS.getRange(); 1544 Diag(D->getLocation(), diag::note_declared_at); 1545 return ExprError(); 1546 } 1547 1548 // Check whether this declaration can be used. Note that we suppress 1549 // this check when we're going to perform argument-dependent lookup 1550 // on this function name, because this might not be the function 1551 // that overload resolution actually selects. 1552 if (DiagnoseUseOfDecl(VD, Loc)) 1553 return ExprError(); 1554 1555 // Only create DeclRefExpr's for valid Decl's. 1556 if (VD->isInvalidDecl()) 1557 return ExprError(); 1558 1559 // If the identifier reference is inside a block, and it refers to a value 1560 // that is outside the block, create a BlockDeclRefExpr instead of a 1561 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when 1562 // the block is formed. 1563 // 1564 // We do not do this for things like enum constants, global variables, etc, 1565 // as they do not get snapshotted. 1566 // 1567 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) { 1568 if (VD->getType().getTypePtr()->isVariablyModifiedType()) { 1569 Diag(Loc, diag::err_ref_vm_type); 1570 Diag(D->getLocation(), diag::note_declared_at); 1571 return ExprError(); 1572 } 1573 1574 if (VD->getType()->isArrayType()) { 1575 Diag(Loc, diag::err_ref_array_type); 1576 Diag(D->getLocation(), diag::note_declared_at); 1577 return ExprError(); 1578 } 1579 1580 MarkDeclarationReferenced(Loc, VD); 1581 QualType ExprTy = VD->getType().getNonReferenceType(); 1582 // The BlocksAttr indicates the variable is bound by-reference. 1583 if (VD->getAttr<BlocksAttr>()) 1584 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true)); 1585 // This is to record that a 'const' was actually synthesize and added. 1586 bool constAdded = !ExprTy.isConstQualified(); 1587 // Variable will be bound by-copy, make it const within the closure. 1588 1589 ExprTy.addConst(); 1590 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false, 1591 constAdded)); 1592 } 1593 // If this reference is not in a block or if the referenced variable is 1594 // within the block, create a normal DeclRefExpr. 1595 1596 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, &SS); 1597} 1598 1599Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, 1600 tok::TokenKind Kind) { 1601 PredefinedExpr::IdentType IT; 1602 1603 switch (Kind) { 1604 default: assert(0 && "Unknown simple primary expr!"); 1605 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 1606 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 1607 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 1608 } 1609 1610 // Pre-defined identifiers are of type char[x], where x is the length of the 1611 // string. 1612 1613 Decl *currentDecl = getCurFunctionOrMethodDecl(); 1614 if (!currentDecl) { 1615 Diag(Loc, diag::ext_predef_outside_function); 1616 currentDecl = Context.getTranslationUnitDecl(); 1617 } 1618 1619 QualType ResTy; 1620 if (cast<DeclContext>(currentDecl)->isDependentContext()) { 1621 ResTy = Context.DependentTy; 1622 } else { 1623 unsigned Length = 1624 PredefinedExpr::ComputeName(Context, IT, currentDecl).length(); 1625 1626 llvm::APInt LengthI(32, Length + 1); 1627 ResTy = Context.CharTy.withConst(); 1628 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); 1629 } 1630 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT)); 1631} 1632 1633Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) { 1634 llvm::SmallString<16> CharBuffer; 1635 CharBuffer.resize(Tok.getLength()); 1636 const char *ThisTokBegin = &CharBuffer[0]; 1637 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin); 1638 1639 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength, 1640 Tok.getLocation(), PP); 1641 if (Literal.hadError()) 1642 return ExprError(); 1643 1644 QualType Ty; 1645 if (!getLangOptions().CPlusPlus) 1646 Ty = Context.IntTy; // 'x' and L'x' -> int in C. 1647 else if (Literal.isWide()) 1648 Ty = Context.WCharTy; // L'x' -> wchar_t in C++. 1649 else 1650 Ty = Context.CharTy; // 'x' -> char in C++ 1651 1652 return Owned(new (Context) CharacterLiteral(Literal.getValue(), 1653 Literal.isWide(), 1654 Ty, Tok.getLocation())); 1655} 1656 1657Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) { 1658 // Fast path for a single digit (which is quite common). A single digit 1659 // cannot have a trigraph, escaped newline, radix prefix, or type suffix. 1660 if (Tok.getLength() == 1) { 1661 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 1662 unsigned IntSize = Context.Target.getIntWidth(); 1663 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'), 1664 Context.IntTy, Tok.getLocation())); 1665 } 1666 1667 llvm::SmallString<512> IntegerBuffer; 1668 // Add padding so that NumericLiteralParser can overread by one character. 1669 IntegerBuffer.resize(Tok.getLength()+1); 1670 const char *ThisTokBegin = &IntegerBuffer[0]; 1671 1672 // Get the spelling of the token, which eliminates trigraphs, etc. 1673 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin); 1674 1675 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength, 1676 Tok.getLocation(), PP); 1677 if (Literal.hadError) 1678 return ExprError(); 1679 1680 Expr *Res; 1681 1682 if (Literal.isFloatingLiteral()) { 1683 QualType Ty; 1684 if (Literal.isFloat) 1685 Ty = Context.FloatTy; 1686 else if (!Literal.isLong) 1687 Ty = Context.DoubleTy; 1688 else 1689 Ty = Context.LongDoubleTy; 1690 1691 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty); 1692 1693 using llvm::APFloat; 1694 APFloat Val(Format); 1695 1696 APFloat::opStatus result = Literal.GetFloatValue(Val); 1697 1698 // Overflow is always an error, but underflow is only an error if 1699 // we underflowed to zero (APFloat reports denormals as underflow). 1700 if ((result & APFloat::opOverflow) || 1701 ((result & APFloat::opUnderflow) && Val.isZero())) { 1702 unsigned diagnostic; 1703 llvm::SmallVector<char, 20> buffer; 1704 if (result & APFloat::opOverflow) { 1705 diagnostic = diag::err_float_overflow; 1706 APFloat::getLargest(Format).toString(buffer); 1707 } else { 1708 diagnostic = diag::err_float_underflow; 1709 APFloat::getSmallest(Format).toString(buffer); 1710 } 1711 1712 Diag(Tok.getLocation(), diagnostic) 1713 << Ty 1714 << llvm::StringRef(buffer.data(), buffer.size()); 1715 } 1716 1717 bool isExact = (result == APFloat::opOK); 1718 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation()); 1719 1720 } else if (!Literal.isIntegerLiteral()) { 1721 return ExprError(); 1722 } else { 1723 QualType Ty; 1724 1725 // long long is a C99 feature. 1726 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x && 1727 Literal.isLongLong) 1728 Diag(Tok.getLocation(), diag::ext_longlong); 1729 1730 // Get the value in the widest-possible width. 1731 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0); 1732 1733 if (Literal.GetIntegerValue(ResultVal)) { 1734 // If this value didn't fit into uintmax_t, warn and force to ull. 1735 Diag(Tok.getLocation(), diag::warn_integer_too_large); 1736 Ty = Context.UnsignedLongLongTy; 1737 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 1738 "long long is not intmax_t?"); 1739 } else { 1740 // If this value fits into a ULL, try to figure out what else it fits into 1741 // according to the rules of C99 6.4.4.1p5. 1742 1743 // Octal, Hexadecimal, and integers with a U suffix are allowed to 1744 // be an unsigned int. 1745 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 1746 1747 // Check from smallest to largest, picking the smallest type we can. 1748 unsigned Width = 0; 1749 if (!Literal.isLong && !Literal.isLongLong) { 1750 // Are int/unsigned possibilities? 1751 unsigned IntSize = Context.Target.getIntWidth(); 1752 1753 // Does it fit in a unsigned int? 1754 if (ResultVal.isIntN(IntSize)) { 1755 // Does it fit in a signed int? 1756 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 1757 Ty = Context.IntTy; 1758 else if (AllowUnsigned) 1759 Ty = Context.UnsignedIntTy; 1760 Width = IntSize; 1761 } 1762 } 1763 1764 // Are long/unsigned long possibilities? 1765 if (Ty.isNull() && !Literal.isLongLong) { 1766 unsigned LongSize = Context.Target.getLongWidth(); 1767 1768 // Does it fit in a unsigned long? 1769 if (ResultVal.isIntN(LongSize)) { 1770 // Does it fit in a signed long? 1771 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 1772 Ty = Context.LongTy; 1773 else if (AllowUnsigned) 1774 Ty = Context.UnsignedLongTy; 1775 Width = LongSize; 1776 } 1777 } 1778 1779 // Finally, check long long if needed. 1780 if (Ty.isNull()) { 1781 unsigned LongLongSize = Context.Target.getLongLongWidth(); 1782 1783 // Does it fit in a unsigned long long? 1784 if (ResultVal.isIntN(LongLongSize)) { 1785 // Does it fit in a signed long long? 1786 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0) 1787 Ty = Context.LongLongTy; 1788 else if (AllowUnsigned) 1789 Ty = Context.UnsignedLongLongTy; 1790 Width = LongLongSize; 1791 } 1792 } 1793 1794 // If we still couldn't decide a type, we probably have something that 1795 // does not fit in a signed long long, but has no U suffix. 1796 if (Ty.isNull()) { 1797 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed); 1798 Ty = Context.UnsignedLongLongTy; 1799 Width = Context.Target.getLongLongWidth(); 1800 } 1801 1802 if (ResultVal.getBitWidth() != Width) 1803 ResultVal.trunc(Width); 1804 } 1805 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation()); 1806 } 1807 1808 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 1809 if (Literal.isImaginary) 1810 Res = new (Context) ImaginaryLiteral(Res, 1811 Context.getComplexType(Res->getType())); 1812 1813 return Owned(Res); 1814} 1815 1816Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L, 1817 SourceLocation R, ExprArg Val) { 1818 Expr *E = Val.takeAs<Expr>(); 1819 assert((E != 0) && "ActOnParenExpr() missing expr"); 1820 return Owned(new (Context) ParenExpr(L, R, E)); 1821} 1822 1823/// The UsualUnaryConversions() function is *not* called by this routine. 1824/// See C99 6.3.2.1p[2-4] for more details. 1825bool Sema::CheckSizeOfAlignOfOperand(QualType exprType, 1826 SourceLocation OpLoc, 1827 const SourceRange &ExprRange, 1828 bool isSizeof) { 1829 if (exprType->isDependentType()) 1830 return false; 1831 1832 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 1833 // the result is the size of the referenced type." 1834 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 1835 // result shall be the alignment of the referenced type." 1836 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>()) 1837 exprType = Ref->getPointeeType(); 1838 1839 // C99 6.5.3.4p1: 1840 if (exprType->isFunctionType()) { 1841 // alignof(function) is allowed as an extension. 1842 if (isSizeof) 1843 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange; 1844 return false; 1845 } 1846 1847 // Allow sizeof(void)/alignof(void) as an extension. 1848 if (exprType->isVoidType()) { 1849 Diag(OpLoc, diag::ext_sizeof_void_type) 1850 << (isSizeof ? "sizeof" : "__alignof") << ExprRange; 1851 return false; 1852 } 1853 1854 if (RequireCompleteType(OpLoc, exprType, 1855 PDiag(diag::err_sizeof_alignof_incomplete_type) 1856 << int(!isSizeof) << ExprRange)) 1857 return true; 1858 1859 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode. 1860 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) { 1861 Diag(OpLoc, diag::err_sizeof_nonfragile_interface) 1862 << exprType << isSizeof << ExprRange; 1863 return true; 1864 } 1865 1866 return false; 1867} 1868 1869bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc, 1870 const SourceRange &ExprRange) { 1871 E = E->IgnoreParens(); 1872 1873 // alignof decl is always ok. 1874 if (isa<DeclRefExpr>(E)) 1875 return false; 1876 1877 // Cannot know anything else if the expression is dependent. 1878 if (E->isTypeDependent()) 1879 return false; 1880 1881 if (E->getBitField()) { 1882 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange; 1883 return true; 1884 } 1885 1886 // Alignment of a field access is always okay, so long as it isn't a 1887 // bit-field. 1888 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) 1889 if (isa<FieldDecl>(ME->getMemberDecl())) 1890 return false; 1891 1892 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false); 1893} 1894 1895/// \brief Build a sizeof or alignof expression given a type operand. 1896Action::OwningExprResult 1897Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo, 1898 SourceLocation OpLoc, 1899 bool isSizeOf, SourceRange R) { 1900 if (!TInfo) 1901 return ExprError(); 1902 1903 QualType T = TInfo->getType(); 1904 1905 if (!T->isDependentType() && 1906 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf)) 1907 return ExprError(); 1908 1909 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 1910 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo, 1911 Context.getSizeType(), OpLoc, 1912 R.getEnd())); 1913} 1914 1915/// \brief Build a sizeof or alignof expression given an expression 1916/// operand. 1917Action::OwningExprResult 1918Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc, 1919 bool isSizeOf, SourceRange R) { 1920 // Verify that the operand is valid. 1921 bool isInvalid = false; 1922 if (E->isTypeDependent()) { 1923 // Delay type-checking for type-dependent expressions. 1924 } else if (!isSizeOf) { 1925 isInvalid = CheckAlignOfExpr(E, OpLoc, R); 1926 } else if (E->getBitField()) { // C99 6.5.3.4p1. 1927 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0; 1928 isInvalid = true; 1929 } else { 1930 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true); 1931 } 1932 1933 if (isInvalid) 1934 return ExprError(); 1935 1936 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 1937 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E, 1938 Context.getSizeType(), OpLoc, 1939 R.getEnd())); 1940} 1941 1942/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and 1943/// the same for @c alignof and @c __alignof 1944/// Note that the ArgRange is invalid if isType is false. 1945Action::OwningExprResult 1946Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType, 1947 void *TyOrEx, const SourceRange &ArgRange) { 1948 // If error parsing type, ignore. 1949 if (TyOrEx == 0) return ExprError(); 1950 1951 if (isType) { 1952 TypeSourceInfo *TInfo; 1953 (void) GetTypeFromParser(TyOrEx, &TInfo); 1954 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange); 1955 } 1956 1957 Expr *ArgEx = (Expr *)TyOrEx; 1958 Action::OwningExprResult Result 1959 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange()); 1960 1961 if (Result.isInvalid()) 1962 DeleteExpr(ArgEx); 1963 1964 return move(Result); 1965} 1966 1967QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) { 1968 if (V->isTypeDependent()) 1969 return Context.DependentTy; 1970 1971 // These operators return the element type of a complex type. 1972 if (const ComplexType *CT = V->getType()->getAs<ComplexType>()) 1973 return CT->getElementType(); 1974 1975 // Otherwise they pass through real integer and floating point types here. 1976 if (V->getType()->isArithmeticType()) 1977 return V->getType(); 1978 1979 // Reject anything else. 1980 Diag(Loc, diag::err_realimag_invalid_type) << V->getType() 1981 << (isReal ? "__real" : "__imag"); 1982 return QualType(); 1983} 1984 1985 1986 1987Action::OwningExprResult 1988Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 1989 tok::TokenKind Kind, ExprArg Input) { 1990 UnaryOperator::Opcode Opc; 1991 switch (Kind) { 1992 default: assert(0 && "Unknown unary op!"); 1993 case tok::plusplus: Opc = UnaryOperator::PostInc; break; 1994 case tok::minusminus: Opc = UnaryOperator::PostDec; break; 1995 } 1996 1997 return BuildUnaryOp(S, OpLoc, Opc, move(Input)); 1998} 1999 2000Action::OwningExprResult 2001Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc, 2002 ExprArg Idx, SourceLocation RLoc) { 2003 // Since this might be a postfix expression, get rid of ParenListExprs. 2004 Base = MaybeConvertParenListExprToParenExpr(S, move(Base)); 2005 2006 Expr *LHSExp = static_cast<Expr*>(Base.get()), 2007 *RHSExp = static_cast<Expr*>(Idx.get()); 2008 2009 if (getLangOptions().CPlusPlus && 2010 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) { 2011 Base.release(); 2012 Idx.release(); 2013 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 2014 Context.DependentTy, RLoc)); 2015 } 2016 2017 if (getLangOptions().CPlusPlus && 2018 (LHSExp->getType()->isRecordType() || 2019 LHSExp->getType()->isEnumeralType() || 2020 RHSExp->getType()->isRecordType() || 2021 RHSExp->getType()->isEnumeralType())) { 2022 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx)); 2023 } 2024 2025 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc); 2026} 2027 2028 2029Action::OwningExprResult 2030Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc, 2031 ExprArg Idx, SourceLocation RLoc) { 2032 Expr *LHSExp = static_cast<Expr*>(Base.get()); 2033 Expr *RHSExp = static_cast<Expr*>(Idx.get()); 2034 2035 // Perform default conversions. 2036 DefaultFunctionArrayConversion(LHSExp); 2037 DefaultFunctionArrayConversion(RHSExp); 2038 2039 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 2040 2041 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 2042 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 2043 // in the subscript position. As a result, we need to derive the array base 2044 // and index from the expression types. 2045 Expr *BaseExpr, *IndexExpr; 2046 QualType ResultType; 2047 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 2048 BaseExpr = LHSExp; 2049 IndexExpr = RHSExp; 2050 ResultType = Context.DependentTy; 2051 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 2052 BaseExpr = LHSExp; 2053 IndexExpr = RHSExp; 2054 ResultType = PTy->getPointeeType(); 2055 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 2056 // Handle the uncommon case of "123[Ptr]". 2057 BaseExpr = RHSExp; 2058 IndexExpr = LHSExp; 2059 ResultType = PTy->getPointeeType(); 2060 } else if (const ObjCObjectPointerType *PTy = 2061 LHSTy->getAs<ObjCObjectPointerType>()) { 2062 BaseExpr = LHSExp; 2063 IndexExpr = RHSExp; 2064 ResultType = PTy->getPointeeType(); 2065 } else if (const ObjCObjectPointerType *PTy = 2066 RHSTy->getAs<ObjCObjectPointerType>()) { 2067 // Handle the uncommon case of "123[Ptr]". 2068 BaseExpr = RHSExp; 2069 IndexExpr = LHSExp; 2070 ResultType = PTy->getPointeeType(); 2071 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 2072 BaseExpr = LHSExp; // vectors: V[123] 2073 IndexExpr = RHSExp; 2074 2075 // FIXME: need to deal with const... 2076 ResultType = VTy->getElementType(); 2077 } else if (LHSTy->isArrayType()) { 2078 // If we see an array that wasn't promoted by 2079 // DefaultFunctionArrayConversion, it must be an array that 2080 // wasn't promoted because of the C90 rule that doesn't 2081 // allow promoting non-lvalue arrays. Warn, then 2082 // force the promotion here. 2083 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 2084 LHSExp->getSourceRange(); 2085 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 2086 CastExpr::CK_ArrayToPointerDecay); 2087 LHSTy = LHSExp->getType(); 2088 2089 BaseExpr = LHSExp; 2090 IndexExpr = RHSExp; 2091 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 2092 } else if (RHSTy->isArrayType()) { 2093 // Same as previous, except for 123[f().a] case 2094 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 2095 RHSExp->getSourceRange(); 2096 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 2097 CastExpr::CK_ArrayToPointerDecay); 2098 RHSTy = RHSExp->getType(); 2099 2100 BaseExpr = RHSExp; 2101 IndexExpr = LHSExp; 2102 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 2103 } else { 2104 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 2105 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 2106 } 2107 // C99 6.5.2.1p1 2108 if (!(IndexExpr->getType()->isIntegerType() && 2109 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent()) 2110 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 2111 << IndexExpr->getSourceRange()); 2112 2113 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 2114 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 2115 && !IndexExpr->isTypeDependent()) 2116 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 2117 2118 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 2119 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 2120 // type. Note that Functions are not objects, and that (in C99 parlance) 2121 // incomplete types are not object types. 2122 if (ResultType->isFunctionType()) { 2123 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 2124 << ResultType << BaseExpr->getSourceRange(); 2125 return ExprError(); 2126 } 2127 2128 if (!ResultType->isDependentType() && 2129 RequireCompleteType(LLoc, ResultType, 2130 PDiag(diag::err_subscript_incomplete_type) 2131 << BaseExpr->getSourceRange())) 2132 return ExprError(); 2133 2134 // Diagnose bad cases where we step over interface counts. 2135 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) { 2136 Diag(LLoc, diag::err_subscript_nonfragile_interface) 2137 << ResultType << BaseExpr->getSourceRange(); 2138 return ExprError(); 2139 } 2140 2141 Base.release(); 2142 Idx.release(); 2143 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 2144 ResultType, RLoc)); 2145} 2146 2147QualType Sema:: 2148CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc, 2149 const IdentifierInfo *CompName, 2150 SourceLocation CompLoc) { 2151 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements, 2152 // see FIXME there. 2153 // 2154 // FIXME: This logic can be greatly simplified by splitting it along 2155 // halving/not halving and reworking the component checking. 2156 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>(); 2157 2158 // The vector accessor can't exceed the number of elements. 2159 const char *compStr = CompName->getNameStart(); 2160 2161 // This flag determines whether or not the component is one of the four 2162 // special names that indicate a subset of exactly half the elements are 2163 // to be selected. 2164 bool HalvingSwizzle = false; 2165 2166 // This flag determines whether or not CompName has an 's' char prefix, 2167 // indicating that it is a string of hex values to be used as vector indices. 2168 bool HexSwizzle = *compStr == 's' || *compStr == 'S'; 2169 2170 // Check that we've found one of the special components, or that the component 2171 // names must come from the same set. 2172 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") || 2173 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) { 2174 HalvingSwizzle = true; 2175 } else if (vecType->getPointAccessorIdx(*compStr) != -1) { 2176 do 2177 compStr++; 2178 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1); 2179 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) { 2180 do 2181 compStr++; 2182 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1); 2183 } 2184 2185 if (!HalvingSwizzle && *compStr) { 2186 // We didn't get to the end of the string. This means the component names 2187 // didn't come from the same set *or* we encountered an illegal name. 2188 Diag(OpLoc, diag::err_ext_vector_component_name_illegal) 2189 << std::string(compStr,compStr+1) << SourceRange(CompLoc); 2190 return QualType(); 2191 } 2192 2193 // Ensure no component accessor exceeds the width of the vector type it 2194 // operates on. 2195 if (!HalvingSwizzle) { 2196 compStr = CompName->getNameStart(); 2197 2198 if (HexSwizzle) 2199 compStr++; 2200 2201 while (*compStr) { 2202 if (!vecType->isAccessorWithinNumElements(*compStr++)) { 2203 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length) 2204 << baseType << SourceRange(CompLoc); 2205 return QualType(); 2206 } 2207 } 2208 } 2209 2210 // The component accessor looks fine - now we need to compute the actual type. 2211 // The vector type is implied by the component accessor. For example, 2212 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc. 2213 // vec4.s0 is a float, vec4.s23 is a vec3, etc. 2214 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2. 2215 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2 2216 : CompName->getLength(); 2217 if (HexSwizzle) 2218 CompSize--; 2219 2220 if (CompSize == 1) 2221 return vecType->getElementType(); 2222 2223 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize); 2224 // Now look up the TypeDefDecl from the vector type. Without this, 2225 // diagostics look bad. We want extended vector types to appear built-in. 2226 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) { 2227 if (ExtVectorDecls[i]->getUnderlyingType() == VT) 2228 return Context.getTypedefType(ExtVectorDecls[i]); 2229 } 2230 return VT; // should never get here (a typedef type should always be found). 2231} 2232 2233static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl, 2234 IdentifierInfo *Member, 2235 const Selector &Sel, 2236 ASTContext &Context) { 2237 2238 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member)) 2239 return PD; 2240 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel)) 2241 return OMD; 2242 2243 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(), 2244 E = PDecl->protocol_end(); I != E; ++I) { 2245 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel, 2246 Context)) 2247 return D; 2248 } 2249 return 0; 2250} 2251 2252static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy, 2253 IdentifierInfo *Member, 2254 const Selector &Sel, 2255 ASTContext &Context) { 2256 // Check protocols on qualified interfaces. 2257 Decl *GDecl = 0; 2258 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(), 2259 E = QIdTy->qual_end(); I != E; ++I) { 2260 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) { 2261 GDecl = PD; 2262 break; 2263 } 2264 // Also must look for a getter name which uses property syntax. 2265 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) { 2266 GDecl = OMD; 2267 break; 2268 } 2269 } 2270 if (!GDecl) { 2271 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(), 2272 E = QIdTy->qual_end(); I != E; ++I) { 2273 // Search in the protocol-qualifier list of current protocol. 2274 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context); 2275 if (GDecl) 2276 return GDecl; 2277 } 2278 } 2279 return GDecl; 2280} 2281 2282Sema::OwningExprResult 2283Sema::ActOnDependentMemberExpr(ExprArg Base, QualType BaseType, 2284 bool IsArrow, SourceLocation OpLoc, 2285 const CXXScopeSpec &SS, 2286 NamedDecl *FirstQualifierInScope, 2287 DeclarationName Name, SourceLocation NameLoc, 2288 const TemplateArgumentListInfo *TemplateArgs) { 2289 Expr *BaseExpr = Base.takeAs<Expr>(); 2290 2291 // Even in dependent contexts, try to diagnose base expressions with 2292 // obviously wrong types, e.g.: 2293 // 2294 // T* t; 2295 // t.f; 2296 // 2297 // In Obj-C++, however, the above expression is valid, since it could be 2298 // accessing the 'f' property if T is an Obj-C interface. The extra check 2299 // allows this, while still reporting an error if T is a struct pointer. 2300 if (!IsArrow) { 2301 const PointerType *PT = BaseType->getAs<PointerType>(); 2302 if (PT && (!getLangOptions().ObjC1 || 2303 PT->getPointeeType()->isRecordType())) { 2304 assert(BaseExpr && "cannot happen with implicit member accesses"); 2305 Diag(NameLoc, diag::err_typecheck_member_reference_struct_union) 2306 << BaseType << BaseExpr->getSourceRange(); 2307 return ExprError(); 2308 } 2309 } 2310 2311 assert(BaseType->isDependentType() || Name.isDependentName()); 2312 2313 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr 2314 // must have pointer type, and the accessed type is the pointee. 2315 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType, 2316 IsArrow, OpLoc, 2317 static_cast<NestedNameSpecifier*>(SS.getScopeRep()), 2318 SS.getRange(), 2319 FirstQualifierInScope, 2320 Name, NameLoc, 2321 TemplateArgs)); 2322} 2323 2324/// We know that the given qualified member reference points only to 2325/// declarations which do not belong to the static type of the base 2326/// expression. Diagnose the problem. 2327static void DiagnoseQualifiedMemberReference(Sema &SemaRef, 2328 Expr *BaseExpr, 2329 QualType BaseType, 2330 const CXXScopeSpec &SS, 2331 const LookupResult &R) { 2332 // If this is an implicit member access, use a different set of 2333 // diagnostics. 2334 if (!BaseExpr) 2335 return DiagnoseInstanceReference(SemaRef, SS, R); 2336 2337 // FIXME: this is an exceedingly lame diagnostic for some of the more 2338 // complicated cases here. 2339 DeclContext *DC = R.getRepresentativeDecl()->getDeclContext(); 2340 SemaRef.Diag(R.getNameLoc(), diag::err_not_direct_base_or_virtual) 2341 << SS.getRange() << DC << BaseType; 2342} 2343 2344// Check whether the declarations we found through a nested-name 2345// specifier in a member expression are actually members of the base 2346// type. The restriction here is: 2347// 2348// C++ [expr.ref]p2: 2349// ... In these cases, the id-expression shall name a 2350// member of the class or of one of its base classes. 2351// 2352// So it's perfectly legitimate for the nested-name specifier to name 2353// an unrelated class, and for us to find an overload set including 2354// decls from classes which are not superclasses, as long as the decl 2355// we actually pick through overload resolution is from a superclass. 2356bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr, 2357 QualType BaseType, 2358 const CXXScopeSpec &SS, 2359 const LookupResult &R) { 2360 const RecordType *BaseRT = BaseType->getAs<RecordType>(); 2361 if (!BaseRT) { 2362 // We can't check this yet because the base type is still 2363 // dependent. 2364 assert(BaseType->isDependentType()); 2365 return false; 2366 } 2367 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl()); 2368 2369 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2370 // If this is an implicit member reference and we find a 2371 // non-instance member, it's not an error. 2372 if (!BaseExpr && !IsInstanceMember((*I)->getUnderlyingDecl())) 2373 return false; 2374 2375 // Note that we use the DC of the decl, not the underlying decl. 2376 CXXRecordDecl *RecordD = cast<CXXRecordDecl>((*I)->getDeclContext()); 2377 while (RecordD->isAnonymousStructOrUnion()) 2378 RecordD = cast<CXXRecordDecl>(RecordD->getParent()); 2379 2380 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord; 2381 MemberRecord.insert(RecordD->getCanonicalDecl()); 2382 2383 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord)) 2384 return false; 2385 } 2386 2387 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R); 2388 return true; 2389} 2390 2391static bool 2392LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R, 2393 SourceRange BaseRange, const RecordType *RTy, 2394 SourceLocation OpLoc, const CXXScopeSpec &SS) { 2395 RecordDecl *RDecl = RTy->getDecl(); 2396 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0), 2397 PDiag(diag::err_typecheck_incomplete_tag) 2398 << BaseRange)) 2399 return true; 2400 2401 DeclContext *DC = RDecl; 2402 if (SS.isSet()) { 2403 // If the member name was a qualified-id, look into the 2404 // nested-name-specifier. 2405 DC = SemaRef.computeDeclContext(SS, false); 2406 2407 if (SemaRef.RequireCompleteDeclContext(SS)) { 2408 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag) 2409 << SS.getRange() << DC; 2410 return true; 2411 } 2412 2413 assert(DC && "Cannot handle non-computable dependent contexts in lookup"); 2414 2415 if (!isa<TypeDecl>(DC)) { 2416 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass) 2417 << DC << SS.getRange(); 2418 return true; 2419 } 2420 } 2421 2422 // The record definition is complete, now look up the member. 2423 SemaRef.LookupQualifiedName(R, DC); 2424 2425 if (!R.empty()) 2426 return false; 2427 2428 // We didn't find anything with the given name, so try to correct 2429 // for typos. 2430 DeclarationName Name = R.getLookupName(); 2431 if (SemaRef.CorrectTypo(R, 0, &SS, DC) && 2432 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) { 2433 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest) 2434 << Name << DC << R.getLookupName() << SS.getRange() 2435 << CodeModificationHint::CreateReplacement(R.getNameLoc(), 2436 R.getLookupName().getAsString()); 2437 if (NamedDecl *ND = R.getAsSingle<NamedDecl>()) 2438 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl) 2439 << ND->getDeclName(); 2440 return false; 2441 } else { 2442 R.clear(); 2443 } 2444 2445 return false; 2446} 2447 2448Sema::OwningExprResult 2449Sema::BuildMemberReferenceExpr(ExprArg BaseArg, QualType BaseType, 2450 SourceLocation OpLoc, bool IsArrow, 2451 const CXXScopeSpec &SS, 2452 NamedDecl *FirstQualifierInScope, 2453 DeclarationName Name, SourceLocation NameLoc, 2454 const TemplateArgumentListInfo *TemplateArgs) { 2455 Expr *Base = BaseArg.takeAs<Expr>(); 2456 2457 if (BaseType->isDependentType() || 2458 (SS.isSet() && isDependentScopeSpecifier(SS))) 2459 return ActOnDependentMemberExpr(ExprArg(*this, Base), BaseType, 2460 IsArrow, OpLoc, 2461 SS, FirstQualifierInScope, 2462 Name, NameLoc, 2463 TemplateArgs); 2464 2465 LookupResult R(*this, Name, NameLoc, LookupMemberName); 2466 2467 // Implicit member accesses. 2468 if (!Base) { 2469 QualType RecordTy = BaseType; 2470 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType(); 2471 if (LookupMemberExprInRecord(*this, R, SourceRange(), 2472 RecordTy->getAs<RecordType>(), 2473 OpLoc, SS)) 2474 return ExprError(); 2475 2476 // Explicit member accesses. 2477 } else { 2478 OwningExprResult Result = 2479 LookupMemberExpr(R, Base, IsArrow, OpLoc, 2480 SS, /*ObjCImpDecl*/ DeclPtrTy()); 2481 2482 if (Result.isInvalid()) { 2483 Owned(Base); 2484 return ExprError(); 2485 } 2486 2487 if (Result.get()) 2488 return move(Result); 2489 } 2490 2491 return BuildMemberReferenceExpr(ExprArg(*this, Base), BaseType, 2492 OpLoc, IsArrow, SS, FirstQualifierInScope, 2493 R, TemplateArgs); 2494} 2495 2496Sema::OwningExprResult 2497Sema::BuildMemberReferenceExpr(ExprArg Base, QualType BaseExprType, 2498 SourceLocation OpLoc, bool IsArrow, 2499 const CXXScopeSpec &SS, 2500 NamedDecl *FirstQualifierInScope, 2501 LookupResult &R, 2502 const TemplateArgumentListInfo *TemplateArgs) { 2503 Expr *BaseExpr = Base.takeAs<Expr>(); 2504 QualType BaseType = BaseExprType; 2505 if (IsArrow) { 2506 assert(BaseType->isPointerType()); 2507 BaseType = BaseType->getAs<PointerType>()->getPointeeType(); 2508 } 2509 2510 NestedNameSpecifier *Qualifier = 2511 static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 2512 DeclarationName MemberName = R.getLookupName(); 2513 SourceLocation MemberLoc = R.getNameLoc(); 2514 2515 if (R.isAmbiguous()) 2516 return ExprError(); 2517 2518 if (R.empty()) { 2519 // Rederive where we looked up. 2520 DeclContext *DC = (SS.isSet() 2521 ? computeDeclContext(SS, false) 2522 : BaseType->getAs<RecordType>()->getDecl()); 2523 2524 Diag(R.getNameLoc(), diag::err_no_member) 2525 << MemberName << DC 2526 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange()); 2527 return ExprError(); 2528 } 2529 2530 // Diagnose lookups that find only declarations from a non-base 2531 // type. This is possible for either qualified lookups (which may 2532 // have been qualified with an unrelated type) or implicit member 2533 // expressions (which were found with unqualified lookup and thus 2534 // may have come from an enclosing scope). Note that it's okay for 2535 // lookup to find declarations from a non-base type as long as those 2536 // aren't the ones picked by overload resolution. 2537 if ((SS.isSet() || !BaseExpr || 2538 (isa<CXXThisExpr>(BaseExpr) && 2539 cast<CXXThisExpr>(BaseExpr)->isImplicit())) && 2540 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R)) 2541 return ExprError(); 2542 2543 // Construct an unresolved result if we in fact got an unresolved 2544 // result. 2545 if (R.isOverloadedResult() || R.isUnresolvableResult()) { 2546 bool Dependent = 2547 BaseExprType->isDependentType() || 2548 R.isUnresolvableResult() || 2549 UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs); 2550 2551 // Suppress any lookup-related diagnostics; we'll do these when we 2552 // pick a member. 2553 R.suppressDiagnostics(); 2554 2555 UnresolvedMemberExpr *MemExpr 2556 = UnresolvedMemberExpr::Create(Context, Dependent, 2557 R.isUnresolvableResult(), 2558 BaseExpr, BaseExprType, 2559 IsArrow, OpLoc, 2560 Qualifier, SS.getRange(), 2561 MemberName, MemberLoc, 2562 TemplateArgs); 2563 MemExpr->addDecls(R.begin(), R.end()); 2564 2565 return Owned(MemExpr); 2566 } 2567 2568 assert(R.isSingleResult()); 2569 NamedDecl *MemberDecl = R.getFoundDecl(); 2570 2571 // FIXME: diagnose the presence of template arguments now. 2572 2573 // If the decl being referenced had an error, return an error for this 2574 // sub-expr without emitting another error, in order to avoid cascading 2575 // error cases. 2576 if (MemberDecl->isInvalidDecl()) 2577 return ExprError(); 2578 2579 // Handle the implicit-member-access case. 2580 if (!BaseExpr) { 2581 // If this is not an instance member, convert to a non-member access. 2582 if (!IsInstanceMember(MemberDecl)) 2583 return BuildDeclarationNameExpr(SS, R.getNameLoc(), MemberDecl); 2584 2585 SourceLocation Loc = R.getNameLoc(); 2586 if (SS.getRange().isValid()) 2587 Loc = SS.getRange().getBegin(); 2588 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true); 2589 } 2590 2591 bool ShouldCheckUse = true; 2592 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) { 2593 // Don't diagnose the use of a virtual member function unless it's 2594 // explicitly qualified. 2595 if (MD->isVirtual() && !SS.isSet()) 2596 ShouldCheckUse = false; 2597 } 2598 2599 // Check the use of this member. 2600 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) { 2601 Owned(BaseExpr); 2602 return ExprError(); 2603 } 2604 2605 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) { 2606 // We may have found a field within an anonymous union or struct 2607 // (C++ [class.union]). 2608 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion() && 2609 !BaseType->getAs<RecordType>()->getDecl()->isAnonymousStructOrUnion()) 2610 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD, 2611 BaseExpr, OpLoc); 2612 2613 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref] 2614 QualType MemberType = FD->getType(); 2615 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) 2616 MemberType = Ref->getPointeeType(); 2617 else { 2618 Qualifiers BaseQuals = BaseType.getQualifiers(); 2619 BaseQuals.removeObjCGCAttr(); 2620 if (FD->isMutable()) BaseQuals.removeConst(); 2621 2622 Qualifiers MemberQuals 2623 = Context.getCanonicalType(MemberType).getQualifiers(); 2624 2625 Qualifiers Combined = BaseQuals + MemberQuals; 2626 if (Combined != MemberQuals) 2627 MemberType = Context.getQualifiedType(MemberType, Combined); 2628 } 2629 2630 MarkDeclarationReferenced(MemberLoc, FD); 2631 if (PerformObjectMemberConversion(BaseExpr, FD)) 2632 return ExprError(); 2633 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS, 2634 FD, MemberLoc, MemberType)); 2635 } 2636 2637 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) { 2638 MarkDeclarationReferenced(MemberLoc, Var); 2639 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS, 2640 Var, MemberLoc, 2641 Var->getType().getNonReferenceType())); 2642 } 2643 2644 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) { 2645 MarkDeclarationReferenced(MemberLoc, MemberDecl); 2646 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS, 2647 MemberFn, MemberLoc, 2648 MemberFn->getType())); 2649 } 2650 2651 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) { 2652 MarkDeclarationReferenced(MemberLoc, MemberDecl); 2653 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS, 2654 Enum, MemberLoc, Enum->getType())); 2655 } 2656 2657 Owned(BaseExpr); 2658 2659 if (isa<TypeDecl>(MemberDecl)) 2660 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type) 2661 << MemberName << int(IsArrow)); 2662 2663 // We found a declaration kind that we didn't expect. This is a 2664 // generic error message that tells the user that she can't refer 2665 // to this member with '.' or '->'. 2666 return ExprError(Diag(MemberLoc, 2667 diag::err_typecheck_member_reference_unknown) 2668 << MemberName << int(IsArrow)); 2669} 2670 2671/// Look up the given member of the given non-type-dependent 2672/// expression. This can return in one of two ways: 2673/// * If it returns a sentinel null-but-valid result, the caller will 2674/// assume that lookup was performed and the results written into 2675/// the provided structure. It will take over from there. 2676/// * Otherwise, the returned expression will be produced in place of 2677/// an ordinary member expression. 2678/// 2679/// The ObjCImpDecl bit is a gross hack that will need to be properly 2680/// fixed for ObjC++. 2681Sema::OwningExprResult 2682Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr, 2683 bool &IsArrow, SourceLocation OpLoc, 2684 const CXXScopeSpec &SS, 2685 DeclPtrTy ObjCImpDecl) { 2686 assert(BaseExpr && "no base expression"); 2687 2688 // Perform default conversions. 2689 DefaultFunctionArrayConversion(BaseExpr); 2690 2691 QualType BaseType = BaseExpr->getType(); 2692 assert(!BaseType->isDependentType()); 2693 2694 DeclarationName MemberName = R.getLookupName(); 2695 SourceLocation MemberLoc = R.getNameLoc(); 2696 2697 // If the user is trying to apply -> or . to a function pointer 2698 // type, it's probably because they forgot parentheses to call that 2699 // function. Suggest the addition of those parentheses, build the 2700 // call, and continue on. 2701 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 2702 if (const FunctionProtoType *Fun 2703 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) { 2704 QualType ResultTy = Fun->getResultType(); 2705 if (Fun->getNumArgs() == 0 && 2706 ((!IsArrow && ResultTy->isRecordType()) || 2707 (IsArrow && ResultTy->isPointerType() && 2708 ResultTy->getAs<PointerType>()->getPointeeType() 2709 ->isRecordType()))) { 2710 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd()); 2711 Diag(Loc, diag::err_member_reference_needs_call) 2712 << QualType(Fun, 0) 2713 << CodeModificationHint::CreateInsertion(Loc, "()"); 2714 2715 OwningExprResult NewBase 2716 = ActOnCallExpr(0, ExprArg(*this, BaseExpr), Loc, 2717 MultiExprArg(*this, 0, 0), 0, Loc); 2718 if (NewBase.isInvalid()) 2719 return ExprError(); 2720 2721 BaseExpr = NewBase.takeAs<Expr>(); 2722 DefaultFunctionArrayConversion(BaseExpr); 2723 BaseType = BaseExpr->getType(); 2724 } 2725 } 2726 } 2727 2728 // If this is an Objective-C pseudo-builtin and a definition is provided then 2729 // use that. 2730 if (BaseType->isObjCIdType()) { 2731 if (IsArrow) { 2732 // Handle the following exceptional case PObj->isa. 2733 if (const ObjCObjectPointerType *OPT = 2734 BaseType->getAs<ObjCObjectPointerType>()) { 2735 if (OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) && 2736 MemberName.getAsIdentifierInfo()->isStr("isa")) 2737 return Owned(new (Context) ObjCIsaExpr(BaseExpr, true, MemberLoc, 2738 Context.getObjCClassType())); 2739 } 2740 } 2741 // We have an 'id' type. Rather than fall through, we check if this 2742 // is a reference to 'isa'. 2743 if (BaseType != Context.ObjCIdRedefinitionType) { 2744 BaseType = Context.ObjCIdRedefinitionType; 2745 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast); 2746 } 2747 } 2748 2749 // If this is an Objective-C pseudo-builtin and a definition is provided then 2750 // use that. 2751 if (Context.isObjCSelType(BaseType)) { 2752 // We have an 'SEL' type. Rather than fall through, we check if this 2753 // is a reference to 'sel_id'. 2754 if (BaseType != Context.ObjCSelRedefinitionType) { 2755 BaseType = Context.ObjCSelRedefinitionType; 2756 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast); 2757 } 2758 } 2759 2760 assert(!BaseType.isNull() && "no type for member expression"); 2761 2762 // Handle properties on ObjC 'Class' types. 2763 if (!IsArrow && BaseType->isObjCClassType()) { 2764 // Also must look for a getter name which uses property syntax. 2765 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 2766 Selector Sel = PP.getSelectorTable().getNullarySelector(Member); 2767 if (ObjCMethodDecl *MD = getCurMethodDecl()) { 2768 ObjCInterfaceDecl *IFace = MD->getClassInterface(); 2769 ObjCMethodDecl *Getter; 2770 // FIXME: need to also look locally in the implementation. 2771 if ((Getter = IFace->lookupClassMethod(Sel))) { 2772 // Check the use of this method. 2773 if (DiagnoseUseOfDecl(Getter, MemberLoc)) 2774 return ExprError(); 2775 } 2776 // If we found a getter then this may be a valid dot-reference, we 2777 // will look for the matching setter, in case it is needed. 2778 Selector SetterSel = 2779 SelectorTable::constructSetterName(PP.getIdentifierTable(), 2780 PP.getSelectorTable(), Member); 2781 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel); 2782 if (!Setter) { 2783 // If this reference is in an @implementation, also check for 'private' 2784 // methods. 2785 Setter = IFace->lookupPrivateInstanceMethod(SetterSel); 2786 } 2787 // Look through local category implementations associated with the class. 2788 if (!Setter) 2789 Setter = IFace->getCategoryClassMethod(SetterSel); 2790 2791 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc)) 2792 return ExprError(); 2793 2794 if (Getter || Setter) { 2795 QualType PType; 2796 2797 if (Getter) 2798 PType = Getter->getResultType(); 2799 else 2800 // Get the expression type from Setter's incoming parameter. 2801 PType = (*(Setter->param_end() -1))->getType(); 2802 // FIXME: we must check that the setter has property type. 2803 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, 2804 PType, 2805 Setter, MemberLoc, BaseExpr)); 2806 } 2807 return ExprError(Diag(MemberLoc, diag::err_property_not_found) 2808 << MemberName << BaseType); 2809 } 2810 } 2811 2812 if (BaseType->isObjCClassType() && 2813 BaseType != Context.ObjCClassRedefinitionType) { 2814 BaseType = Context.ObjCClassRedefinitionType; 2815 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast); 2816 } 2817 2818 if (IsArrow) { 2819 if (const PointerType *PT = BaseType->getAs<PointerType>()) 2820 BaseType = PT->getPointeeType(); 2821 else if (BaseType->isObjCObjectPointerType()) 2822 ; 2823 else if (BaseType->isRecordType()) { 2824 // Recover from arrow accesses to records, e.g.: 2825 // struct MyRecord foo; 2826 // foo->bar 2827 // This is actually well-formed in C++ if MyRecord has an 2828 // overloaded operator->, but that should have been dealt with 2829 // by now. 2830 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 2831 << BaseType << int(IsArrow) << BaseExpr->getSourceRange() 2832 << CodeModificationHint::CreateReplacement(OpLoc, "."); 2833 IsArrow = false; 2834 } else { 2835 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow) 2836 << BaseType << BaseExpr->getSourceRange(); 2837 return ExprError(); 2838 } 2839 } else { 2840 // Recover from dot accesses to pointers, e.g.: 2841 // type *foo; 2842 // foo.bar 2843 // This is actually well-formed in two cases: 2844 // - 'type' is an Objective C type 2845 // - 'bar' is a pseudo-destructor name which happens to refer to 2846 // the appropriate pointer type 2847 if (MemberName.getNameKind() != DeclarationName::CXXDestructorName) { 2848 const PointerType *PT = BaseType->getAs<PointerType>(); 2849 if (PT && PT->getPointeeType()->isRecordType()) { 2850 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 2851 << BaseType << int(IsArrow) << BaseExpr->getSourceRange() 2852 << CodeModificationHint::CreateReplacement(OpLoc, "->"); 2853 BaseType = PT->getPointeeType(); 2854 IsArrow = true; 2855 } 2856 } 2857 } 2858 2859 // Handle field access to simple records. This also handles access 2860 // to fields of the ObjC 'id' struct. 2861 if (const RecordType *RTy = BaseType->getAs<RecordType>()) { 2862 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(), 2863 RTy, OpLoc, SS)) 2864 return ExprError(); 2865 return Owned((Expr*) 0); 2866 } 2867 2868 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring 2869 // into a record type was handled above, any destructor we see here is a 2870 // pseudo-destructor. 2871 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) { 2872 // C++ [expr.pseudo]p2: 2873 // The left hand side of the dot operator shall be of scalar type. The 2874 // left hand side of the arrow operator shall be of pointer to scalar 2875 // type. 2876 if (!BaseType->isScalarType()) 2877 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar) 2878 << BaseType << BaseExpr->getSourceRange()); 2879 2880 // [...] The type designated by the pseudo-destructor-name shall be the 2881 // same as the object type. 2882 if (!MemberName.getCXXNameType()->isDependentType() && 2883 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType())) 2884 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch) 2885 << BaseType << MemberName.getCXXNameType() 2886 << BaseExpr->getSourceRange() << SourceRange(MemberLoc)); 2887 2888 // [...] Furthermore, the two type-names in a pseudo-destructor-name of 2889 // the form 2890 // 2891 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name 2892 // 2893 // shall designate the same scalar type. 2894 // 2895 // FIXME: DPG can't see any way to trigger this particular clause, so it 2896 // isn't checked here. 2897 2898 // FIXME: We've lost the precise spelling of the type by going through 2899 // DeclarationName. Can we do better? 2900 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr, 2901 IsArrow, OpLoc, 2902 (NestedNameSpecifier *) SS.getScopeRep(), 2903 SS.getRange(), 2904 MemberName.getCXXNameType(), 2905 MemberLoc)); 2906 } 2907 2908 // Handle access to Objective-C instance variables, such as "Obj->ivar" and 2909 // (*Obj).ivar. 2910 if ((IsArrow && BaseType->isObjCObjectPointerType()) || 2911 (!IsArrow && BaseType->isObjCInterfaceType())) { 2912 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>(); 2913 const ObjCInterfaceType *IFaceT = 2914 OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>(); 2915 if (IFaceT) { 2916 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 2917 2918 ObjCInterfaceDecl *IDecl = IFaceT->getDecl(); 2919 ObjCInterfaceDecl *ClassDeclared; 2920 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 2921 2922 if (!IV) { 2923 // Attempt to correct for typos in ivar names. 2924 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(), 2925 LookupMemberName); 2926 if (CorrectTypo(Res, 0, 0, IDecl) && 2927 (IV = Res.getAsSingle<ObjCIvarDecl>())) { 2928 Diag(R.getNameLoc(), 2929 diag::err_typecheck_member_reference_ivar_suggest) 2930 << IDecl->getDeclName() << MemberName << IV->getDeclName() 2931 << CodeModificationHint::CreateReplacement(R.getNameLoc(), 2932 IV->getNameAsString()); 2933 Diag(IV->getLocation(), diag::note_previous_decl) 2934 << IV->getDeclName(); 2935 } 2936 } 2937 2938 if (IV) { 2939 // If the decl being referenced had an error, return an error for this 2940 // sub-expr without emitting another error, in order to avoid cascading 2941 // error cases. 2942 if (IV->isInvalidDecl()) 2943 return ExprError(); 2944 2945 // Check whether we can reference this field. 2946 if (DiagnoseUseOfDecl(IV, MemberLoc)) 2947 return ExprError(); 2948 if (IV->getAccessControl() != ObjCIvarDecl::Public && 2949 IV->getAccessControl() != ObjCIvarDecl::Package) { 2950 ObjCInterfaceDecl *ClassOfMethodDecl = 0; 2951 if (ObjCMethodDecl *MD = getCurMethodDecl()) 2952 ClassOfMethodDecl = MD->getClassInterface(); 2953 else if (ObjCImpDecl && getCurFunctionDecl()) { 2954 // Case of a c-function declared inside an objc implementation. 2955 // FIXME: For a c-style function nested inside an objc implementation 2956 // class, there is no implementation context available, so we pass 2957 // down the context as argument to this routine. Ideally, this context 2958 // need be passed down in the AST node and somehow calculated from the 2959 // AST for a function decl. 2960 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>(); 2961 if (ObjCImplementationDecl *IMPD = 2962 dyn_cast<ObjCImplementationDecl>(ImplDecl)) 2963 ClassOfMethodDecl = IMPD->getClassInterface(); 2964 else if (ObjCCategoryImplDecl* CatImplClass = 2965 dyn_cast<ObjCCategoryImplDecl>(ImplDecl)) 2966 ClassOfMethodDecl = CatImplClass->getClassInterface(); 2967 } 2968 2969 if (IV->getAccessControl() == ObjCIvarDecl::Private) { 2970 if (ClassDeclared != IDecl || 2971 ClassOfMethodDecl != ClassDeclared) 2972 Diag(MemberLoc, diag::error_private_ivar_access) 2973 << IV->getDeclName(); 2974 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl)) 2975 // @protected 2976 Diag(MemberLoc, diag::error_protected_ivar_access) 2977 << IV->getDeclName(); 2978 } 2979 2980 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(), 2981 MemberLoc, BaseExpr, 2982 IsArrow)); 2983 } 2984 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar) 2985 << IDecl->getDeclName() << MemberName 2986 << BaseExpr->getSourceRange()); 2987 } 2988 } 2989 // Handle properties on 'id' and qualified "id". 2990 if (!IsArrow && (BaseType->isObjCIdType() || 2991 BaseType->isObjCQualifiedIdType())) { 2992 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>(); 2993 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 2994 2995 // Check protocols on qualified interfaces. 2996 Selector Sel = PP.getSelectorTable().getNullarySelector(Member); 2997 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) { 2998 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) { 2999 // Check the use of this declaration 3000 if (DiagnoseUseOfDecl(PD, MemberLoc)) 3001 return ExprError(); 3002 3003 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(), 3004 MemberLoc, BaseExpr)); 3005 } 3006 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) { 3007 // Check the use of this method. 3008 if (DiagnoseUseOfDecl(OMD, MemberLoc)) 3009 return ExprError(); 3010 3011 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel, 3012 OMD->getResultType(), 3013 OMD, OpLoc, MemberLoc, 3014 NULL, 0)); 3015 } 3016 } 3017 3018 return ExprError(Diag(MemberLoc, diag::err_property_not_found) 3019 << MemberName << BaseType); 3020 } 3021 // Handle Objective-C property access, which is "Obj.property" where Obj is a 3022 // pointer to a (potentially qualified) interface type. 3023 const ObjCObjectPointerType *OPT; 3024 if (!IsArrow && (OPT = BaseType->getAsObjCInterfacePointerType())) { 3025 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType(); 3026 ObjCInterfaceDecl *IFace = IFaceT->getDecl(); 3027 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 3028 3029 // Search for a declared property first. 3030 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) { 3031 // Check whether we can reference this property. 3032 if (DiagnoseUseOfDecl(PD, MemberLoc)) 3033 return ExprError(); 3034 QualType ResTy = PD->getType(); 3035 Selector Sel = PP.getSelectorTable().getNullarySelector(Member); 3036 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel); 3037 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc)) 3038 ResTy = Getter->getResultType(); 3039 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy, 3040 MemberLoc, BaseExpr)); 3041 } 3042 // Check protocols on qualified interfaces. 3043 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(), 3044 E = OPT->qual_end(); I != E; ++I) 3045 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) { 3046 // Check whether we can reference this property. 3047 if (DiagnoseUseOfDecl(PD, MemberLoc)) 3048 return ExprError(); 3049 3050 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(), 3051 MemberLoc, BaseExpr)); 3052 } 3053 // If that failed, look for an "implicit" property by seeing if the nullary 3054 // selector is implemented. 3055 3056 // FIXME: The logic for looking up nullary and unary selectors should be 3057 // shared with the code in ActOnInstanceMessage. 3058 3059 Selector Sel = PP.getSelectorTable().getNullarySelector(Member); 3060 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel); 3061 3062 // If this reference is in an @implementation, check for 'private' methods. 3063 if (!Getter) 3064 Getter = IFace->lookupPrivateInstanceMethod(Sel); 3065 3066 // Look through local category implementations associated with the class. 3067 if (!Getter) 3068 Getter = IFace->getCategoryInstanceMethod(Sel); 3069 if (Getter) { 3070 // Check if we can reference this property. 3071 if (DiagnoseUseOfDecl(Getter, MemberLoc)) 3072 return ExprError(); 3073 } 3074 // If we found a getter then this may be a valid dot-reference, we 3075 // will look for the matching setter, in case it is needed. 3076 Selector SetterSel = 3077 SelectorTable::constructSetterName(PP.getIdentifierTable(), 3078 PP.getSelectorTable(), Member); 3079 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel); 3080 if (!Setter) { 3081 // If this reference is in an @implementation, also check for 'private' 3082 // methods. 3083 Setter = IFace->lookupPrivateInstanceMethod(SetterSel); 3084 } 3085 // Look through local category implementations associated with the class. 3086 if (!Setter) 3087 Setter = IFace->getCategoryInstanceMethod(SetterSel); 3088 3089 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc)) 3090 return ExprError(); 3091 3092 if (Getter) { 3093 QualType PType; 3094 PType = Getter->getResultType(); 3095 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType, 3096 Setter, MemberLoc, BaseExpr)); 3097 } 3098 3099 // Attempt to correct for typos in property names. 3100 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(), 3101 LookupOrdinaryName); 3102 if (CorrectTypo(Res, 0, 0, IFace, false, OPT) && 3103 Res.getAsSingle<ObjCPropertyDecl>()) { 3104 Diag(R.getNameLoc(), diag::err_property_not_found_suggest) 3105 << MemberName << BaseType << Res.getLookupName() 3106 << CodeModificationHint::CreateReplacement(R.getNameLoc(), 3107 Res.getLookupName().getAsString()); 3108 ObjCPropertyDecl *Property = Res.getAsSingle<ObjCPropertyDecl>(); 3109 Diag(Property->getLocation(), diag::note_previous_decl) 3110 << Property->getDeclName(); 3111 3112 return LookupMemberExpr(Res, BaseExpr, IsArrow, OpLoc, SS, 3113 ObjCImpDecl); 3114 } 3115 3116 return ExprError(Diag(MemberLoc, diag::err_property_not_found) 3117 << MemberName << BaseType); 3118 } 3119 3120 // Handle the following exceptional case (*Obj).isa. 3121 if (!IsArrow && 3122 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) && 3123 MemberName.getAsIdentifierInfo()->isStr("isa")) 3124 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc, 3125 Context.getObjCClassType())); 3126 3127 // Handle 'field access' to vectors, such as 'V.xx'. 3128 if (BaseType->isExtVectorType()) { 3129 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 3130 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc); 3131 if (ret.isNull()) 3132 return ExprError(); 3133 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member, 3134 MemberLoc)); 3135 } 3136 3137 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union) 3138 << BaseType << BaseExpr->getSourceRange(); 3139 3140 return ExprError(); 3141} 3142 3143static Sema::OwningExprResult DiagnoseDtorReference(Sema &SemaRef, 3144 SourceLocation NameLoc, 3145 Sema::ExprArg MemExpr) { 3146 Expr *E = (Expr *) MemExpr.get(); 3147 SourceLocation ExpectedLParenLoc = SemaRef.PP.getLocForEndOfToken(NameLoc); 3148 SemaRef.Diag(E->getLocStart(), diag::err_dtor_expr_without_call) 3149 << isa<CXXPseudoDestructorExpr>(E) 3150 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()"); 3151 3152 return SemaRef.ActOnCallExpr(/*Scope*/ 0, 3153 move(MemExpr), 3154 /*LPLoc*/ ExpectedLParenLoc, 3155 Sema::MultiExprArg(SemaRef, 0, 0), 3156 /*CommaLocs*/ 0, 3157 /*RPLoc*/ ExpectedLParenLoc); 3158} 3159 3160/// The main callback when the parser finds something like 3161/// expression . [nested-name-specifier] identifier 3162/// expression -> [nested-name-specifier] identifier 3163/// where 'identifier' encompasses a fairly broad spectrum of 3164/// possibilities, including destructor and operator references. 3165/// 3166/// \param OpKind either tok::arrow or tok::period 3167/// \param HasTrailingLParen whether the next token is '(', which 3168/// is used to diagnose mis-uses of special members that can 3169/// only be called 3170/// \param ObjCImpDecl the current ObjC @implementation decl; 3171/// this is an ugly hack around the fact that ObjC @implementations 3172/// aren't properly put in the context chain 3173Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg BaseArg, 3174 SourceLocation OpLoc, 3175 tok::TokenKind OpKind, 3176 const CXXScopeSpec &SS, 3177 UnqualifiedId &Id, 3178 DeclPtrTy ObjCImpDecl, 3179 bool HasTrailingLParen) { 3180 if (SS.isSet() && SS.isInvalid()) 3181 return ExprError(); 3182 3183 TemplateArgumentListInfo TemplateArgsBuffer; 3184 3185 // Decompose the name into its component parts. 3186 DeclarationName Name; 3187 SourceLocation NameLoc; 3188 const TemplateArgumentListInfo *TemplateArgs; 3189 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, 3190 Name, NameLoc, TemplateArgs); 3191 3192 bool IsArrow = (OpKind == tok::arrow); 3193 3194 NamedDecl *FirstQualifierInScope 3195 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S, 3196 static_cast<NestedNameSpecifier*>(SS.getScopeRep()))); 3197 3198 // This is a postfix expression, so get rid of ParenListExprs. 3199 BaseArg = MaybeConvertParenListExprToParenExpr(S, move(BaseArg)); 3200 3201 Expr *Base = BaseArg.takeAs<Expr>(); 3202 OwningExprResult Result(*this); 3203 if (Base->getType()->isDependentType() || Name.isDependentName()) { 3204 Result = ActOnDependentMemberExpr(ExprArg(*this, Base), Base->getType(), 3205 IsArrow, OpLoc, 3206 SS, FirstQualifierInScope, 3207 Name, NameLoc, 3208 TemplateArgs); 3209 } else { 3210 LookupResult R(*this, Name, NameLoc, LookupMemberName); 3211 if (TemplateArgs) { 3212 // Re-use the lookup done for the template name. 3213 DecomposeTemplateName(R, Id); 3214 } else { 3215 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc, 3216 SS, ObjCImpDecl); 3217 3218 if (Result.isInvalid()) { 3219 Owned(Base); 3220 return ExprError(); 3221 } 3222 3223 if (Result.get()) { 3224 // The only way a reference to a destructor can be used is to 3225 // immediately call it, which falls into this case. If the 3226 // next token is not a '(', produce a diagnostic and build the 3227 // call now. 3228 if (!HasTrailingLParen && 3229 Id.getKind() == UnqualifiedId::IK_DestructorName) 3230 return DiagnoseDtorReference(*this, NameLoc, move(Result)); 3231 3232 return move(Result); 3233 } 3234 } 3235 3236 Result = BuildMemberReferenceExpr(ExprArg(*this, Base), Base->getType(), 3237 OpLoc, IsArrow, SS, FirstQualifierInScope, 3238 R, TemplateArgs); 3239 } 3240 3241 return move(Result); 3242} 3243 3244Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 3245 FunctionDecl *FD, 3246 ParmVarDecl *Param) { 3247 if (Param->hasUnparsedDefaultArg()) { 3248 Diag (CallLoc, 3249 diag::err_use_of_default_argument_to_function_declared_later) << 3250 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 3251 Diag(UnparsedDefaultArgLocs[Param], 3252 diag::note_default_argument_declared_here); 3253 } else { 3254 if (Param->hasUninstantiatedDefaultArg()) { 3255 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 3256 3257 // Instantiate the expression. 3258 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD); 3259 3260 InstantiatingTemplate Inst(*this, CallLoc, Param, 3261 ArgList.getInnermost().getFlatArgumentList(), 3262 ArgList.getInnermost().flat_size()); 3263 3264 OwningExprResult Result = SubstExpr(UninstExpr, ArgList); 3265 if (Result.isInvalid()) 3266 return ExprError(); 3267 3268 // Check the expression as an initializer for the parameter. 3269 InitializedEntity Entity 3270 = InitializedEntity::InitializeParameter(Param); 3271 InitializationKind Kind 3272 = InitializationKind::CreateCopy(Param->getLocation(), 3273 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin()); 3274 Expr *ResultE = Result.takeAs<Expr>(); 3275 3276 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1); 3277 Result = InitSeq.Perform(*this, Entity, Kind, 3278 MultiExprArg(*this, (void**)&ResultE, 1)); 3279 if (Result.isInvalid()) 3280 return ExprError(); 3281 3282 // Build the default argument expression. 3283 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, 3284 Result.takeAs<Expr>())); 3285 } 3286 3287 // If the default expression creates temporaries, we need to 3288 // push them to the current stack of expression temporaries so they'll 3289 // be properly destroyed. 3290 // FIXME: We should really be rebuilding the default argument with new 3291 // bound temporaries; see the comment in PR5810. 3292 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) 3293 ExprTemporaries.push_back(Param->getDefaultArgTemporary(i)); 3294 } 3295 3296 // We already type-checked the argument, so we know it works. 3297 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param)); 3298} 3299 3300/// ConvertArgumentsForCall - Converts the arguments specified in 3301/// Args/NumArgs to the parameter types of the function FDecl with 3302/// function prototype Proto. Call is the call expression itself, and 3303/// Fn is the function expression. For a C++ member function, this 3304/// routine does not attempt to convert the object argument. Returns 3305/// true if the call is ill-formed. 3306bool 3307Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 3308 FunctionDecl *FDecl, 3309 const FunctionProtoType *Proto, 3310 Expr **Args, unsigned NumArgs, 3311 SourceLocation RParenLoc) { 3312 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 3313 // assignment, to the types of the corresponding parameter, ... 3314 unsigned NumArgsInProto = Proto->getNumArgs(); 3315 bool Invalid = false; 3316 3317 // If too few arguments are available (and we don't have default 3318 // arguments for the remaining parameters), don't make the call. 3319 if (NumArgs < NumArgsInProto) { 3320 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments()) 3321 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args) 3322 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange(); 3323 Call->setNumArgs(Context, NumArgsInProto); 3324 } 3325 3326 // If too many are passed and not variadic, error on the extras and drop 3327 // them. 3328 if (NumArgs > NumArgsInProto) { 3329 if (!Proto->isVariadic()) { 3330 Diag(Args[NumArgsInProto]->getLocStart(), 3331 diag::err_typecheck_call_too_many_args) 3332 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange() 3333 << SourceRange(Args[NumArgsInProto]->getLocStart(), 3334 Args[NumArgs-1]->getLocEnd()); 3335 // This deletes the extra arguments. 3336 Call->setNumArgs(Context, NumArgsInProto); 3337 return true; 3338 } 3339 } 3340 llvm::SmallVector<Expr *, 8> AllArgs; 3341 VariadicCallType CallType = 3342 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply; 3343 if (Fn->getType()->isBlockPointerType()) 3344 CallType = VariadicBlock; // Block 3345 else if (isa<MemberExpr>(Fn)) 3346 CallType = VariadicMethod; 3347 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl, 3348 Proto, 0, Args, NumArgs, AllArgs, CallType); 3349 if (Invalid) 3350 return true; 3351 unsigned TotalNumArgs = AllArgs.size(); 3352 for (unsigned i = 0; i < TotalNumArgs; ++i) 3353 Call->setArg(i, AllArgs[i]); 3354 3355 return false; 3356} 3357 3358bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, 3359 FunctionDecl *FDecl, 3360 const FunctionProtoType *Proto, 3361 unsigned FirstProtoArg, 3362 Expr **Args, unsigned NumArgs, 3363 llvm::SmallVector<Expr *, 8> &AllArgs, 3364 VariadicCallType CallType) { 3365 unsigned NumArgsInProto = Proto->getNumArgs(); 3366 unsigned NumArgsToCheck = NumArgs; 3367 bool Invalid = false; 3368 if (NumArgs != NumArgsInProto) 3369 // Use default arguments for missing arguments 3370 NumArgsToCheck = NumArgsInProto; 3371 unsigned ArgIx = 0; 3372 // Continue to check argument types (even if we have too few/many args). 3373 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) { 3374 QualType ProtoArgType = Proto->getArgType(i); 3375 3376 Expr *Arg; 3377 if (ArgIx < NumArgs) { 3378 Arg = Args[ArgIx++]; 3379 3380 if (RequireCompleteType(Arg->getSourceRange().getBegin(), 3381 ProtoArgType, 3382 PDiag(diag::err_call_incomplete_argument) 3383 << Arg->getSourceRange())) 3384 return true; 3385 3386 // Pass the argument 3387 ParmVarDecl *Param = 0; 3388 if (FDecl && i < FDecl->getNumParams()) 3389 Param = FDecl->getParamDecl(i); 3390 3391 3392 InitializedEntity Entity = 3393 Param? InitializedEntity::InitializeParameter(Param) 3394 : InitializedEntity::InitializeParameter(ProtoArgType); 3395 OwningExprResult ArgE = PerformCopyInitialization(Entity, 3396 SourceLocation(), 3397 Owned(Arg)); 3398 if (ArgE.isInvalid()) 3399 return true; 3400 3401 Arg = ArgE.takeAs<Expr>(); 3402 } else { 3403 ParmVarDecl *Param = FDecl->getParamDecl(i); 3404 3405 OwningExprResult ArgExpr = 3406 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 3407 if (ArgExpr.isInvalid()) 3408 return true; 3409 3410 Arg = ArgExpr.takeAs<Expr>(); 3411 } 3412 AllArgs.push_back(Arg); 3413 } 3414 3415 // If this is a variadic call, handle args passed through "...". 3416 if (CallType != VariadicDoesNotApply) { 3417 // Promote the arguments (C99 6.5.2.2p7). 3418 for (unsigned i = ArgIx; i < NumArgs; i++) { 3419 Expr *Arg = Args[i]; 3420 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType); 3421 AllArgs.push_back(Arg); 3422 } 3423 } 3424 return Invalid; 3425} 3426 3427/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 3428/// This provides the location of the left/right parens and a list of comma 3429/// locations. 3430Action::OwningExprResult 3431Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc, 3432 MultiExprArg args, 3433 SourceLocation *CommaLocs, SourceLocation RParenLoc) { 3434 unsigned NumArgs = args.size(); 3435 3436 // Since this might be a postfix expression, get rid of ParenListExprs. 3437 fn = MaybeConvertParenListExprToParenExpr(S, move(fn)); 3438 3439 Expr *Fn = fn.takeAs<Expr>(); 3440 Expr **Args = reinterpret_cast<Expr**>(args.release()); 3441 assert(Fn && "no function call expression"); 3442 3443 if (getLangOptions().CPlusPlus) { 3444 // If this is a pseudo-destructor expression, build the call immediately. 3445 if (isa<CXXPseudoDestructorExpr>(Fn)) { 3446 if (NumArgs > 0) { 3447 // Pseudo-destructor calls should not have any arguments. 3448 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 3449 << CodeModificationHint::CreateRemoval( 3450 SourceRange(Args[0]->getLocStart(), 3451 Args[NumArgs-1]->getLocEnd())); 3452 3453 for (unsigned I = 0; I != NumArgs; ++I) 3454 Args[I]->Destroy(Context); 3455 3456 NumArgs = 0; 3457 } 3458 3459 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy, 3460 RParenLoc)); 3461 } 3462 3463 // Determine whether this is a dependent call inside a C++ template, 3464 // in which case we won't do any semantic analysis now. 3465 // FIXME: Will need to cache the results of name lookup (including ADL) in 3466 // Fn. 3467 bool Dependent = false; 3468 if (Fn->isTypeDependent()) 3469 Dependent = true; 3470 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs)) 3471 Dependent = true; 3472 3473 if (Dependent) 3474 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs, 3475 Context.DependentTy, RParenLoc)); 3476 3477 // Determine whether this is a call to an object (C++ [over.call.object]). 3478 if (Fn->getType()->isRecordType()) 3479 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs, 3480 CommaLocs, RParenLoc)); 3481 3482 Expr *NakedFn = Fn->IgnoreParens(); 3483 3484 // Determine whether this is a call to an unresolved member function. 3485 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) { 3486 // If lookup was unresolved but not dependent (i.e. didn't find 3487 // an unresolved using declaration), it has to be an overloaded 3488 // function set, which means it must contain either multiple 3489 // declarations (all methods or method templates) or a single 3490 // method template. 3491 assert((MemE->getNumDecls() > 1) || 3492 isa<FunctionTemplateDecl>(*MemE->decls_begin())); 3493 (void)MemE; 3494 3495 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs, 3496 CommaLocs, RParenLoc); 3497 } 3498 3499 // Determine whether this is a call to a member function. 3500 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) { 3501 NamedDecl *MemDecl = MemExpr->getMemberDecl(); 3502 if (isa<CXXMethodDecl>(MemDecl)) 3503 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs, 3504 CommaLocs, RParenLoc); 3505 } 3506 3507 // Determine whether this is a call to a pointer-to-member function. 3508 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) { 3509 if (BO->getOpcode() == BinaryOperator::PtrMemD || 3510 BO->getOpcode() == BinaryOperator::PtrMemI) { 3511 if (const FunctionProtoType *FPT = 3512 dyn_cast<FunctionProtoType>(BO->getType())) { 3513 QualType ResultTy = FPT->getResultType().getNonReferenceType(); 3514 3515 ExprOwningPtr<CXXMemberCallExpr> 3516 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args, 3517 NumArgs, ResultTy, 3518 RParenLoc)); 3519 3520 if (CheckCallReturnType(FPT->getResultType(), 3521 BO->getRHS()->getSourceRange().getBegin(), 3522 TheCall.get(), 0)) 3523 return ExprError(); 3524 3525 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs, 3526 RParenLoc)) 3527 return ExprError(); 3528 3529 return Owned(MaybeBindToTemporary(TheCall.release()).release()); 3530 } 3531 return ExprError(Diag(Fn->getLocStart(), 3532 diag::err_typecheck_call_not_function) 3533 << Fn->getType() << Fn->getSourceRange()); 3534 } 3535 } 3536 } 3537 3538 // If we're directly calling a function, get the appropriate declaration. 3539 // Also, in C++, keep track of whether we should perform argument-dependent 3540 // lookup and whether there were any explicitly-specified template arguments. 3541 3542 Expr *NakedFn = Fn->IgnoreParens(); 3543 if (isa<UnresolvedLookupExpr>(NakedFn)) { 3544 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn); 3545 return BuildOverloadedCallExpr(Fn, ULE, LParenLoc, Args, NumArgs, 3546 CommaLocs, RParenLoc); 3547 } 3548 3549 NamedDecl *NDecl = 0; 3550 if (isa<DeclRefExpr>(NakedFn)) 3551 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 3552 3553 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc); 3554} 3555 3556/// BuildResolvedCallExpr - Build a call to a resolved expression, 3557/// i.e. an expression not of \p OverloadTy. The expression should 3558/// unary-convert to an expression of function-pointer or 3559/// block-pointer type. 3560/// 3561/// \param NDecl the declaration being called, if available 3562Sema::OwningExprResult 3563Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 3564 SourceLocation LParenLoc, 3565 Expr **Args, unsigned NumArgs, 3566 SourceLocation RParenLoc) { 3567 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 3568 3569 // Promote the function operand. 3570 UsualUnaryConversions(Fn); 3571 3572 // Make the call expr early, before semantic checks. This guarantees cleanup 3573 // of arguments and function on error. 3574 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn, 3575 Args, NumArgs, 3576 Context.BoolTy, 3577 RParenLoc)); 3578 3579 const FunctionType *FuncT; 3580 if (!Fn->getType()->isBlockPointerType()) { 3581 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 3582 // have type pointer to function". 3583 const PointerType *PT = Fn->getType()->getAs<PointerType>(); 3584 if (PT == 0) 3585 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 3586 << Fn->getType() << Fn->getSourceRange()); 3587 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 3588 } else { // This is a block call. 3589 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()-> 3590 getAs<FunctionType>(); 3591 } 3592 if (FuncT == 0) 3593 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 3594 << Fn->getType() << Fn->getSourceRange()); 3595 3596 // Check for a valid return type 3597 if (CheckCallReturnType(FuncT->getResultType(), 3598 Fn->getSourceRange().getBegin(), TheCall.get(), 3599 FDecl)) 3600 return ExprError(); 3601 3602 // We know the result type of the call, set it. 3603 TheCall->setType(FuncT->getResultType().getNonReferenceType()); 3604 3605 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) { 3606 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs, 3607 RParenLoc)) 3608 return ExprError(); 3609 } else { 3610 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 3611 3612 if (FDecl) { 3613 // Check if we have too few/too many template arguments, based 3614 // on our knowledge of the function definition. 3615 const FunctionDecl *Def = 0; 3616 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) { 3617 const FunctionProtoType *Proto = 3618 Def->getType()->getAs<FunctionProtoType>(); 3619 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) { 3620 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 3621 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange(); 3622 } 3623 } 3624 } 3625 3626 // Promote the arguments (C99 6.5.2.2p6). 3627 for (unsigned i = 0; i != NumArgs; i++) { 3628 Expr *Arg = Args[i]; 3629 DefaultArgumentPromotion(Arg); 3630 if (RequireCompleteType(Arg->getSourceRange().getBegin(), 3631 Arg->getType(), 3632 PDiag(diag::err_call_incomplete_argument) 3633 << Arg->getSourceRange())) 3634 return ExprError(); 3635 TheCall->setArg(i, Arg); 3636 } 3637 } 3638 3639 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 3640 if (!Method->isStatic()) 3641 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 3642 << Fn->getSourceRange()); 3643 3644 // Check for sentinels 3645 if (NDecl) 3646 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs); 3647 3648 // Do special checking on direct calls to functions. 3649 if (FDecl) { 3650 if (CheckFunctionCall(FDecl, TheCall.get())) 3651 return ExprError(); 3652 3653 if (unsigned BuiltinID = FDecl->getBuiltinID()) 3654 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take()); 3655 } else if (NDecl) { 3656 if (CheckBlockCall(NDecl, TheCall.get())) 3657 return ExprError(); 3658 } 3659 3660 return MaybeBindToTemporary(TheCall.take()); 3661} 3662 3663Action::OwningExprResult 3664Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty, 3665 SourceLocation RParenLoc, ExprArg InitExpr) { 3666 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type"); 3667 // FIXME: put back this assert when initializers are worked out. 3668 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 3669 3670 TypeSourceInfo *TInfo; 3671 QualType literalType = GetTypeFromParser(Ty, &TInfo); 3672 if (!TInfo) 3673 TInfo = Context.getTrivialTypeSourceInfo(literalType); 3674 3675 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, move(InitExpr)); 3676} 3677 3678Action::OwningExprResult 3679Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 3680 SourceLocation RParenLoc, ExprArg InitExpr) { 3681 QualType literalType = TInfo->getType(); 3682 Expr *literalExpr = static_cast<Expr*>(InitExpr.get()); 3683 3684 if (literalType->isArrayType()) { 3685 if (literalType->isVariableArrayType()) 3686 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 3687 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())); 3688 } else if (!literalType->isDependentType() && 3689 RequireCompleteType(LParenLoc, literalType, 3690 PDiag(diag::err_typecheck_decl_incomplete_type) 3691 << SourceRange(LParenLoc, 3692 literalExpr->getSourceRange().getEnd()))) 3693 return ExprError(); 3694 3695 InitializedEntity Entity 3696 = InitializedEntity::InitializeTemporary(literalType); 3697 InitializationKind Kind 3698 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc), 3699 /*IsCStyleCast=*/true); 3700 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1); 3701 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, 3702 MultiExprArg(*this, (void**)&literalExpr, 1), 3703 &literalType); 3704 if (Result.isInvalid()) 3705 return ExprError(); 3706 InitExpr.release(); 3707 literalExpr = static_cast<Expr*>(Result.get()); 3708 3709 bool isFileScope = getCurFunctionOrMethodDecl() == 0; 3710 if (isFileScope) { // 6.5.2.5p3 3711 if (CheckForConstantInitializer(literalExpr, literalType)) 3712 return ExprError(); 3713 } 3714 3715 Result.release(); 3716 3717 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 3718 literalExpr, isFileScope)); 3719} 3720 3721Action::OwningExprResult 3722Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist, 3723 SourceLocation RBraceLoc) { 3724 unsigned NumInit = initlist.size(); 3725 Expr **InitList = reinterpret_cast<Expr**>(initlist.release()); 3726 3727 // Semantic analysis for initializers is done by ActOnDeclarator() and 3728 // CheckInitializer() - it requires knowledge of the object being intialized. 3729 3730 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit, 3731 RBraceLoc); 3732 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 3733 return Owned(E); 3734} 3735 3736static CastExpr::CastKind getScalarCastKind(ASTContext &Context, 3737 QualType SrcTy, QualType DestTy) { 3738 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 3739 return CastExpr::CK_NoOp; 3740 3741 if (SrcTy->hasPointerRepresentation()) { 3742 if (DestTy->hasPointerRepresentation()) 3743 return DestTy->isObjCObjectPointerType() ? 3744 CastExpr::CK_AnyPointerToObjCPointerCast : 3745 CastExpr::CK_BitCast; 3746 if (DestTy->isIntegerType()) 3747 return CastExpr::CK_PointerToIntegral; 3748 } 3749 3750 if (SrcTy->isIntegerType()) { 3751 if (DestTy->isIntegerType()) 3752 return CastExpr::CK_IntegralCast; 3753 if (DestTy->hasPointerRepresentation()) 3754 return CastExpr::CK_IntegralToPointer; 3755 if (DestTy->isRealFloatingType()) 3756 return CastExpr::CK_IntegralToFloating; 3757 } 3758 3759 if (SrcTy->isRealFloatingType()) { 3760 if (DestTy->isRealFloatingType()) 3761 return CastExpr::CK_FloatingCast; 3762 if (DestTy->isIntegerType()) 3763 return CastExpr::CK_FloatingToIntegral; 3764 } 3765 3766 // FIXME: Assert here. 3767 // assert(false && "Unhandled cast combination!"); 3768 return CastExpr::CK_Unknown; 3769} 3770 3771/// CheckCastTypes - Check type constraints for casting between types. 3772bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr, 3773 CastExpr::CastKind& Kind, 3774 CXXMethodDecl *& ConversionDecl, 3775 bool FunctionalStyle) { 3776 if (getLangOptions().CPlusPlus) 3777 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle, 3778 ConversionDecl); 3779 3780 DefaultFunctionArrayConversion(castExpr); 3781 3782 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression 3783 // type needs to be scalar. 3784 if (castType->isVoidType()) { 3785 // Cast to void allows any expr type. 3786 Kind = CastExpr::CK_ToVoid; 3787 return false; 3788 } 3789 3790 if (!castType->isScalarType() && !castType->isVectorType()) { 3791 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) && 3792 (castType->isStructureType() || castType->isUnionType())) { 3793 // GCC struct/union extension: allow cast to self. 3794 // FIXME: Check that the cast destination type is complete. 3795 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar) 3796 << castType << castExpr->getSourceRange(); 3797 Kind = CastExpr::CK_NoOp; 3798 return false; 3799 } 3800 3801 if (castType->isUnionType()) { 3802 // GCC cast to union extension 3803 RecordDecl *RD = castType->getAs<RecordType>()->getDecl(); 3804 RecordDecl::field_iterator Field, FieldEnd; 3805 for (Field = RD->field_begin(), FieldEnd = RD->field_end(); 3806 Field != FieldEnd; ++Field) { 3807 if (Context.hasSameUnqualifiedType(Field->getType(), 3808 castExpr->getType())) { 3809 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union) 3810 << castExpr->getSourceRange(); 3811 break; 3812 } 3813 } 3814 if (Field == FieldEnd) 3815 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type) 3816 << castExpr->getType() << castExpr->getSourceRange(); 3817 Kind = CastExpr::CK_ToUnion; 3818 return false; 3819 } 3820 3821 // Reject any other conversions to non-scalar types. 3822 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar) 3823 << castType << castExpr->getSourceRange(); 3824 } 3825 3826 if (!castExpr->getType()->isScalarType() && 3827 !castExpr->getType()->isVectorType()) { 3828 return Diag(castExpr->getLocStart(), 3829 diag::err_typecheck_expect_scalar_operand) 3830 << castExpr->getType() << castExpr->getSourceRange(); 3831 } 3832 3833 if (castType->isExtVectorType()) 3834 return CheckExtVectorCast(TyR, castType, castExpr, Kind); 3835 3836 if (castType->isVectorType()) 3837 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind); 3838 if (castExpr->getType()->isVectorType()) 3839 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind); 3840 3841 if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) 3842 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR; 3843 3844 if (isa<ObjCSelectorExpr>(castExpr)) 3845 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr); 3846 3847 if (!castType->isArithmeticType()) { 3848 QualType castExprType = castExpr->getType(); 3849 if (!castExprType->isIntegralType() && castExprType->isArithmeticType()) 3850 return Diag(castExpr->getLocStart(), 3851 diag::err_cast_pointer_from_non_pointer_int) 3852 << castExprType << castExpr->getSourceRange(); 3853 } else if (!castExpr->getType()->isArithmeticType()) { 3854 if (!castType->isIntegralType() && castType->isArithmeticType()) 3855 return Diag(castExpr->getLocStart(), 3856 diag::err_cast_pointer_to_non_pointer_int) 3857 << castType << castExpr->getSourceRange(); 3858 } 3859 3860 Kind = getScalarCastKind(Context, castExpr->getType(), castType); 3861 return false; 3862} 3863 3864bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 3865 CastExpr::CastKind &Kind) { 3866 assert(VectorTy->isVectorType() && "Not a vector type!"); 3867 3868 if (Ty->isVectorType() || Ty->isIntegerType()) { 3869 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty)) 3870 return Diag(R.getBegin(), 3871 Ty->isVectorType() ? 3872 diag::err_invalid_conversion_between_vectors : 3873 diag::err_invalid_conversion_between_vector_and_integer) 3874 << VectorTy << Ty << R; 3875 } else 3876 return Diag(R.getBegin(), 3877 diag::err_invalid_conversion_between_vector_and_scalar) 3878 << VectorTy << Ty << R; 3879 3880 Kind = CastExpr::CK_BitCast; 3881 return false; 3882} 3883 3884bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr, 3885 CastExpr::CastKind &Kind) { 3886 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 3887 3888 QualType SrcTy = CastExpr->getType(); 3889 3890 // If SrcTy is a VectorType, the total size must match to explicitly cast to 3891 // an ExtVectorType. 3892 if (SrcTy->isVectorType()) { 3893 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) 3894 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 3895 << DestTy << SrcTy << R; 3896 Kind = CastExpr::CK_BitCast; 3897 return false; 3898 } 3899 3900 // All non-pointer scalars can be cast to ExtVector type. The appropriate 3901 // conversion will take place first from scalar to elt type, and then 3902 // splat from elt type to vector. 3903 if (SrcTy->isPointerType()) 3904 return Diag(R.getBegin(), 3905 diag::err_invalid_conversion_between_vector_and_scalar) 3906 << DestTy << SrcTy << R; 3907 3908 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType(); 3909 ImpCastExprToType(CastExpr, DestElemTy, 3910 getScalarCastKind(Context, SrcTy, DestElemTy)); 3911 3912 Kind = CastExpr::CK_VectorSplat; 3913 return false; 3914} 3915 3916Action::OwningExprResult 3917Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty, 3918 SourceLocation RParenLoc, ExprArg Op) { 3919 assert((Ty != 0) && (Op.get() != 0) && 3920 "ActOnCastExpr(): missing type or expr"); 3921 3922 TypeSourceInfo *castTInfo; 3923 QualType castType = GetTypeFromParser(Ty, &castTInfo); 3924 if (!castTInfo) 3925 castTInfo = Context.getTrivialTypeSourceInfo(castType); 3926 3927 // If the Expr being casted is a ParenListExpr, handle it specially. 3928 Expr *castExpr = (Expr *)Op.get(); 3929 if (isa<ParenListExpr>(castExpr)) 3930 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op), 3931 castTInfo); 3932 3933 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, move(Op)); 3934} 3935 3936Action::OwningExprResult 3937Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, 3938 SourceLocation RParenLoc, ExprArg Op) { 3939 Expr *castExpr = static_cast<Expr*>(Op.get()); 3940 3941 CXXMethodDecl *Method = 0; 3942 CastExpr::CastKind Kind = CastExpr::CK_Unknown; 3943 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr, 3944 Kind, Method)) 3945 return ExprError(); 3946 3947 if (Method) { 3948 // FIXME: preserve type source info here 3949 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, Ty->getType(), 3950 Kind, Method, move(Op)); 3951 3952 if (CastArg.isInvalid()) 3953 return ExprError(); 3954 3955 castExpr = CastArg.takeAs<Expr>(); 3956 } else { 3957 Op.release(); 3958 } 3959 3960 return Owned(new (Context) CStyleCastExpr(Ty->getType().getNonReferenceType(), 3961 Kind, castExpr, Ty, 3962 LParenLoc, RParenLoc)); 3963} 3964 3965/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence 3966/// of comma binary operators. 3967Action::OwningExprResult 3968Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) { 3969 Expr *expr = EA.takeAs<Expr>(); 3970 ParenListExpr *E = dyn_cast<ParenListExpr>(expr); 3971 if (!E) 3972 return Owned(expr); 3973 3974 OwningExprResult Result(*this, E->getExpr(0)); 3975 3976 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 3977 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result), 3978 Owned(E->getExpr(i))); 3979 3980 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result)); 3981} 3982 3983Action::OwningExprResult 3984Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc, 3985 SourceLocation RParenLoc, ExprArg Op, 3986 TypeSourceInfo *TInfo) { 3987 ParenListExpr *PE = (ParenListExpr *)Op.get(); 3988 QualType Ty = TInfo->getType(); 3989 3990 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')' 3991 // then handle it as such. 3992 if (getLangOptions().AltiVec && Ty->isVectorType()) { 3993 if (PE->getNumExprs() == 0) { 3994 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer); 3995 return ExprError(); 3996 } 3997 3998 llvm::SmallVector<Expr *, 8> initExprs; 3999 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i) 4000 initExprs.push_back(PE->getExpr(i)); 4001 4002 // FIXME: This means that pretty-printing the final AST will produce curly 4003 // braces instead of the original commas. 4004 Op.release(); 4005 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0], 4006 initExprs.size(), RParenLoc); 4007 E->setType(Ty); 4008 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, Owned(E)); 4009 } else { 4010 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 4011 // sequence of BinOp comma operators. 4012 Op = MaybeConvertParenListExprToParenExpr(S, move(Op)); 4013 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, move(Op)); 4014 } 4015} 4016 4017Action::OwningExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L, 4018 SourceLocation R, 4019 MultiExprArg Val, 4020 TypeTy *TypeOfCast) { 4021 unsigned nexprs = Val.size(); 4022 Expr **exprs = reinterpret_cast<Expr**>(Val.release()); 4023 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list"); 4024 Expr *expr; 4025 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast)) 4026 expr = new (Context) ParenExpr(L, R, exprs[0]); 4027 else 4028 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R); 4029 return Owned(expr); 4030} 4031 4032/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension. 4033/// In that case, lhs = cond. 4034/// C99 6.5.15 4035QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS, 4036 SourceLocation QuestionLoc) { 4037 // C++ is sufficiently different to merit its own checker. 4038 if (getLangOptions().CPlusPlus) 4039 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc); 4040 4041 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional); 4042 4043 UsualUnaryConversions(Cond); 4044 UsualUnaryConversions(LHS); 4045 UsualUnaryConversions(RHS); 4046 QualType CondTy = Cond->getType(); 4047 QualType LHSTy = LHS->getType(); 4048 QualType RHSTy = RHS->getType(); 4049 4050 // first, check the condition. 4051 if (!CondTy->isScalarType()) { // C99 6.5.15p2 4052 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) 4053 << CondTy; 4054 return QualType(); 4055 } 4056 4057 // Now check the two expressions. 4058 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 4059 return CheckVectorOperands(QuestionLoc, LHS, RHS); 4060 4061 // If both operands have arithmetic type, do the usual arithmetic conversions 4062 // to find a common type: C99 6.5.15p3,5. 4063 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 4064 UsualArithmeticConversions(LHS, RHS); 4065 return LHS->getType(); 4066 } 4067 4068 // If both operands are the same structure or union type, the result is that 4069 // type. 4070 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 4071 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 4072 if (LHSRT->getDecl() == RHSRT->getDecl()) 4073 // "If both the operands have structure or union type, the result has 4074 // that type." This implies that CV qualifiers are dropped. 4075 return LHSTy.getUnqualifiedType(); 4076 // FIXME: Type of conditional expression must be complete in C mode. 4077 } 4078 4079 // C99 6.5.15p5: "If both operands have void type, the result has void type." 4080 // The following || allows only one side to be void (a GCC-ism). 4081 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 4082 if (!LHSTy->isVoidType()) 4083 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void) 4084 << RHS->getSourceRange(); 4085 if (!RHSTy->isVoidType()) 4086 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void) 4087 << LHS->getSourceRange(); 4088 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid); 4089 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid); 4090 return Context.VoidTy; 4091 } 4092 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 4093 // the type of the other operand." 4094 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) && 4095 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 4096 // promote the null to a pointer. 4097 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown); 4098 return LHSTy; 4099 } 4100 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) && 4101 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 4102 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown); 4103 return RHSTy; 4104 } 4105 4106 // All objective-c pointer type analysis is done here. 4107 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 4108 QuestionLoc); 4109 if (!compositeType.isNull()) 4110 return compositeType; 4111 4112 4113 // Handle block pointer types. 4114 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 4115 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 4116 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 4117 QualType destType = Context.getPointerType(Context.VoidTy); 4118 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast); 4119 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast); 4120 return destType; 4121 } 4122 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 4123 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 4124 return QualType(); 4125 } 4126 // We have 2 block pointer types. 4127 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 4128 // Two identical block pointer types are always compatible. 4129 return LHSTy; 4130 } 4131 // The block pointer types aren't identical, continue checking. 4132 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType(); 4133 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType(); 4134 4135 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(), 4136 rhptee.getUnqualifiedType())) { 4137 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers) 4138 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 4139 // In this situation, we assume void* type. No especially good 4140 // reason, but this is what gcc does, and we do have to pick 4141 // to get a consistent AST. 4142 QualType incompatTy = Context.getPointerType(Context.VoidTy); 4143 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast); 4144 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast); 4145 return incompatTy; 4146 } 4147 // The block pointer types are compatible. 4148 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast); 4149 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast); 4150 return LHSTy; 4151 } 4152 4153 // Check constraints for C object pointers types (C99 6.5.15p3,6). 4154 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 4155 // get the "pointed to" types 4156 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 4157 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 4158 4159 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 4160 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 4161 // Figure out necessary qualifiers (C99 6.5.15p6) 4162 QualType destPointee 4163 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 4164 QualType destType = Context.getPointerType(destPointee); 4165 // Add qualifiers if necessary. 4166 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp); 4167 // Promote to void*. 4168 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast); 4169 return destType; 4170 } 4171 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 4172 QualType destPointee 4173 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 4174 QualType destType = Context.getPointerType(destPointee); 4175 // Add qualifiers if necessary. 4176 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp); 4177 // Promote to void*. 4178 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast); 4179 return destType; 4180 } 4181 4182 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 4183 // Two identical pointer types are always compatible. 4184 return LHSTy; 4185 } 4186 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(), 4187 rhptee.getUnqualifiedType())) { 4188 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers) 4189 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 4190 // In this situation, we assume void* type. No especially good 4191 // reason, but this is what gcc does, and we do have to pick 4192 // to get a consistent AST. 4193 QualType incompatTy = Context.getPointerType(Context.VoidTy); 4194 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast); 4195 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast); 4196 return incompatTy; 4197 } 4198 // The pointer types are compatible. 4199 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to 4200 // differently qualified versions of compatible types, the result type is 4201 // a pointer to an appropriately qualified version of the *composite* 4202 // type. 4203 // FIXME: Need to calculate the composite type. 4204 // FIXME: Need to add qualifiers 4205 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast); 4206 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast); 4207 return LHSTy; 4208 } 4209 4210 // GCC compatibility: soften pointer/integer mismatch. 4211 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) { 4212 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch) 4213 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 4214 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer); 4215 return RHSTy; 4216 } 4217 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) { 4218 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch) 4219 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 4220 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer); 4221 return LHSTy; 4222 } 4223 4224 // Otherwise, the operands are not compatible. 4225 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 4226 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 4227 return QualType(); 4228} 4229 4230/// FindCompositeObjCPointerType - Helper method to find composite type of 4231/// two objective-c pointer types of the two input expressions. 4232QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS, 4233 SourceLocation QuestionLoc) { 4234 QualType LHSTy = LHS->getType(); 4235 QualType RHSTy = RHS->getType(); 4236 4237 // Handle things like Class and struct objc_class*. Here we case the result 4238 // to the pseudo-builtin, because that will be implicitly cast back to the 4239 // redefinition type if an attempt is made to access its fields. 4240 if (LHSTy->isObjCClassType() && 4241 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) { 4242 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast); 4243 return LHSTy; 4244 } 4245 if (RHSTy->isObjCClassType() && 4246 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) { 4247 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast); 4248 return RHSTy; 4249 } 4250 // And the same for struct objc_object* / id 4251 if (LHSTy->isObjCIdType() && 4252 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) { 4253 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast); 4254 return LHSTy; 4255 } 4256 if (RHSTy->isObjCIdType() && 4257 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) { 4258 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast); 4259 return RHSTy; 4260 } 4261 // And the same for struct objc_selector* / SEL 4262 if (Context.isObjCSelType(LHSTy) && 4263 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) { 4264 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast); 4265 return LHSTy; 4266 } 4267 if (Context.isObjCSelType(RHSTy) && 4268 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) { 4269 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast); 4270 return RHSTy; 4271 } 4272 // Check constraints for Objective-C object pointers types. 4273 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 4274 4275 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 4276 // Two identical object pointer types are always compatible. 4277 return LHSTy; 4278 } 4279 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>(); 4280 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>(); 4281 QualType compositeType = LHSTy; 4282 4283 // If both operands are interfaces and either operand can be 4284 // assigned to the other, use that type as the composite 4285 // type. This allows 4286 // xxx ? (A*) a : (B*) b 4287 // where B is a subclass of A. 4288 // 4289 // Additionally, as for assignment, if either type is 'id' 4290 // allow silent coercion. Finally, if the types are 4291 // incompatible then make sure to use 'id' as the composite 4292 // type so the result is acceptable for sending messages to. 4293 4294 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 4295 // It could return the composite type. 4296 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 4297 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 4298 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 4299 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 4300 } else if ((LHSTy->isObjCQualifiedIdType() || 4301 RHSTy->isObjCQualifiedIdType()) && 4302 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 4303 // Need to handle "id<xx>" explicitly. 4304 // GCC allows qualified id and any Objective-C type to devolve to 4305 // id. Currently localizing to here until clear this should be 4306 // part of ObjCQualifiedIdTypesAreCompatible. 4307 compositeType = Context.getObjCIdType(); 4308 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 4309 compositeType = Context.getObjCIdType(); 4310 } else if (!(compositeType = 4311 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) 4312 ; 4313 else { 4314 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 4315 << LHSTy << RHSTy 4316 << LHS->getSourceRange() << RHS->getSourceRange(); 4317 QualType incompatTy = Context.getObjCIdType(); 4318 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast); 4319 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast); 4320 return incompatTy; 4321 } 4322 // The object pointer types are compatible. 4323 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast); 4324 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast); 4325 return compositeType; 4326 } 4327 // Check Objective-C object pointer types and 'void *' 4328 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 4329 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 4330 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 4331 QualType destPointee 4332 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 4333 QualType destType = Context.getPointerType(destPointee); 4334 // Add qualifiers if necessary. 4335 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp); 4336 // Promote to void*. 4337 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast); 4338 return destType; 4339 } 4340 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 4341 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 4342 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 4343 QualType destPointee 4344 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 4345 QualType destType = Context.getPointerType(destPointee); 4346 // Add qualifiers if necessary. 4347 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp); 4348 // Promote to void*. 4349 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast); 4350 return destType; 4351 } 4352 return QualType(); 4353} 4354 4355/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 4356/// in the case of a the GNU conditional expr extension. 4357Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 4358 SourceLocation ColonLoc, 4359 ExprArg Cond, ExprArg LHS, 4360 ExprArg RHS) { 4361 Expr *CondExpr = (Expr *) Cond.get(); 4362 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get(); 4363 4364 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 4365 // was the condition. 4366 bool isLHSNull = LHSExpr == 0; 4367 if (isLHSNull) 4368 LHSExpr = CondExpr; 4369 4370 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, 4371 RHSExpr, QuestionLoc); 4372 if (result.isNull()) 4373 return ExprError(); 4374 4375 Cond.release(); 4376 LHS.release(); 4377 RHS.release(); 4378 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc, 4379 isLHSNull ? 0 : LHSExpr, 4380 ColonLoc, RHSExpr, result)); 4381} 4382 4383// CheckPointerTypesForAssignment - This is a very tricky routine (despite 4384// being closely modeled after the C99 spec:-). The odd characteristic of this 4385// routine is it effectively iqnores the qualifiers on the top level pointee. 4386// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 4387// FIXME: add a couple examples in this comment. 4388Sema::AssignConvertType 4389Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) { 4390 QualType lhptee, rhptee; 4391 4392 if ((lhsType->isObjCClassType() && 4393 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) || 4394 (rhsType->isObjCClassType() && 4395 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) { 4396 return Compatible; 4397 } 4398 4399 // get the "pointed to" type (ignoring qualifiers at the top level) 4400 lhptee = lhsType->getAs<PointerType>()->getPointeeType(); 4401 rhptee = rhsType->getAs<PointerType>()->getPointeeType(); 4402 4403 // make sure we operate on the canonical type 4404 lhptee = Context.getCanonicalType(lhptee); 4405 rhptee = Context.getCanonicalType(rhptee); 4406 4407 AssignConvertType ConvTy = Compatible; 4408 4409 // C99 6.5.16.1p1: This following citation is common to constraints 4410 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 4411 // qualifiers of the type *pointed to* by the right; 4412 // FIXME: Handle ExtQualType 4413 if (!lhptee.isAtLeastAsQualifiedAs(rhptee)) 4414 ConvTy = CompatiblePointerDiscardsQualifiers; 4415 4416 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 4417 // incomplete type and the other is a pointer to a qualified or unqualified 4418 // version of void... 4419 if (lhptee->isVoidType()) { 4420 if (rhptee->isIncompleteOrObjectType()) 4421 return ConvTy; 4422 4423 // As an extension, we allow cast to/from void* to function pointer. 4424 assert(rhptee->isFunctionType()); 4425 return FunctionVoidPointer; 4426 } 4427 4428 if (rhptee->isVoidType()) { 4429 if (lhptee->isIncompleteOrObjectType()) 4430 return ConvTy; 4431 4432 // As an extension, we allow cast to/from void* to function pointer. 4433 assert(lhptee->isFunctionType()); 4434 return FunctionVoidPointer; 4435 } 4436 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 4437 // unqualified versions of compatible types, ... 4438 lhptee = lhptee.getUnqualifiedType(); 4439 rhptee = rhptee.getUnqualifiedType(); 4440 if (!Context.typesAreCompatible(lhptee, rhptee)) { 4441 // Check if the pointee types are compatible ignoring the sign. 4442 // We explicitly check for char so that we catch "char" vs 4443 // "unsigned char" on systems where "char" is unsigned. 4444 if (lhptee->isCharType()) 4445 lhptee = Context.UnsignedCharTy; 4446 else if (lhptee->isSignedIntegerType()) 4447 lhptee = Context.getCorrespondingUnsignedType(lhptee); 4448 4449 if (rhptee->isCharType()) 4450 rhptee = Context.UnsignedCharTy; 4451 else if (rhptee->isSignedIntegerType()) 4452 rhptee = Context.getCorrespondingUnsignedType(rhptee); 4453 4454 if (lhptee == rhptee) { 4455 // Types are compatible ignoring the sign. Qualifier incompatibility 4456 // takes priority over sign incompatibility because the sign 4457 // warning can be disabled. 4458 if (ConvTy != Compatible) 4459 return ConvTy; 4460 return IncompatiblePointerSign; 4461 } 4462 4463 // If we are a multi-level pointer, it's possible that our issue is simply 4464 // one of qualification - e.g. char ** -> const char ** is not allowed. If 4465 // the eventual target type is the same and the pointers have the same 4466 // level of indirection, this must be the issue. 4467 if (lhptee->isPointerType() && rhptee->isPointerType()) { 4468 do { 4469 lhptee = lhptee->getAs<PointerType>()->getPointeeType(); 4470 rhptee = rhptee->getAs<PointerType>()->getPointeeType(); 4471 4472 lhptee = Context.getCanonicalType(lhptee); 4473 rhptee = Context.getCanonicalType(rhptee); 4474 } while (lhptee->isPointerType() && rhptee->isPointerType()); 4475 4476 if (Context.hasSameUnqualifiedType(lhptee, rhptee)) 4477 return IncompatibleNestedPointerQualifiers; 4478 } 4479 4480 // General pointer incompatibility takes priority over qualifiers. 4481 return IncompatiblePointer; 4482 } 4483 return ConvTy; 4484} 4485 4486/// CheckBlockPointerTypesForAssignment - This routine determines whether two 4487/// block pointer types are compatible or whether a block and normal pointer 4488/// are compatible. It is more restrict than comparing two function pointer 4489// types. 4490Sema::AssignConvertType 4491Sema::CheckBlockPointerTypesForAssignment(QualType lhsType, 4492 QualType rhsType) { 4493 QualType lhptee, rhptee; 4494 4495 // get the "pointed to" type (ignoring qualifiers at the top level) 4496 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType(); 4497 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType(); 4498 4499 // make sure we operate on the canonical type 4500 lhptee = Context.getCanonicalType(lhptee); 4501 rhptee = Context.getCanonicalType(rhptee); 4502 4503 AssignConvertType ConvTy = Compatible; 4504 4505 // For blocks we enforce that qualifiers are identical. 4506 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers()) 4507 ConvTy = CompatiblePointerDiscardsQualifiers; 4508 4509 if (!Context.typesAreCompatible(lhptee, rhptee)) 4510 return IncompatibleBlockPointer; 4511 return ConvTy; 4512} 4513 4514/// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types 4515/// for assignment compatibility. 4516Sema::AssignConvertType 4517Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) { 4518 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType()) 4519 return Compatible; 4520 QualType lhptee = 4521 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType(); 4522 QualType rhptee = 4523 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType(); 4524 // make sure we operate on the canonical type 4525 lhptee = Context.getCanonicalType(lhptee); 4526 rhptee = Context.getCanonicalType(rhptee); 4527 if (!lhptee.isAtLeastAsQualifiedAs(rhptee)) 4528 return CompatiblePointerDiscardsQualifiers; 4529 4530 if (Context.typesAreCompatible(lhsType, rhsType)) 4531 return Compatible; 4532 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) 4533 return IncompatibleObjCQualifiedId; 4534 return IncompatiblePointer; 4535} 4536 4537/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 4538/// has code to accommodate several GCC extensions when type checking 4539/// pointers. Here are some objectionable examples that GCC considers warnings: 4540/// 4541/// int a, *pint; 4542/// short *pshort; 4543/// struct foo *pfoo; 4544/// 4545/// pint = pshort; // warning: assignment from incompatible pointer type 4546/// a = pint; // warning: assignment makes integer from pointer without a cast 4547/// pint = a; // warning: assignment makes pointer from integer without a cast 4548/// pint = pfoo; // warning: assignment from incompatible pointer type 4549/// 4550/// As a result, the code for dealing with pointers is more complex than the 4551/// C99 spec dictates. 4552/// 4553Sema::AssignConvertType 4554Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) { 4555 // Get canonical types. We're not formatting these types, just comparing 4556 // them. 4557 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType(); 4558 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType(); 4559 4560 if (lhsType == rhsType) 4561 return Compatible; // Common case: fast path an exact match. 4562 4563 if ((lhsType->isObjCClassType() && 4564 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) || 4565 (rhsType->isObjCClassType() && 4566 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) { 4567 return Compatible; 4568 } 4569 4570 // If the left-hand side is a reference type, then we are in a 4571 // (rare!) case where we've allowed the use of references in C, 4572 // e.g., as a parameter type in a built-in function. In this case, 4573 // just make sure that the type referenced is compatible with the 4574 // right-hand side type. The caller is responsible for adjusting 4575 // lhsType so that the resulting expression does not have reference 4576 // type. 4577 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) { 4578 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) 4579 return Compatible; 4580 return Incompatible; 4581 } 4582 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 4583 // to the same ExtVector type. 4584 if (lhsType->isExtVectorType()) { 4585 if (rhsType->isExtVectorType()) 4586 return lhsType == rhsType ? Compatible : Incompatible; 4587 if (!rhsType->isVectorType() && rhsType->isArithmeticType()) 4588 return Compatible; 4589 } 4590 4591 if (lhsType->isVectorType() || rhsType->isVectorType()) { 4592 // If we are allowing lax vector conversions, and LHS and RHS are both 4593 // vectors, the total size only needs to be the same. This is a bitcast; 4594 // no bits are changed but the result type is different. 4595 if (getLangOptions().LaxVectorConversions && 4596 lhsType->isVectorType() && rhsType->isVectorType()) { 4597 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType)) 4598 return IncompatibleVectors; 4599 } 4600 return Incompatible; 4601 } 4602 4603 if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) 4604 return Compatible; 4605 4606 if (isa<PointerType>(lhsType)) { 4607 if (rhsType->isIntegerType()) 4608 return IntToPointer; 4609 4610 if (isa<PointerType>(rhsType)) 4611 return CheckPointerTypesForAssignment(lhsType, rhsType); 4612 4613 // In general, C pointers are not compatible with ObjC object pointers. 4614 if (isa<ObjCObjectPointerType>(rhsType)) { 4615 if (lhsType->isVoidPointerType()) // an exception to the rule. 4616 return Compatible; 4617 return IncompatiblePointer; 4618 } 4619 if (rhsType->getAs<BlockPointerType>()) { 4620 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType()) 4621 return Compatible; 4622 4623 // Treat block pointers as objects. 4624 if (getLangOptions().ObjC1 && lhsType->isObjCIdType()) 4625 return Compatible; 4626 } 4627 return Incompatible; 4628 } 4629 4630 if (isa<BlockPointerType>(lhsType)) { 4631 if (rhsType->isIntegerType()) 4632 return IntToBlockPointer; 4633 4634 // Treat block pointers as objects. 4635 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) 4636 return Compatible; 4637 4638 if (rhsType->isBlockPointerType()) 4639 return CheckBlockPointerTypesForAssignment(lhsType, rhsType); 4640 4641 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) { 4642 if (RHSPT->getPointeeType()->isVoidType()) 4643 return Compatible; 4644 } 4645 return Incompatible; 4646 } 4647 4648 if (isa<ObjCObjectPointerType>(lhsType)) { 4649 if (rhsType->isIntegerType()) 4650 return IntToPointer; 4651 4652 // In general, C pointers are not compatible with ObjC object pointers. 4653 if (isa<PointerType>(rhsType)) { 4654 if (rhsType->isVoidPointerType()) // an exception to the rule. 4655 return Compatible; 4656 return IncompatiblePointer; 4657 } 4658 if (rhsType->isObjCObjectPointerType()) { 4659 return CheckObjCPointerTypesForAssignment(lhsType, rhsType); 4660 } 4661 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) { 4662 if (RHSPT->getPointeeType()->isVoidType()) 4663 return Compatible; 4664 } 4665 // Treat block pointers as objects. 4666 if (rhsType->isBlockPointerType()) 4667 return Compatible; 4668 return Incompatible; 4669 } 4670 if (isa<PointerType>(rhsType)) { 4671 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer. 4672 if (lhsType == Context.BoolTy) 4673 return Compatible; 4674 4675 if (lhsType->isIntegerType()) 4676 return PointerToInt; 4677 4678 if (isa<PointerType>(lhsType)) 4679 return CheckPointerTypesForAssignment(lhsType, rhsType); 4680 4681 if (isa<BlockPointerType>(lhsType) && 4682 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType()) 4683 return Compatible; 4684 return Incompatible; 4685 } 4686 if (isa<ObjCObjectPointerType>(rhsType)) { 4687 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer. 4688 if (lhsType == Context.BoolTy) 4689 return Compatible; 4690 4691 if (lhsType->isIntegerType()) 4692 return PointerToInt; 4693 4694 // In general, C pointers are not compatible with ObjC object pointers. 4695 if (isa<PointerType>(lhsType)) { 4696 if (lhsType->isVoidPointerType()) // an exception to the rule. 4697 return Compatible; 4698 return IncompatiblePointer; 4699 } 4700 if (isa<BlockPointerType>(lhsType) && 4701 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType()) 4702 return Compatible; 4703 return Incompatible; 4704 } 4705 4706 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) { 4707 if (Context.typesAreCompatible(lhsType, rhsType)) 4708 return Compatible; 4709 } 4710 return Incompatible; 4711} 4712 4713/// \brief Constructs a transparent union from an expression that is 4714/// used to initialize the transparent union. 4715static void ConstructTransparentUnion(ASTContext &C, Expr *&E, 4716 QualType UnionType, FieldDecl *Field) { 4717 // Build an initializer list that designates the appropriate member 4718 // of the transparent union. 4719 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(), 4720 &E, 1, 4721 SourceLocation()); 4722 Initializer->setType(UnionType); 4723 Initializer->setInitializedFieldInUnion(Field); 4724 4725 // Build a compound literal constructing a value of the transparent 4726 // union type from this initializer list. 4727 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 4728 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 4729 Initializer, false); 4730} 4731 4732Sema::AssignConvertType 4733Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) { 4734 QualType FromType = rExpr->getType(); 4735 4736 // If the ArgType is a Union type, we want to handle a potential 4737 // transparent_union GCC extension. 4738 const RecordType *UT = ArgType->getAsUnionType(); 4739 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4740 return Incompatible; 4741 4742 // The field to initialize within the transparent union. 4743 RecordDecl *UD = UT->getDecl(); 4744 FieldDecl *InitField = 0; 4745 // It's compatible if the expression matches any of the fields. 4746 for (RecordDecl::field_iterator it = UD->field_begin(), 4747 itend = UD->field_end(); 4748 it != itend; ++it) { 4749 if (it->getType()->isPointerType()) { 4750 // If the transparent union contains a pointer type, we allow: 4751 // 1) void pointer 4752 // 2) null pointer constant 4753 if (FromType->isPointerType()) 4754 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 4755 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast); 4756 InitField = *it; 4757 break; 4758 } 4759 4760 if (rExpr->isNullPointerConstant(Context, 4761 Expr::NPC_ValueDependentIsNull)) { 4762 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer); 4763 InitField = *it; 4764 break; 4765 } 4766 } 4767 4768 if (CheckAssignmentConstraints(it->getType(), rExpr->getType()) 4769 == Compatible) { 4770 InitField = *it; 4771 break; 4772 } 4773 } 4774 4775 if (!InitField) 4776 return Incompatible; 4777 4778 ConstructTransparentUnion(Context, rExpr, ArgType, InitField); 4779 return Compatible; 4780} 4781 4782Sema::AssignConvertType 4783Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) { 4784 if (getLangOptions().CPlusPlus) { 4785 if (!lhsType->isRecordType()) { 4786 // C++ 5.17p3: If the left operand is not of class type, the 4787 // expression is implicitly converted (C++ 4) to the 4788 // cv-unqualified type of the left operand. 4789 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(), 4790 AA_Assigning)) 4791 return Incompatible; 4792 return Compatible; 4793 } 4794 4795 // FIXME: Currently, we fall through and treat C++ classes like C 4796 // structures. 4797 } 4798 4799 // C99 6.5.16.1p1: the left operand is a pointer and the right is 4800 // a null pointer constant. 4801 if ((lhsType->isPointerType() || 4802 lhsType->isObjCObjectPointerType() || 4803 lhsType->isBlockPointerType()) 4804 && rExpr->isNullPointerConstant(Context, 4805 Expr::NPC_ValueDependentIsNull)) { 4806 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown); 4807 return Compatible; 4808 } 4809 4810 // This check seems unnatural, however it is necessary to ensure the proper 4811 // conversion of functions/arrays. If the conversion were done for all 4812 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 4813 // expressions that surpress this implicit conversion (&, sizeof). 4814 // 4815 // Suppress this for references: C++ 8.5.3p5. 4816 if (!lhsType->isReferenceType()) 4817 DefaultFunctionArrayConversion(rExpr); 4818 4819 Sema::AssignConvertType result = 4820 CheckAssignmentConstraints(lhsType, rExpr->getType()); 4821 4822 // C99 6.5.16.1p2: The value of the right operand is converted to the 4823 // type of the assignment expression. 4824 // CheckAssignmentConstraints allows the left-hand side to be a reference, 4825 // so that we can use references in built-in functions even in C. 4826 // The getNonReferenceType() call makes sure that the resulting expression 4827 // does not have reference type. 4828 if (result != Incompatible && rExpr->getType() != lhsType) 4829 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(), 4830 CastExpr::CK_Unknown); 4831 return result; 4832} 4833 4834QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) { 4835 Diag(Loc, diag::err_typecheck_invalid_operands) 4836 << lex->getType() << rex->getType() 4837 << lex->getSourceRange() << rex->getSourceRange(); 4838 return QualType(); 4839} 4840 4841QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) { 4842 // For conversion purposes, we ignore any qualifiers. 4843 // For example, "const float" and "float" are equivalent. 4844 QualType lhsType = 4845 Context.getCanonicalType(lex->getType()).getUnqualifiedType(); 4846 QualType rhsType = 4847 Context.getCanonicalType(rex->getType()).getUnqualifiedType(); 4848 4849 // If the vector types are identical, return. 4850 if (lhsType == rhsType) 4851 return lhsType; 4852 4853 // Handle the case of a vector & extvector type of the same size and element 4854 // type. It would be nice if we only had one vector type someday. 4855 if (getLangOptions().LaxVectorConversions) { 4856 // FIXME: Should we warn here? 4857 if (const VectorType *LV = lhsType->getAs<VectorType>()) { 4858 if (const VectorType *RV = rhsType->getAs<VectorType>()) 4859 if (LV->getElementType() == RV->getElementType() && 4860 LV->getNumElements() == RV->getNumElements()) { 4861 return lhsType->isExtVectorType() ? lhsType : rhsType; 4862 } 4863 } 4864 } 4865 4866 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can 4867 // swap back (so that we don't reverse the inputs to a subtract, for instance. 4868 bool swapped = false; 4869 if (rhsType->isExtVectorType()) { 4870 swapped = true; 4871 std::swap(rex, lex); 4872 std::swap(rhsType, lhsType); 4873 } 4874 4875 // Handle the case of an ext vector and scalar. 4876 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) { 4877 QualType EltTy = LV->getElementType(); 4878 if (EltTy->isIntegralType() && rhsType->isIntegralType()) { 4879 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) { 4880 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast); 4881 if (swapped) std::swap(rex, lex); 4882 return lhsType; 4883 } 4884 } 4885 if (EltTy->isRealFloatingType() && rhsType->isScalarType() && 4886 rhsType->isRealFloatingType()) { 4887 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) { 4888 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast); 4889 if (swapped) std::swap(rex, lex); 4890 return lhsType; 4891 } 4892 } 4893 } 4894 4895 // Vectors of different size or scalar and non-ext-vector are errors. 4896 Diag(Loc, diag::err_typecheck_vector_not_convertable) 4897 << lex->getType() << rex->getType() 4898 << lex->getSourceRange() << rex->getSourceRange(); 4899 return QualType(); 4900} 4901 4902QualType Sema::CheckMultiplyDivideOperands( 4903 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) { 4904 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 4905 return CheckVectorOperands(Loc, lex, rex); 4906 4907 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 4908 4909 if (!lex->getType()->isArithmeticType() || 4910 !rex->getType()->isArithmeticType()) 4911 return InvalidOperands(Loc, lex, rex); 4912 4913 // Check for division by zero. 4914 if (isDiv && 4915 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull)) 4916 DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero) 4917 << rex->getSourceRange()); 4918 4919 return compType; 4920} 4921 4922QualType Sema::CheckRemainderOperands( 4923 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) { 4924 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) { 4925 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType()) 4926 return CheckVectorOperands(Loc, lex, rex); 4927 return InvalidOperands(Loc, lex, rex); 4928 } 4929 4930 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 4931 4932 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType()) 4933 return InvalidOperands(Loc, lex, rex); 4934 4935 // Check for remainder by zero. 4936 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull)) 4937 DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero) 4938 << rex->getSourceRange()); 4939 4940 return compType; 4941} 4942 4943QualType Sema::CheckAdditionOperands( // C99 6.5.6 4944 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) { 4945 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) { 4946 QualType compType = CheckVectorOperands(Loc, lex, rex); 4947 if (CompLHSTy) *CompLHSTy = compType; 4948 return compType; 4949 } 4950 4951 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy); 4952 4953 // handle the common case first (both operands are arithmetic). 4954 if (lex->getType()->isArithmeticType() && 4955 rex->getType()->isArithmeticType()) { 4956 if (CompLHSTy) *CompLHSTy = compType; 4957 return compType; 4958 } 4959 4960 // Put any potential pointer into PExp 4961 Expr* PExp = lex, *IExp = rex; 4962 if (IExp->getType()->isAnyPointerType()) 4963 std::swap(PExp, IExp); 4964 4965 if (PExp->getType()->isAnyPointerType()) { 4966 4967 if (IExp->getType()->isIntegerType()) { 4968 QualType PointeeTy = PExp->getType()->getPointeeType(); 4969 4970 // Check for arithmetic on pointers to incomplete types. 4971 if (PointeeTy->isVoidType()) { 4972 if (getLangOptions().CPlusPlus) { 4973 Diag(Loc, diag::err_typecheck_pointer_arith_void_type) 4974 << lex->getSourceRange() << rex->getSourceRange(); 4975 return QualType(); 4976 } 4977 4978 // GNU extension: arithmetic on pointer to void 4979 Diag(Loc, diag::ext_gnu_void_ptr) 4980 << lex->getSourceRange() << rex->getSourceRange(); 4981 } else if (PointeeTy->isFunctionType()) { 4982 if (getLangOptions().CPlusPlus) { 4983 Diag(Loc, diag::err_typecheck_pointer_arith_function_type) 4984 << lex->getType() << lex->getSourceRange(); 4985 return QualType(); 4986 } 4987 4988 // GNU extension: arithmetic on pointer to function 4989 Diag(Loc, diag::ext_gnu_ptr_func_arith) 4990 << lex->getType() << lex->getSourceRange(); 4991 } else { 4992 // Check if we require a complete type. 4993 if (((PExp->getType()->isPointerType() && 4994 !PExp->getType()->isDependentType()) || 4995 PExp->getType()->isObjCObjectPointerType()) && 4996 RequireCompleteType(Loc, PointeeTy, 4997 PDiag(diag::err_typecheck_arithmetic_incomplete_type) 4998 << PExp->getSourceRange() 4999 << PExp->getType())) 5000 return QualType(); 5001 } 5002 // Diagnose bad cases where we step over interface counts. 5003 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) { 5004 Diag(Loc, diag::err_arithmetic_nonfragile_interface) 5005 << PointeeTy << PExp->getSourceRange(); 5006 return QualType(); 5007 } 5008 5009 if (CompLHSTy) { 5010 QualType LHSTy = Context.isPromotableBitField(lex); 5011 if (LHSTy.isNull()) { 5012 LHSTy = lex->getType(); 5013 if (LHSTy->isPromotableIntegerType()) 5014 LHSTy = Context.getPromotedIntegerType(LHSTy); 5015 } 5016 *CompLHSTy = LHSTy; 5017 } 5018 return PExp->getType(); 5019 } 5020 } 5021 5022 return InvalidOperands(Loc, lex, rex); 5023} 5024 5025// C99 6.5.6 5026QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex, 5027 SourceLocation Loc, QualType* CompLHSTy) { 5028 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) { 5029 QualType compType = CheckVectorOperands(Loc, lex, rex); 5030 if (CompLHSTy) *CompLHSTy = compType; 5031 return compType; 5032 } 5033 5034 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy); 5035 5036 // Enforce type constraints: C99 6.5.6p3. 5037 5038 // Handle the common case first (both operands are arithmetic). 5039 if (lex->getType()->isArithmeticType() 5040 && rex->getType()->isArithmeticType()) { 5041 if (CompLHSTy) *CompLHSTy = compType; 5042 return compType; 5043 } 5044 5045 // Either ptr - int or ptr - ptr. 5046 if (lex->getType()->isAnyPointerType()) { 5047 QualType lpointee = lex->getType()->getPointeeType(); 5048 5049 // The LHS must be an completely-defined object type. 5050 5051 bool ComplainAboutVoid = false; 5052 Expr *ComplainAboutFunc = 0; 5053 if (lpointee->isVoidType()) { 5054 if (getLangOptions().CPlusPlus) { 5055 Diag(Loc, diag::err_typecheck_pointer_arith_void_type) 5056 << lex->getSourceRange() << rex->getSourceRange(); 5057 return QualType(); 5058 } 5059 5060 // GNU C extension: arithmetic on pointer to void 5061 ComplainAboutVoid = true; 5062 } else if (lpointee->isFunctionType()) { 5063 if (getLangOptions().CPlusPlus) { 5064 Diag(Loc, diag::err_typecheck_pointer_arith_function_type) 5065 << lex->getType() << lex->getSourceRange(); 5066 return QualType(); 5067 } 5068 5069 // GNU C extension: arithmetic on pointer to function 5070 ComplainAboutFunc = lex; 5071 } else if (!lpointee->isDependentType() && 5072 RequireCompleteType(Loc, lpointee, 5073 PDiag(diag::err_typecheck_sub_ptr_object) 5074 << lex->getSourceRange() 5075 << lex->getType())) 5076 return QualType(); 5077 5078 // Diagnose bad cases where we step over interface counts. 5079 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) { 5080 Diag(Loc, diag::err_arithmetic_nonfragile_interface) 5081 << lpointee << lex->getSourceRange(); 5082 return QualType(); 5083 } 5084 5085 // The result type of a pointer-int computation is the pointer type. 5086 if (rex->getType()->isIntegerType()) { 5087 if (ComplainAboutVoid) 5088 Diag(Loc, diag::ext_gnu_void_ptr) 5089 << lex->getSourceRange() << rex->getSourceRange(); 5090 if (ComplainAboutFunc) 5091 Diag(Loc, diag::ext_gnu_ptr_func_arith) 5092 << ComplainAboutFunc->getType() 5093 << ComplainAboutFunc->getSourceRange(); 5094 5095 if (CompLHSTy) *CompLHSTy = lex->getType(); 5096 return lex->getType(); 5097 } 5098 5099 // Handle pointer-pointer subtractions. 5100 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) { 5101 QualType rpointee = RHSPTy->getPointeeType(); 5102 5103 // RHS must be a completely-type object type. 5104 // Handle the GNU void* extension. 5105 if (rpointee->isVoidType()) { 5106 if (getLangOptions().CPlusPlus) { 5107 Diag(Loc, diag::err_typecheck_pointer_arith_void_type) 5108 << lex->getSourceRange() << rex->getSourceRange(); 5109 return QualType(); 5110 } 5111 5112 ComplainAboutVoid = true; 5113 } else if (rpointee->isFunctionType()) { 5114 if (getLangOptions().CPlusPlus) { 5115 Diag(Loc, diag::err_typecheck_pointer_arith_function_type) 5116 << rex->getType() << rex->getSourceRange(); 5117 return QualType(); 5118 } 5119 5120 // GNU extension: arithmetic on pointer to function 5121 if (!ComplainAboutFunc) 5122 ComplainAboutFunc = rex; 5123 } else if (!rpointee->isDependentType() && 5124 RequireCompleteType(Loc, rpointee, 5125 PDiag(diag::err_typecheck_sub_ptr_object) 5126 << rex->getSourceRange() 5127 << rex->getType())) 5128 return QualType(); 5129 5130 if (getLangOptions().CPlusPlus) { 5131 // Pointee types must be the same: C++ [expr.add] 5132 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 5133 Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 5134 << lex->getType() << rex->getType() 5135 << lex->getSourceRange() << rex->getSourceRange(); 5136 return QualType(); 5137 } 5138 } else { 5139 // Pointee types must be compatible C99 6.5.6p3 5140 if (!Context.typesAreCompatible( 5141 Context.getCanonicalType(lpointee).getUnqualifiedType(), 5142 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 5143 Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 5144 << lex->getType() << rex->getType() 5145 << lex->getSourceRange() << rex->getSourceRange(); 5146 return QualType(); 5147 } 5148 } 5149 5150 if (ComplainAboutVoid) 5151 Diag(Loc, diag::ext_gnu_void_ptr) 5152 << lex->getSourceRange() << rex->getSourceRange(); 5153 if (ComplainAboutFunc) 5154 Diag(Loc, diag::ext_gnu_ptr_func_arith) 5155 << ComplainAboutFunc->getType() 5156 << ComplainAboutFunc->getSourceRange(); 5157 5158 if (CompLHSTy) *CompLHSTy = lex->getType(); 5159 return Context.getPointerDiffType(); 5160 } 5161 } 5162 5163 return InvalidOperands(Loc, lex, rex); 5164} 5165 5166// C99 6.5.7 5167QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc, 5168 bool isCompAssign) { 5169 // C99 6.5.7p2: Each of the operands shall have integer type. 5170 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType()) 5171 return InvalidOperands(Loc, lex, rex); 5172 5173 // Vector shifts promote their scalar inputs to vector type. 5174 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 5175 return CheckVectorOperands(Loc, lex, rex); 5176 5177 // Shifts don't perform usual arithmetic conversions, they just do integer 5178 // promotions on each operand. C99 6.5.7p3 5179 QualType LHSTy = Context.isPromotableBitField(lex); 5180 if (LHSTy.isNull()) { 5181 LHSTy = lex->getType(); 5182 if (LHSTy->isPromotableIntegerType()) 5183 LHSTy = Context.getPromotedIntegerType(LHSTy); 5184 } 5185 if (!isCompAssign) 5186 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast); 5187 5188 UsualUnaryConversions(rex); 5189 5190 // Sanity-check shift operands 5191 llvm::APSInt Right; 5192 // Check right/shifter operand 5193 if (!rex->isValueDependent() && 5194 rex->isIntegerConstantExpr(Right, Context)) { 5195 if (Right.isNegative()) 5196 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange(); 5197 else { 5198 llvm::APInt LeftBits(Right.getBitWidth(), 5199 Context.getTypeSize(lex->getType())); 5200 if (Right.uge(LeftBits)) 5201 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange(); 5202 } 5203 } 5204 5205 // "The type of the result is that of the promoted left operand." 5206 return LHSTy; 5207} 5208 5209// C99 6.5.8, C++ [expr.rel] 5210QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc, 5211 unsigned OpaqueOpc, bool isRelational) { 5212 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc; 5213 5214 // Handle vector comparisons separately. 5215 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 5216 return CheckVectorCompareOperands(lex, rex, Loc, isRelational); 5217 5218 CheckSignCompare(lex, rex, Loc, diag::warn_mixed_sign_comparison, 5219 (Opc == BinaryOperator::EQ || Opc == BinaryOperator::NE)); 5220 5221 // C99 6.5.8p3 / C99 6.5.9p4 5222 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 5223 UsualArithmeticConversions(lex, rex); 5224 else { 5225 UsualUnaryConversions(lex); 5226 UsualUnaryConversions(rex); 5227 } 5228 QualType lType = lex->getType(); 5229 QualType rType = rex->getType(); 5230 5231 if (!lType->isFloatingType() 5232 && !(lType->isBlockPointerType() && isRelational)) { 5233 // For non-floating point types, check for self-comparisons of the form 5234 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 5235 // often indicate logic errors in the program. 5236 // NOTE: Don't warn about comparisons of enum constants. These can arise 5237 // from macro expansions, and are usually quite deliberate. 5238 Expr *LHSStripped = lex->IgnoreParens(); 5239 Expr *RHSStripped = rex->IgnoreParens(); 5240 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) 5241 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) 5242 if (DRL->getDecl() == DRR->getDecl() && 5243 !isa<EnumConstantDecl>(DRL->getDecl())) 5244 DiagRuntimeBehavior(Loc, PDiag(diag::warn_selfcomparison)); 5245 5246 if (isa<CastExpr>(LHSStripped)) 5247 LHSStripped = LHSStripped->IgnoreParenCasts(); 5248 if (isa<CastExpr>(RHSStripped)) 5249 RHSStripped = RHSStripped->IgnoreParenCasts(); 5250 5251 // Warn about comparisons against a string constant (unless the other 5252 // operand is null), the user probably wants strcmp. 5253 Expr *literalString = 0; 5254 Expr *literalStringStripped = 0; 5255 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 5256 !RHSStripped->isNullPointerConstant(Context, 5257 Expr::NPC_ValueDependentIsNull)) { 5258 literalString = lex; 5259 literalStringStripped = LHSStripped; 5260 } else if ((isa<StringLiteral>(RHSStripped) || 5261 isa<ObjCEncodeExpr>(RHSStripped)) && 5262 !LHSStripped->isNullPointerConstant(Context, 5263 Expr::NPC_ValueDependentIsNull)) { 5264 literalString = rex; 5265 literalStringStripped = RHSStripped; 5266 } 5267 5268 if (literalString) { 5269 std::string resultComparison; 5270 switch (Opc) { 5271 case BinaryOperator::LT: resultComparison = ") < 0"; break; 5272 case BinaryOperator::GT: resultComparison = ") > 0"; break; 5273 case BinaryOperator::LE: resultComparison = ") <= 0"; break; 5274 case BinaryOperator::GE: resultComparison = ") >= 0"; break; 5275 case BinaryOperator::EQ: resultComparison = ") == 0"; break; 5276 case BinaryOperator::NE: resultComparison = ") != 0"; break; 5277 default: assert(false && "Invalid comparison operator"); 5278 } 5279 5280 DiagRuntimeBehavior(Loc, 5281 PDiag(diag::warn_stringcompare) 5282 << isa<ObjCEncodeExpr>(literalStringStripped) 5283 << literalString->getSourceRange() 5284 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ") 5285 << CodeModificationHint::CreateInsertion(lex->getLocStart(), 5286 "strcmp(") 5287 << CodeModificationHint::CreateInsertion( 5288 PP.getLocForEndOfToken(rex->getLocEnd()), 5289 resultComparison)); 5290 } 5291 } 5292 5293 // The result of comparisons is 'bool' in C++, 'int' in C. 5294 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy; 5295 5296 if (isRelational) { 5297 if (lType->isRealType() && rType->isRealType()) 5298 return ResultTy; 5299 } else { 5300 // Check for comparisons of floating point operands using != and ==. 5301 if (lType->isFloatingType() && rType->isFloatingType()) 5302 CheckFloatComparison(Loc,lex,rex); 5303 5304 if (lType->isArithmeticType() && rType->isArithmeticType()) 5305 return ResultTy; 5306 } 5307 5308 bool LHSIsNull = lex->isNullPointerConstant(Context, 5309 Expr::NPC_ValueDependentIsNull); 5310 bool RHSIsNull = rex->isNullPointerConstant(Context, 5311 Expr::NPC_ValueDependentIsNull); 5312 5313 // All of the following pointer related warnings are GCC extensions, except 5314 // when handling null pointer constants. One day, we can consider making them 5315 // errors (when -pedantic-errors is enabled). 5316 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2 5317 QualType LCanPointeeTy = 5318 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType()); 5319 QualType RCanPointeeTy = 5320 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType()); 5321 5322 if (getLangOptions().CPlusPlus) { 5323 if (LCanPointeeTy == RCanPointeeTy) 5324 return ResultTy; 5325 if (!isRelational && 5326 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 5327 // Valid unless comparison between non-null pointer and function pointer 5328 // This is a gcc extension compatibility comparison. 5329 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 5330 && !LHSIsNull && !RHSIsNull) { 5331 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void) 5332 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 5333 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast); 5334 return ResultTy; 5335 } 5336 } 5337 // C++ [expr.rel]p2: 5338 // [...] Pointer conversions (4.10) and qualification 5339 // conversions (4.4) are performed on pointer operands (or on 5340 // a pointer operand and a null pointer constant) to bring 5341 // them to their composite pointer type. [...] 5342 // 5343 // C++ [expr.eq]p1 uses the same notion for (in)equality 5344 // comparisons of pointers. 5345 QualType T = FindCompositePointerType(lex, rex); 5346 if (T.isNull()) { 5347 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers) 5348 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 5349 return QualType(); 5350 } 5351 5352 ImpCastExprToType(lex, T, CastExpr::CK_BitCast); 5353 ImpCastExprToType(rex, T, CastExpr::CK_BitCast); 5354 return ResultTy; 5355 } 5356 // C99 6.5.9p2 and C99 6.5.8p2 5357 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 5358 RCanPointeeTy.getUnqualifiedType())) { 5359 // Valid unless a relational comparison of function pointers 5360 if (isRelational && LCanPointeeTy->isFunctionType()) { 5361 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 5362 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 5363 } 5364 } else if (!isRelational && 5365 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 5366 // Valid unless comparison between non-null pointer and function pointer 5367 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 5368 && !LHSIsNull && !RHSIsNull) { 5369 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void) 5370 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 5371 } 5372 } else { 5373 // Invalid 5374 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers) 5375 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 5376 } 5377 if (LCanPointeeTy != RCanPointeeTy) 5378 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast); 5379 return ResultTy; 5380 } 5381 5382 if (getLangOptions().CPlusPlus) { 5383 // Comparison of pointers with null pointer constants and equality 5384 // comparisons of member pointers to null pointer constants. 5385 if (RHSIsNull && 5386 (lType->isPointerType() || 5387 (!isRelational && lType->isMemberPointerType()))) { 5388 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer); 5389 return ResultTy; 5390 } 5391 if (LHSIsNull && 5392 (rType->isPointerType() || 5393 (!isRelational && rType->isMemberPointerType()))) { 5394 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer); 5395 return ResultTy; 5396 } 5397 5398 // Comparison of member pointers. 5399 if (!isRelational && 5400 lType->isMemberPointerType() && rType->isMemberPointerType()) { 5401 // C++ [expr.eq]p2: 5402 // In addition, pointers to members can be compared, or a pointer to 5403 // member and a null pointer constant. Pointer to member conversions 5404 // (4.11) and qualification conversions (4.4) are performed to bring 5405 // them to a common type. If one operand is a null pointer constant, 5406 // the common type is the type of the other operand. Otherwise, the 5407 // common type is a pointer to member type similar (4.4) to the type 5408 // of one of the operands, with a cv-qualification signature (4.4) 5409 // that is the union of the cv-qualification signatures of the operand 5410 // types. 5411 QualType T = FindCompositePointerType(lex, rex); 5412 if (T.isNull()) { 5413 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers) 5414 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 5415 return QualType(); 5416 } 5417 5418 ImpCastExprToType(lex, T, CastExpr::CK_BitCast); 5419 ImpCastExprToType(rex, T, CastExpr::CK_BitCast); 5420 return ResultTy; 5421 } 5422 5423 // Comparison of nullptr_t with itself. 5424 if (lType->isNullPtrType() && rType->isNullPtrType()) 5425 return ResultTy; 5426 } 5427 5428 // Handle block pointer types. 5429 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) { 5430 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType(); 5431 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType(); 5432 5433 if (!LHSIsNull && !RHSIsNull && 5434 !Context.typesAreCompatible(lpointee, rpointee)) { 5435 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 5436 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 5437 } 5438 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast); 5439 return ResultTy; 5440 } 5441 // Allow block pointers to be compared with null pointer constants. 5442 if (!isRelational 5443 && ((lType->isBlockPointerType() && rType->isPointerType()) 5444 || (lType->isPointerType() && rType->isBlockPointerType()))) { 5445 if (!LHSIsNull && !RHSIsNull) { 5446 if (!((rType->isPointerType() && rType->getAs<PointerType>() 5447 ->getPointeeType()->isVoidType()) 5448 || (lType->isPointerType() && lType->getAs<PointerType>() 5449 ->getPointeeType()->isVoidType()))) 5450 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 5451 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 5452 } 5453 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast); 5454 return ResultTy; 5455 } 5456 5457 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) { 5458 if (lType->isPointerType() || rType->isPointerType()) { 5459 const PointerType *LPT = lType->getAs<PointerType>(); 5460 const PointerType *RPT = rType->getAs<PointerType>(); 5461 bool LPtrToVoid = LPT ? 5462 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false; 5463 bool RPtrToVoid = RPT ? 5464 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false; 5465 5466 if (!LPtrToVoid && !RPtrToVoid && 5467 !Context.typesAreCompatible(lType, rType)) { 5468 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers) 5469 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 5470 } 5471 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast); 5472 return ResultTy; 5473 } 5474 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) { 5475 if (!Context.areComparableObjCPointerTypes(lType, rType)) 5476 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers) 5477 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 5478 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast); 5479 return ResultTy; 5480 } 5481 } 5482 if (lType->isAnyPointerType() && rType->isIntegerType()) { 5483 unsigned DiagID = 0; 5484 if (RHSIsNull) { 5485 if (isRelational) 5486 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 5487 } else if (isRelational) 5488 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 5489 else 5490 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 5491 5492 if (DiagID) { 5493 Diag(Loc, DiagID) 5494 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 5495 } 5496 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer); 5497 return ResultTy; 5498 } 5499 if (lType->isIntegerType() && rType->isAnyPointerType()) { 5500 unsigned DiagID = 0; 5501 if (LHSIsNull) { 5502 if (isRelational) 5503 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 5504 } else if (isRelational) 5505 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 5506 else 5507 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 5508 5509 if (DiagID) { 5510 Diag(Loc, DiagID) 5511 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 5512 } 5513 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer); 5514 return ResultTy; 5515 } 5516 // Handle block pointers. 5517 if (!isRelational && RHSIsNull 5518 && lType->isBlockPointerType() && rType->isIntegerType()) { 5519 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer); 5520 return ResultTy; 5521 } 5522 if (!isRelational && LHSIsNull 5523 && lType->isIntegerType() && rType->isBlockPointerType()) { 5524 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer); 5525 return ResultTy; 5526 } 5527 return InvalidOperands(Loc, lex, rex); 5528} 5529 5530/// CheckVectorCompareOperands - vector comparisons are a clang extension that 5531/// operates on extended vector types. Instead of producing an IntTy result, 5532/// like a scalar comparison, a vector comparison produces a vector of integer 5533/// types. 5534QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex, 5535 SourceLocation Loc, 5536 bool isRelational) { 5537 // Check to make sure we're operating on vectors of the same type and width, 5538 // Allowing one side to be a scalar of element type. 5539 QualType vType = CheckVectorOperands(Loc, lex, rex); 5540 if (vType.isNull()) 5541 return vType; 5542 5543 QualType lType = lex->getType(); 5544 QualType rType = rex->getType(); 5545 5546 // For non-floating point types, check for self-comparisons of the form 5547 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 5548 // often indicate logic errors in the program. 5549 if (!lType->isFloatingType()) { 5550 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens())) 5551 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens())) 5552 if (DRL->getDecl() == DRR->getDecl()) 5553 DiagRuntimeBehavior(Loc, PDiag(diag::warn_selfcomparison)); 5554 } 5555 5556 // Check for comparisons of floating point operands using != and ==. 5557 if (!isRelational && lType->isFloatingType()) { 5558 assert (rType->isFloatingType()); 5559 CheckFloatComparison(Loc,lex,rex); 5560 } 5561 5562 // Return the type for the comparison, which is the same as vector type for 5563 // integer vectors, or an integer type of identical size and number of 5564 // elements for floating point vectors. 5565 if (lType->isIntegerType()) 5566 return lType; 5567 5568 const VectorType *VTy = lType->getAs<VectorType>(); 5569 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 5570 if (TypeSize == Context.getTypeSize(Context.IntTy)) 5571 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 5572 if (TypeSize == Context.getTypeSize(Context.LongTy)) 5573 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 5574 5575 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 5576 "Unhandled vector element size in vector compare"); 5577 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 5578} 5579 5580inline QualType Sema::CheckBitwiseOperands( 5581 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) { 5582 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 5583 return CheckVectorOperands(Loc, lex, rex); 5584 5585 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 5586 5587 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType()) 5588 return compType; 5589 return InvalidOperands(Loc, lex, rex); 5590} 5591 5592inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 5593 Expr *&lex, Expr *&rex, SourceLocation Loc) { 5594 if (!Context.getLangOptions().CPlusPlus) { 5595 UsualUnaryConversions(lex); 5596 UsualUnaryConversions(rex); 5597 5598 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType()) 5599 return InvalidOperands(Loc, lex, rex); 5600 5601 return Context.IntTy; 5602 } 5603 5604 // C++ [expr.log.and]p1 5605 // C++ [expr.log.or]p1 5606 // The operands are both implicitly converted to type bool (clause 4). 5607 StandardConversionSequence LHS; 5608 if (!IsStandardConversion(lex, Context.BoolTy, 5609 /*InOverloadResolution=*/false, LHS)) 5610 return InvalidOperands(Loc, lex, rex); 5611 5612 if (PerformImplicitConversion(lex, Context.BoolTy, LHS, 5613 AA_Passing, /*IgnoreBaseAccess=*/false)) 5614 return InvalidOperands(Loc, lex, rex); 5615 5616 StandardConversionSequence RHS; 5617 if (!IsStandardConversion(rex, Context.BoolTy, 5618 /*InOverloadResolution=*/false, RHS)) 5619 return InvalidOperands(Loc, lex, rex); 5620 5621 if (PerformImplicitConversion(rex, Context.BoolTy, RHS, 5622 AA_Passing, /*IgnoreBaseAccess=*/false)) 5623 return InvalidOperands(Loc, lex, rex); 5624 5625 // C++ [expr.log.and]p2 5626 // C++ [expr.log.or]p2 5627 // The result is a bool. 5628 return Context.BoolTy; 5629} 5630 5631/// IsReadonlyProperty - Verify that otherwise a valid l-value expression 5632/// is a read-only property; return true if so. A readonly property expression 5633/// depends on various declarations and thus must be treated specially. 5634/// 5635static bool IsReadonlyProperty(Expr *E, Sema &S) { 5636 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) { 5637 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E); 5638 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) { 5639 QualType BaseType = PropExpr->getBase()->getType(); 5640 if (const ObjCObjectPointerType *OPT = 5641 BaseType->getAsObjCInterfacePointerType()) 5642 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl()) 5643 if (S.isPropertyReadonly(PDecl, IFace)) 5644 return true; 5645 } 5646 } 5647 return false; 5648} 5649 5650/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 5651/// emit an error and return true. If so, return false. 5652static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 5653 SourceLocation OrigLoc = Loc; 5654 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 5655 &Loc); 5656 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S)) 5657 IsLV = Expr::MLV_ReadonlyProperty; 5658 if (IsLV == Expr::MLV_Valid) 5659 return false; 5660 5661 unsigned Diag = 0; 5662 bool NeedType = false; 5663 switch (IsLV) { // C99 6.5.16p2 5664 default: assert(0 && "Unknown result from isModifiableLvalue!"); 5665 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break; 5666 case Expr::MLV_ArrayType: 5667 Diag = diag::err_typecheck_array_not_modifiable_lvalue; 5668 NeedType = true; 5669 break; 5670 case Expr::MLV_NotObjectType: 5671 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue; 5672 NeedType = true; 5673 break; 5674 case Expr::MLV_LValueCast: 5675 Diag = diag::err_typecheck_lvalue_casts_not_supported; 5676 break; 5677 case Expr::MLV_InvalidExpression: 5678 Diag = diag::err_typecheck_expression_not_modifiable_lvalue; 5679 break; 5680 case Expr::MLV_IncompleteType: 5681 case Expr::MLV_IncompleteVoidType: 5682 return S.RequireCompleteType(Loc, E->getType(), 5683 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue) 5684 << E->getSourceRange()); 5685 case Expr::MLV_DuplicateVectorComponents: 5686 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 5687 break; 5688 case Expr::MLV_NotBlockQualified: 5689 Diag = diag::err_block_decl_ref_not_modifiable_lvalue; 5690 break; 5691 case Expr::MLV_ReadonlyProperty: 5692 Diag = diag::error_readonly_property_assignment; 5693 break; 5694 case Expr::MLV_NoSetterProperty: 5695 Diag = diag::error_nosetter_property_assignment; 5696 break; 5697 case Expr::MLV_SubObjCPropertySetting: 5698 Diag = diag::error_no_subobject_property_setting; 5699 break; 5700 } 5701 5702 SourceRange Assign; 5703 if (Loc != OrigLoc) 5704 Assign = SourceRange(OrigLoc, OrigLoc); 5705 if (NeedType) 5706 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign; 5707 else 5708 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 5709 return true; 5710} 5711 5712 5713 5714// C99 6.5.16.1 5715QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS, 5716 SourceLocation Loc, 5717 QualType CompoundType) { 5718 // Verify that LHS is a modifiable lvalue, and emit error if not. 5719 if (CheckForModifiableLvalue(LHS, Loc, *this)) 5720 return QualType(); 5721 5722 QualType LHSType = LHS->getType(); 5723 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType; 5724 5725 AssignConvertType ConvTy; 5726 if (CompoundType.isNull()) { 5727 // Simple assignment "x = y". 5728 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS); 5729 // Special case of NSObject attributes on c-style pointer types. 5730 if (ConvTy == IncompatiblePointer && 5731 ((Context.isObjCNSObjectType(LHSType) && 5732 RHSType->isObjCObjectPointerType()) || 5733 (Context.isObjCNSObjectType(RHSType) && 5734 LHSType->isObjCObjectPointerType()))) 5735 ConvTy = Compatible; 5736 5737 // If the RHS is a unary plus or minus, check to see if they = and + are 5738 // right next to each other. If so, the user may have typo'd "x =+ 4" 5739 // instead of "x += 4". 5740 Expr *RHSCheck = RHS; 5741 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 5742 RHSCheck = ICE->getSubExpr(); 5743 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 5744 if ((UO->getOpcode() == UnaryOperator::Plus || 5745 UO->getOpcode() == UnaryOperator::Minus) && 5746 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 5747 // Only if the two operators are exactly adjacent. 5748 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() && 5749 // And there is a space or other character before the subexpr of the 5750 // unary +/-. We don't want to warn on "x=-1". 5751 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 5752 UO->getSubExpr()->getLocStart().isFileID()) { 5753 Diag(Loc, diag::warn_not_compound_assign) 5754 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-") 5755 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 5756 } 5757 } 5758 } else { 5759 // Compound assignment "x += y" 5760 ConvTy = CheckAssignmentConstraints(LHSType, RHSType); 5761 } 5762 5763 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 5764 RHS, AA_Assigning)) 5765 return QualType(); 5766 5767 // C99 6.5.16p3: The type of an assignment expression is the type of the 5768 // left operand unless the left operand has qualified type, in which case 5769 // it is the unqualified version of the type of the left operand. 5770 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 5771 // is converted to the type of the assignment expression (above). 5772 // C++ 5.17p1: the type of the assignment expression is that of its left 5773 // operand. 5774 return LHSType.getUnqualifiedType(); 5775} 5776 5777// C99 6.5.17 5778QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) { 5779 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions. 5780 DefaultFunctionArrayConversion(RHS); 5781 5782 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be 5783 // incomplete in C++). 5784 5785 return RHS->getType(); 5786} 5787 5788/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 5789/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 5790QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc, 5791 bool isInc) { 5792 if (Op->isTypeDependent()) 5793 return Context.DependentTy; 5794 5795 QualType ResType = Op->getType(); 5796 assert(!ResType.isNull() && "no type for increment/decrement expression"); 5797 5798 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) { 5799 // Decrement of bool is not allowed. 5800 if (!isInc) { 5801 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 5802 return QualType(); 5803 } 5804 // Increment of bool sets it to true, but is deprecated. 5805 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); 5806 } else if (ResType->isRealType()) { 5807 // OK! 5808 } else if (ResType->isAnyPointerType()) { 5809 QualType PointeeTy = ResType->getPointeeType(); 5810 5811 // C99 6.5.2.4p2, 6.5.6p2 5812 if (PointeeTy->isVoidType()) { 5813 if (getLangOptions().CPlusPlus) { 5814 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type) 5815 << Op->getSourceRange(); 5816 return QualType(); 5817 } 5818 5819 // Pointer to void is a GNU extension in C. 5820 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange(); 5821 } else if (PointeeTy->isFunctionType()) { 5822 if (getLangOptions().CPlusPlus) { 5823 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type) 5824 << Op->getType() << Op->getSourceRange(); 5825 return QualType(); 5826 } 5827 5828 Diag(OpLoc, diag::ext_gnu_ptr_func_arith) 5829 << ResType << Op->getSourceRange(); 5830 } else if (RequireCompleteType(OpLoc, PointeeTy, 5831 PDiag(diag::err_typecheck_arithmetic_incomplete_type) 5832 << Op->getSourceRange() 5833 << ResType)) 5834 return QualType(); 5835 // Diagnose bad cases where we step over interface counts. 5836 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) { 5837 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface) 5838 << PointeeTy << Op->getSourceRange(); 5839 return QualType(); 5840 } 5841 } else if (ResType->isAnyComplexType()) { 5842 // C99 does not support ++/-- on complex types, we allow as an extension. 5843 Diag(OpLoc, diag::ext_integer_increment_complex) 5844 << ResType << Op->getSourceRange(); 5845 } else { 5846 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 5847 << ResType << int(isInc) << Op->getSourceRange(); 5848 return QualType(); 5849 } 5850 // At this point, we know we have a real, complex or pointer type. 5851 // Now make sure the operand is a modifiable lvalue. 5852 if (CheckForModifiableLvalue(Op, OpLoc, *this)) 5853 return QualType(); 5854 return ResType; 5855} 5856 5857/// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 5858/// This routine allows us to typecheck complex/recursive expressions 5859/// where the declaration is needed for type checking. We only need to 5860/// handle cases when the expression references a function designator 5861/// or is an lvalue. Here are some examples: 5862/// - &(x) => x 5863/// - &*****f => f for f a function designator. 5864/// - &s.xx => s 5865/// - &s.zz[1].yy -> s, if zz is an array 5866/// - *(x + 1) -> x, if x is an array 5867/// - &"123"[2] -> 0 5868/// - & __real__ x -> x 5869static NamedDecl *getPrimaryDecl(Expr *E) { 5870 switch (E->getStmtClass()) { 5871 case Stmt::DeclRefExprClass: 5872 return cast<DeclRefExpr>(E)->getDecl(); 5873 case Stmt::MemberExprClass: 5874 // If this is an arrow operator, the address is an offset from 5875 // the base's value, so the object the base refers to is 5876 // irrelevant. 5877 if (cast<MemberExpr>(E)->isArrow()) 5878 return 0; 5879 // Otherwise, the expression refers to a part of the base 5880 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 5881 case Stmt::ArraySubscriptExprClass: { 5882 // FIXME: This code shouldn't be necessary! We should catch the implicit 5883 // promotion of register arrays earlier. 5884 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 5885 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 5886 if (ICE->getSubExpr()->getType()->isArrayType()) 5887 return getPrimaryDecl(ICE->getSubExpr()); 5888 } 5889 return 0; 5890 } 5891 case Stmt::UnaryOperatorClass: { 5892 UnaryOperator *UO = cast<UnaryOperator>(E); 5893 5894 switch(UO->getOpcode()) { 5895 case UnaryOperator::Real: 5896 case UnaryOperator::Imag: 5897 case UnaryOperator::Extension: 5898 return getPrimaryDecl(UO->getSubExpr()); 5899 default: 5900 return 0; 5901 } 5902 } 5903 case Stmt::ParenExprClass: 5904 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 5905 case Stmt::ImplicitCastExprClass: 5906 // If the result of an implicit cast is an l-value, we care about 5907 // the sub-expression; otherwise, the result here doesn't matter. 5908 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 5909 default: 5910 return 0; 5911 } 5912} 5913 5914/// CheckAddressOfOperand - The operand of & must be either a function 5915/// designator or an lvalue designating an object. If it is an lvalue, the 5916/// object cannot be declared with storage class register or be a bit field. 5917/// Note: The usual conversions are *not* applied to the operand of the & 5918/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 5919/// In C++, the operand might be an overloaded function name, in which case 5920/// we allow the '&' but retain the overloaded-function type. 5921QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) { 5922 // Make sure to ignore parentheses in subsequent checks 5923 op = op->IgnoreParens(); 5924 5925 if (op->isTypeDependent()) 5926 return Context.DependentTy; 5927 5928 if (getLangOptions().C99) { 5929 // Implement C99-only parts of addressof rules. 5930 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 5931 if (uOp->getOpcode() == UnaryOperator::Deref) 5932 // Per C99 6.5.3.2, the address of a deref always returns a valid result 5933 // (assuming the deref expression is valid). 5934 return uOp->getSubExpr()->getType(); 5935 } 5936 // Technically, there should be a check for array subscript 5937 // expressions here, but the result of one is always an lvalue anyway. 5938 } 5939 NamedDecl *dcl = getPrimaryDecl(op); 5940 Expr::isLvalueResult lval = op->isLvalue(Context); 5941 5942 MemberExpr *ME = dyn_cast<MemberExpr>(op); 5943 if (lval == Expr::LV_MemberFunction && ME && 5944 isa<CXXMethodDecl>(ME->getMemberDecl())) { 5945 ValueDecl *dcl = cast<MemberExpr>(op)->getMemberDecl(); 5946 // &f where f is a member of the current object, or &o.f, or &p->f 5947 // All these are not allowed, and we need to catch them before the dcl 5948 // branch of the if, below. 5949 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 5950 << dcl; 5951 // FIXME: Improve this diagnostic and provide a fixit. 5952 5953 // Now recover by acting as if the function had been accessed qualified. 5954 return Context.getMemberPointerType(op->getType(), 5955 Context.getTypeDeclType(cast<RecordDecl>(dcl->getDeclContext())) 5956 .getTypePtr()); 5957 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 5958 // C99 6.5.3.2p1 5959 // The operand must be either an l-value or a function designator 5960 if (!op->getType()->isFunctionType()) { 5961 // FIXME: emit more specific diag... 5962 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 5963 << op->getSourceRange(); 5964 return QualType(); 5965 } 5966 } else if (op->getBitField()) { // C99 6.5.3.2p1 5967 // The operand cannot be a bit-field 5968 Diag(OpLoc, diag::err_typecheck_address_of) 5969 << "bit-field" << op->getSourceRange(); 5970 return QualType(); 5971 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) && 5972 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){ 5973 // The operand cannot be an element of a vector 5974 Diag(OpLoc, diag::err_typecheck_address_of) 5975 << "vector element" << op->getSourceRange(); 5976 return QualType(); 5977 } else if (isa<ObjCPropertyRefExpr>(op)) { 5978 // cannot take address of a property expression. 5979 Diag(OpLoc, diag::err_typecheck_address_of) 5980 << "property expression" << op->getSourceRange(); 5981 return QualType(); 5982 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) { 5983 // FIXME: Can LHS ever be null here? 5984 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull()) 5985 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc); 5986 } else if (isa<UnresolvedLookupExpr>(op)) { 5987 return Context.OverloadTy; 5988 } else if (dcl) { // C99 6.5.3.2p1 5989 // We have an lvalue with a decl. Make sure the decl is not declared 5990 // with the register storage-class specifier. 5991 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 5992 if (vd->getStorageClass() == VarDecl::Register) { 5993 Diag(OpLoc, diag::err_typecheck_address_of) 5994 << "register variable" << op->getSourceRange(); 5995 return QualType(); 5996 } 5997 } else if (isa<FunctionTemplateDecl>(dcl)) { 5998 return Context.OverloadTy; 5999 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) { 6000 // Okay: we can take the address of a field. 6001 // Could be a pointer to member, though, if there is an explicit 6002 // scope qualifier for the class. 6003 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 6004 DeclContext *Ctx = dcl->getDeclContext(); 6005 if (Ctx && Ctx->isRecord()) { 6006 if (FD->getType()->isReferenceType()) { 6007 Diag(OpLoc, 6008 diag::err_cannot_form_pointer_to_member_of_reference_type) 6009 << FD->getDeclName() << FD->getType(); 6010 return QualType(); 6011 } 6012 6013 return Context.getMemberPointerType(op->getType(), 6014 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 6015 } 6016 } 6017 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) { 6018 // Okay: we can take the address of a function. 6019 // As above. 6020 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() && 6021 MD->isInstance()) 6022 return Context.getMemberPointerType(op->getType(), 6023 Context.getTypeDeclType(MD->getParent()).getTypePtr()); 6024 } else if (!isa<FunctionDecl>(dcl)) 6025 assert(0 && "Unknown/unexpected decl type"); 6026 } 6027 6028 if (lval == Expr::LV_IncompleteVoidType) { 6029 // Taking the address of a void variable is technically illegal, but we 6030 // allow it in cases which are otherwise valid. 6031 // Example: "extern void x; void* y = &x;". 6032 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 6033 } 6034 6035 // If the operand has type "type", the result has type "pointer to type". 6036 return Context.getPointerType(op->getType()); 6037} 6038 6039QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) { 6040 if (Op->isTypeDependent()) 6041 return Context.DependentTy; 6042 6043 UsualUnaryConversions(Op); 6044 QualType Ty = Op->getType(); 6045 6046 // Note that per both C89 and C99, this is always legal, even if ptype is an 6047 // incomplete type or void. It would be possible to warn about dereferencing 6048 // a void pointer, but it's completely well-defined, and such a warning is 6049 // unlikely to catch any mistakes. 6050 if (const PointerType *PT = Ty->getAs<PointerType>()) 6051 return PT->getPointeeType(); 6052 6053 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>()) 6054 return OPT->getPointeeType(); 6055 6056 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 6057 << Ty << Op->getSourceRange(); 6058 return QualType(); 6059} 6060 6061static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode( 6062 tok::TokenKind Kind) { 6063 BinaryOperator::Opcode Opc; 6064 switch (Kind) { 6065 default: assert(0 && "Unknown binop!"); 6066 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break; 6067 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break; 6068 case tok::star: Opc = BinaryOperator::Mul; break; 6069 case tok::slash: Opc = BinaryOperator::Div; break; 6070 case tok::percent: Opc = BinaryOperator::Rem; break; 6071 case tok::plus: Opc = BinaryOperator::Add; break; 6072 case tok::minus: Opc = BinaryOperator::Sub; break; 6073 case tok::lessless: Opc = BinaryOperator::Shl; break; 6074 case tok::greatergreater: Opc = BinaryOperator::Shr; break; 6075 case tok::lessequal: Opc = BinaryOperator::LE; break; 6076 case tok::less: Opc = BinaryOperator::LT; break; 6077 case tok::greaterequal: Opc = BinaryOperator::GE; break; 6078 case tok::greater: Opc = BinaryOperator::GT; break; 6079 case tok::exclaimequal: Opc = BinaryOperator::NE; break; 6080 case tok::equalequal: Opc = BinaryOperator::EQ; break; 6081 case tok::amp: Opc = BinaryOperator::And; break; 6082 case tok::caret: Opc = BinaryOperator::Xor; break; 6083 case tok::pipe: Opc = BinaryOperator::Or; break; 6084 case tok::ampamp: Opc = BinaryOperator::LAnd; break; 6085 case tok::pipepipe: Opc = BinaryOperator::LOr; break; 6086 case tok::equal: Opc = BinaryOperator::Assign; break; 6087 case tok::starequal: Opc = BinaryOperator::MulAssign; break; 6088 case tok::slashequal: Opc = BinaryOperator::DivAssign; break; 6089 case tok::percentequal: Opc = BinaryOperator::RemAssign; break; 6090 case tok::plusequal: Opc = BinaryOperator::AddAssign; break; 6091 case tok::minusequal: Opc = BinaryOperator::SubAssign; break; 6092 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break; 6093 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break; 6094 case tok::ampequal: Opc = BinaryOperator::AndAssign; break; 6095 case tok::caretequal: Opc = BinaryOperator::XorAssign; break; 6096 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break; 6097 case tok::comma: Opc = BinaryOperator::Comma; break; 6098 } 6099 return Opc; 6100} 6101 6102static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode( 6103 tok::TokenKind Kind) { 6104 UnaryOperator::Opcode Opc; 6105 switch (Kind) { 6106 default: assert(0 && "Unknown unary op!"); 6107 case tok::plusplus: Opc = UnaryOperator::PreInc; break; 6108 case tok::minusminus: Opc = UnaryOperator::PreDec; break; 6109 case tok::amp: Opc = UnaryOperator::AddrOf; break; 6110 case tok::star: Opc = UnaryOperator::Deref; break; 6111 case tok::plus: Opc = UnaryOperator::Plus; break; 6112 case tok::minus: Opc = UnaryOperator::Minus; break; 6113 case tok::tilde: Opc = UnaryOperator::Not; break; 6114 case tok::exclaim: Opc = UnaryOperator::LNot; break; 6115 case tok::kw___real: Opc = UnaryOperator::Real; break; 6116 case tok::kw___imag: Opc = UnaryOperator::Imag; break; 6117 case tok::kw___extension__: Opc = UnaryOperator::Extension; break; 6118 } 6119 return Opc; 6120} 6121 6122/// CreateBuiltinBinOp - Creates a new built-in binary operation with 6123/// operator @p Opc at location @c TokLoc. This routine only supports 6124/// built-in operations; ActOnBinOp handles overloaded operators. 6125Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 6126 unsigned Op, 6127 Expr *lhs, Expr *rhs) { 6128 QualType ResultTy; // Result type of the binary operator. 6129 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op; 6130 // The following two variables are used for compound assignment operators 6131 QualType CompLHSTy; // Type of LHS after promotions for computation 6132 QualType CompResultTy; // Type of computation result 6133 6134 switch (Opc) { 6135 case BinaryOperator::Assign: 6136 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType()); 6137 break; 6138 case BinaryOperator::PtrMemD: 6139 case BinaryOperator::PtrMemI: 6140 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc, 6141 Opc == BinaryOperator::PtrMemI); 6142 break; 6143 case BinaryOperator::Mul: 6144 case BinaryOperator::Div: 6145 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false, 6146 Opc == BinaryOperator::Div); 6147 break; 6148 case BinaryOperator::Rem: 6149 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc); 6150 break; 6151 case BinaryOperator::Add: 6152 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc); 6153 break; 6154 case BinaryOperator::Sub: 6155 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc); 6156 break; 6157 case BinaryOperator::Shl: 6158 case BinaryOperator::Shr: 6159 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc); 6160 break; 6161 case BinaryOperator::LE: 6162 case BinaryOperator::LT: 6163 case BinaryOperator::GE: 6164 case BinaryOperator::GT: 6165 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true); 6166 break; 6167 case BinaryOperator::EQ: 6168 case BinaryOperator::NE: 6169 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false); 6170 break; 6171 case BinaryOperator::And: 6172 case BinaryOperator::Xor: 6173 case BinaryOperator::Or: 6174 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc); 6175 break; 6176 case BinaryOperator::LAnd: 6177 case BinaryOperator::LOr: 6178 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc); 6179 break; 6180 case BinaryOperator::MulAssign: 6181 case BinaryOperator::DivAssign: 6182 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true, 6183 Opc == BinaryOperator::DivAssign); 6184 CompLHSTy = CompResultTy; 6185 if (!CompResultTy.isNull()) 6186 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 6187 break; 6188 case BinaryOperator::RemAssign: 6189 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true); 6190 CompLHSTy = CompResultTy; 6191 if (!CompResultTy.isNull()) 6192 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 6193 break; 6194 case BinaryOperator::AddAssign: 6195 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy); 6196 if (!CompResultTy.isNull()) 6197 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 6198 break; 6199 case BinaryOperator::SubAssign: 6200 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy); 6201 if (!CompResultTy.isNull()) 6202 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 6203 break; 6204 case BinaryOperator::ShlAssign: 6205 case BinaryOperator::ShrAssign: 6206 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true); 6207 CompLHSTy = CompResultTy; 6208 if (!CompResultTy.isNull()) 6209 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 6210 break; 6211 case BinaryOperator::AndAssign: 6212 case BinaryOperator::XorAssign: 6213 case BinaryOperator::OrAssign: 6214 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true); 6215 CompLHSTy = CompResultTy; 6216 if (!CompResultTy.isNull()) 6217 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 6218 break; 6219 case BinaryOperator::Comma: 6220 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc); 6221 break; 6222 } 6223 if (ResultTy.isNull()) 6224 return ExprError(); 6225 if (CompResultTy.isNull()) 6226 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc)); 6227 else 6228 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy, 6229 CompLHSTy, CompResultTy, 6230 OpLoc)); 6231} 6232 6233/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps 6234/// ParenRange in parentheses. 6235static void SuggestParentheses(Sema &Self, SourceLocation Loc, 6236 const PartialDiagnostic &PD, 6237 SourceRange ParenRange, 6238 const PartialDiagnostic &SecondPD = PartialDiagnostic(0), 6239 SourceRange SecondParenRange = SourceRange()) { 6240 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd()); 6241 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) { 6242 // We can't display the parentheses, so just dig the 6243 // warning/error and return. 6244 Self.Diag(Loc, PD); 6245 return; 6246 } 6247 6248 Self.Diag(Loc, PD) 6249 << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(") 6250 << CodeModificationHint::CreateInsertion(EndLoc, ")"); 6251 6252 if (!SecondPD.getDiagID()) 6253 return; 6254 6255 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd()); 6256 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) { 6257 // We can't display the parentheses, so just dig the 6258 // warning/error and return. 6259 Self.Diag(Loc, SecondPD); 6260 return; 6261 } 6262 6263 Self.Diag(Loc, SecondPD) 6264 << CodeModificationHint::CreateInsertion(SecondParenRange.getBegin(), "(") 6265 << CodeModificationHint::CreateInsertion(EndLoc, ")"); 6266} 6267 6268/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 6269/// operators are mixed in a way that suggests that the programmer forgot that 6270/// comparison operators have higher precedence. The most typical example of 6271/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 6272static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc, 6273 SourceLocation OpLoc,Expr *lhs,Expr *rhs){ 6274 typedef BinaryOperator BinOp; 6275 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1), 6276 rhsopc = static_cast<BinOp::Opcode>(-1); 6277 if (BinOp *BO = dyn_cast<BinOp>(lhs)) 6278 lhsopc = BO->getOpcode(); 6279 if (BinOp *BO = dyn_cast<BinOp>(rhs)) 6280 rhsopc = BO->getOpcode(); 6281 6282 // Subs are not binary operators. 6283 if (lhsopc == -1 && rhsopc == -1) 6284 return; 6285 6286 // Bitwise operations are sometimes used as eager logical ops. 6287 // Don't diagnose this. 6288 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) && 6289 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc))) 6290 return; 6291 6292 if (BinOp::isComparisonOp(lhsopc)) 6293 SuggestParentheses(Self, OpLoc, 6294 PDiag(diag::warn_precedence_bitwise_rel) 6295 << SourceRange(lhs->getLocStart(), OpLoc) 6296 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc), 6297 lhs->getSourceRange(), 6298 PDiag(diag::note_precedence_bitwise_first) 6299 << BinOp::getOpcodeStr(Opc), 6300 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd())); 6301 else if (BinOp::isComparisonOp(rhsopc)) 6302 SuggestParentheses(Self, OpLoc, 6303 PDiag(diag::warn_precedence_bitwise_rel) 6304 << SourceRange(OpLoc, rhs->getLocEnd()) 6305 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc), 6306 rhs->getSourceRange(), 6307 PDiag(diag::note_precedence_bitwise_first) 6308 << BinOp::getOpcodeStr(Opc), 6309 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart())); 6310} 6311 6312/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 6313/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3". 6314/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does. 6315static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc, 6316 SourceLocation OpLoc, Expr *lhs, Expr *rhs){ 6317 if (BinaryOperator::isBitwiseOp(Opc)) 6318 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs); 6319} 6320 6321// Binary Operators. 'Tok' is the token for the operator. 6322Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 6323 tok::TokenKind Kind, 6324 ExprArg LHS, ExprArg RHS) { 6325 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind); 6326 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>(); 6327 6328 assert((lhs != 0) && "ActOnBinOp(): missing left expression"); 6329 assert((rhs != 0) && "ActOnBinOp(): missing right expression"); 6330 6331 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 6332 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs); 6333 6334 return BuildBinOp(S, TokLoc, Opc, lhs, rhs); 6335} 6336 6337Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 6338 BinaryOperator::Opcode Opc, 6339 Expr *lhs, Expr *rhs) { 6340 if (getLangOptions().CPlusPlus && 6341 (lhs->getType()->isOverloadableType() || 6342 rhs->getType()->isOverloadableType())) { 6343 // Find all of the overloaded operators visible from this 6344 // point. We perform both an operator-name lookup from the local 6345 // scope and an argument-dependent lookup based on the types of 6346 // the arguments. 6347 UnresolvedSet<16> Functions; 6348 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 6349 if (S && OverOp != OO_None) 6350 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(), 6351 Functions); 6352 6353 // Build the (potentially-overloaded, potentially-dependent) 6354 // binary operation. 6355 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs); 6356 } 6357 6358 // Build a built-in binary operation. 6359 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs); 6360} 6361 6362Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 6363 unsigned OpcIn, 6364 ExprArg InputArg) { 6365 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 6366 6367 // FIXME: Input is modified below, but InputArg is not updated appropriately. 6368 Expr *Input = (Expr *)InputArg.get(); 6369 QualType resultType; 6370 switch (Opc) { 6371 case UnaryOperator::OffsetOf: 6372 assert(false && "Invalid unary operator"); 6373 break; 6374 6375 case UnaryOperator::PreInc: 6376 case UnaryOperator::PreDec: 6377 case UnaryOperator::PostInc: 6378 case UnaryOperator::PostDec: 6379 resultType = CheckIncrementDecrementOperand(Input, OpLoc, 6380 Opc == UnaryOperator::PreInc || 6381 Opc == UnaryOperator::PostInc); 6382 break; 6383 case UnaryOperator::AddrOf: 6384 resultType = CheckAddressOfOperand(Input, OpLoc); 6385 break; 6386 case UnaryOperator::Deref: 6387 DefaultFunctionArrayConversion(Input); 6388 resultType = CheckIndirectionOperand(Input, OpLoc); 6389 break; 6390 case UnaryOperator::Plus: 6391 case UnaryOperator::Minus: 6392 UsualUnaryConversions(Input); 6393 resultType = Input->getType(); 6394 if (resultType->isDependentType()) 6395 break; 6396 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 6397 break; 6398 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7 6399 resultType->isEnumeralType()) 6400 break; 6401 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6 6402 Opc == UnaryOperator::Plus && 6403 resultType->isPointerType()) 6404 break; 6405 6406 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 6407 << resultType << Input->getSourceRange()); 6408 case UnaryOperator::Not: // bitwise complement 6409 UsualUnaryConversions(Input); 6410 resultType = Input->getType(); 6411 if (resultType->isDependentType()) 6412 break; 6413 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 6414 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 6415 // C99 does not support '~' for complex conjugation. 6416 Diag(OpLoc, diag::ext_integer_complement_complex) 6417 << resultType << Input->getSourceRange(); 6418 else if (!resultType->isIntegerType()) 6419 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 6420 << resultType << Input->getSourceRange()); 6421 break; 6422 case UnaryOperator::LNot: // logical negation 6423 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 6424 DefaultFunctionArrayConversion(Input); 6425 resultType = Input->getType(); 6426 if (resultType->isDependentType()) 6427 break; 6428 if (!resultType->isScalarType()) // C99 6.5.3.3p1 6429 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 6430 << resultType << Input->getSourceRange()); 6431 // LNot always has type int. C99 6.5.3.3p5. 6432 // In C++, it's bool. C++ 5.3.1p8 6433 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy; 6434 break; 6435 case UnaryOperator::Real: 6436 case UnaryOperator::Imag: 6437 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real); 6438 break; 6439 case UnaryOperator::Extension: 6440 resultType = Input->getType(); 6441 break; 6442 } 6443 if (resultType.isNull()) 6444 return ExprError(); 6445 6446 InputArg.release(); 6447 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc)); 6448} 6449 6450Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 6451 UnaryOperator::Opcode Opc, 6452 ExprArg input) { 6453 Expr *Input = (Expr*)input.get(); 6454 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() && 6455 Opc != UnaryOperator::Extension) { 6456 // Find all of the overloaded operators visible from this 6457 // point. We perform both an operator-name lookup from the local 6458 // scope and an argument-dependent lookup based on the types of 6459 // the arguments. 6460 UnresolvedSet<16> Functions; 6461 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 6462 if (S && OverOp != OO_None) 6463 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 6464 Functions); 6465 6466 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input)); 6467 } 6468 6469 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input)); 6470} 6471 6472// Unary Operators. 'Tok' is the token for the operator. 6473Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 6474 tok::TokenKind Op, ExprArg input) { 6475 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input)); 6476} 6477 6478/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 6479Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, 6480 SourceLocation LabLoc, 6481 IdentifierInfo *LabelII) { 6482 // Look up the record for this label identifier. 6483 LabelStmt *&LabelDecl = getLabelMap()[LabelII]; 6484 6485 // If we haven't seen this label yet, create a forward reference. It 6486 // will be validated and/or cleaned up in ActOnFinishFunctionBody. 6487 if (LabelDecl == 0) 6488 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0); 6489 6490 // Create the AST node. The address of a label always has type 'void*'. 6491 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl, 6492 Context.getPointerType(Context.VoidTy))); 6493} 6494 6495Sema::OwningExprResult 6496Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt, 6497 SourceLocation RPLoc) { // "({..})" 6498 Stmt *SubStmt = static_cast<Stmt*>(substmt.get()); 6499 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 6500 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 6501 6502 bool isFileScope = getCurFunctionOrMethodDecl() == 0; 6503 if (isFileScope) 6504 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope)); 6505 6506 // FIXME: there are a variety of strange constraints to enforce here, for 6507 // example, it is not possible to goto into a stmt expression apparently. 6508 // More semantic analysis is needed. 6509 6510 // If there are sub stmts in the compound stmt, take the type of the last one 6511 // as the type of the stmtexpr. 6512 QualType Ty = Context.VoidTy; 6513 6514 if (!Compound->body_empty()) { 6515 Stmt *LastStmt = Compound->body_back(); 6516 // If LastStmt is a label, skip down through into the body. 6517 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) 6518 LastStmt = Label->getSubStmt(); 6519 6520 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) 6521 Ty = LastExpr->getType(); 6522 } 6523 6524 // FIXME: Check that expression type is complete/non-abstract; statement 6525 // expressions are not lvalues. 6526 6527 substmt.release(); 6528 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc)); 6529} 6530 6531Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 6532 SourceLocation BuiltinLoc, 6533 SourceLocation TypeLoc, 6534 TypeTy *argty, 6535 OffsetOfComponent *CompPtr, 6536 unsigned NumComponents, 6537 SourceLocation RPLoc) { 6538 // FIXME: This function leaks all expressions in the offset components on 6539 // error. 6540 // FIXME: Preserve type source info. 6541 QualType ArgTy = GetTypeFromParser(argty); 6542 assert(!ArgTy.isNull() && "Missing type argument!"); 6543 6544 bool Dependent = ArgTy->isDependentType(); 6545 6546 // We must have at least one component that refers to the type, and the first 6547 // one is known to be a field designator. Verify that the ArgTy represents 6548 // a struct/union/class. 6549 if (!Dependent && !ArgTy->isRecordType()) 6550 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy); 6551 6552 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable 6553 // with an incomplete type would be illegal. 6554 6555 // Otherwise, create a null pointer as the base, and iteratively process 6556 // the offsetof designators. 6557 QualType ArgTyPtr = Context.getPointerType(ArgTy); 6558 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr); 6559 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref, 6560 ArgTy, SourceLocation()); 6561 6562 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 6563 // GCC extension, diagnose them. 6564 // FIXME: This diagnostic isn't actually visible because the location is in 6565 // a system header! 6566 if (NumComponents != 1) 6567 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 6568 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); 6569 6570 if (!Dependent) { 6571 bool DidWarnAboutNonPOD = false; 6572 6573 if (RequireCompleteType(TypeLoc, Res->getType(), 6574 diag::err_offsetof_incomplete_type)) 6575 return ExprError(); 6576 6577 // FIXME: Dependent case loses a lot of information here. And probably 6578 // leaks like a sieve. 6579 for (unsigned i = 0; i != NumComponents; ++i) { 6580 const OffsetOfComponent &OC = CompPtr[i]; 6581 if (OC.isBrackets) { 6582 // Offset of an array sub-field. TODO: Should we allow vector elements? 6583 const ArrayType *AT = Context.getAsArrayType(Res->getType()); 6584 if (!AT) { 6585 Res->Destroy(Context); 6586 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 6587 << Res->getType()); 6588 } 6589 6590 // FIXME: C++: Verify that operator[] isn't overloaded. 6591 6592 // Promote the array so it looks more like a normal array subscript 6593 // expression. 6594 DefaultFunctionArrayConversion(Res); 6595 6596 // C99 6.5.2.1p1 6597 Expr *Idx = static_cast<Expr*>(OC.U.E); 6598 // FIXME: Leaks Res 6599 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType()) 6600 return ExprError(Diag(Idx->getLocStart(), 6601 diag::err_typecheck_subscript_not_integer) 6602 << Idx->getSourceRange()); 6603 6604 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(), 6605 OC.LocEnd); 6606 continue; 6607 } 6608 6609 const RecordType *RC = Res->getType()->getAs<RecordType>(); 6610 if (!RC) { 6611 Res->Destroy(Context); 6612 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 6613 << Res->getType()); 6614 } 6615 6616 // Get the decl corresponding to this. 6617 RecordDecl *RD = RC->getDecl(); 6618 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 6619 if (!CRD->isPOD() && !DidWarnAboutNonPOD && 6620 DiagRuntimeBehavior(BuiltinLoc, 6621 PDiag(diag::warn_offsetof_non_pod_type) 6622 << SourceRange(CompPtr[0].LocStart, OC.LocEnd) 6623 << Res->getType())) 6624 DidWarnAboutNonPOD = true; 6625 } 6626 6627 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 6628 LookupQualifiedName(R, RD); 6629 6630 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 6631 // FIXME: Leaks Res 6632 if (!MemberDecl) 6633 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 6634 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd)); 6635 6636 // FIXME: C++: Verify that MemberDecl isn't a static field. 6637 // FIXME: Verify that MemberDecl isn't a bitfield. 6638 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) { 6639 Res = BuildAnonymousStructUnionMemberReference( 6640 OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>(); 6641 } else { 6642 PerformObjectMemberConversion(Res, MemberDecl); 6643 // MemberDecl->getType() doesn't get the right qualifiers, but it 6644 // doesn't matter here. 6645 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd, 6646 MemberDecl->getType().getNonReferenceType()); 6647 } 6648 } 6649 } 6650 6651 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf, 6652 Context.getSizeType(), BuiltinLoc)); 6653} 6654 6655 6656Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc, 6657 TypeTy *arg1,TypeTy *arg2, 6658 SourceLocation RPLoc) { 6659 // FIXME: Preserve type source info. 6660 QualType argT1 = GetTypeFromParser(arg1); 6661 QualType argT2 = GetTypeFromParser(arg2); 6662 6663 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)"); 6664 6665 if (getLangOptions().CPlusPlus) { 6666 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus) 6667 << SourceRange(BuiltinLoc, RPLoc); 6668 return ExprError(); 6669 } 6670 6671 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, 6672 argT1, argT2, RPLoc)); 6673} 6674 6675Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 6676 ExprArg cond, 6677 ExprArg expr1, ExprArg expr2, 6678 SourceLocation RPLoc) { 6679 Expr *CondExpr = static_cast<Expr*>(cond.get()); 6680 Expr *LHSExpr = static_cast<Expr*>(expr1.get()); 6681 Expr *RHSExpr = static_cast<Expr*>(expr2.get()); 6682 6683 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 6684 6685 QualType resType; 6686 bool ValueDependent = false; 6687 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 6688 resType = Context.DependentTy; 6689 ValueDependent = true; 6690 } else { 6691 // The conditional expression is required to be a constant expression. 6692 llvm::APSInt condEval(32); 6693 SourceLocation ExpLoc; 6694 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc)) 6695 return ExprError(Diag(ExpLoc, 6696 diag::err_typecheck_choose_expr_requires_constant) 6697 << CondExpr->getSourceRange()); 6698 6699 // If the condition is > zero, then the AST type is the same as the LSHExpr. 6700 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType(); 6701 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent() 6702 : RHSExpr->isValueDependent(); 6703 } 6704 6705 cond.release(); expr1.release(); expr2.release(); 6706 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 6707 resType, RPLoc, 6708 resType->isDependentType(), 6709 ValueDependent)); 6710} 6711 6712//===----------------------------------------------------------------------===// 6713// Clang Extensions. 6714//===----------------------------------------------------------------------===// 6715 6716/// ActOnBlockStart - This callback is invoked when a block literal is started. 6717void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) { 6718 // Analyze block parameters. 6719 BlockSemaInfo *BSI = new BlockSemaInfo(); 6720 6721 // Add BSI to CurBlock. 6722 BSI->PrevBlockInfo = CurBlock; 6723 CurBlock = BSI; 6724 6725 BSI->ReturnType = QualType(); 6726 BSI->TheScope = BlockScope; 6727 BSI->hasBlockDeclRefExprs = false; 6728 BSI->hasPrototype = false; 6729 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking; 6730 CurFunctionNeedsScopeChecking = false; 6731 6732 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc); 6733 CurContext->addDecl(BSI->TheDecl); 6734 PushDeclContext(BlockScope, BSI->TheDecl); 6735} 6736 6737void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) { 6738 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!"); 6739 6740 if (ParamInfo.getNumTypeObjects() == 0 6741 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) { 6742 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 6743 QualType T = GetTypeForDeclarator(ParamInfo, CurScope); 6744 6745 if (T->isArrayType()) { 6746 Diag(ParamInfo.getSourceRange().getBegin(), 6747 diag::err_block_returns_array); 6748 return; 6749 } 6750 6751 // The parameter list is optional, if there was none, assume (). 6752 if (!T->isFunctionType()) 6753 T = Context.getFunctionType(T, NULL, 0, 0, 0); 6754 6755 CurBlock->hasPrototype = true; 6756 CurBlock->isVariadic = false; 6757 // Check for a valid sentinel attribute on this block. 6758 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) { 6759 Diag(ParamInfo.getAttributes()->getLoc(), 6760 diag::warn_attribute_sentinel_not_variadic) << 1; 6761 // FIXME: remove the attribute. 6762 } 6763 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType(); 6764 6765 // Do not allow returning a objc interface by-value. 6766 if (RetTy->isObjCInterfaceType()) { 6767 Diag(ParamInfo.getSourceRange().getBegin(), 6768 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy; 6769 return; 6770 } 6771 return; 6772 } 6773 6774 // Analyze arguments to block. 6775 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function && 6776 "Not a function declarator!"); 6777 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun; 6778 6779 CurBlock->hasPrototype = FTI.hasPrototype; 6780 CurBlock->isVariadic = true; 6781 6782 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes 6783 // no arguments, not a function that takes a single void argument. 6784 if (FTI.hasPrototype && 6785 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 6786 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&& 6787 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) { 6788 // empty arg list, don't push any params. 6789 CurBlock->isVariadic = false; 6790 } else if (FTI.hasPrototype) { 6791 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) 6792 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>()); 6793 CurBlock->isVariadic = FTI.isVariadic; 6794 } 6795 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(), 6796 CurBlock->Params.size()); 6797 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic); 6798 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 6799 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(), 6800 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) { 6801 (*AI)->setOwningFunction(CurBlock->TheDecl); 6802 6803 // If this has an identifier, add it to the scope stack. 6804 if ((*AI)->getIdentifier()) 6805 PushOnScopeChains(*AI, CurBlock->TheScope); 6806 } 6807 6808 // Check for a valid sentinel attribute on this block. 6809 if (!CurBlock->isVariadic && 6810 CurBlock->TheDecl->getAttr<SentinelAttr>()) { 6811 Diag(ParamInfo.getAttributes()->getLoc(), 6812 diag::warn_attribute_sentinel_not_variadic) << 1; 6813 // FIXME: remove the attribute. 6814 } 6815 6816 // Analyze the return type. 6817 QualType T = GetTypeForDeclarator(ParamInfo, CurScope); 6818 QualType RetTy = T->getAs<FunctionType>()->getResultType(); 6819 6820 // Do not allow returning a objc interface by-value. 6821 if (RetTy->isObjCInterfaceType()) { 6822 Diag(ParamInfo.getSourceRange().getBegin(), 6823 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy; 6824 } else if (!RetTy->isDependentType()) 6825 CurBlock->ReturnType = RetTy; 6826} 6827 6828/// ActOnBlockError - If there is an error parsing a block, this callback 6829/// is invoked to pop the information about the block from the action impl. 6830void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 6831 // Ensure that CurBlock is deleted. 6832 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock); 6833 6834 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking; 6835 6836 // Pop off CurBlock, handle nested blocks. 6837 PopDeclContext(); 6838 CurBlock = CurBlock->PrevBlockInfo; 6839 // FIXME: Delete the ParmVarDecl objects as well??? 6840} 6841 6842/// ActOnBlockStmtExpr - This is called when the body of a block statement 6843/// literal was successfully completed. ^(int x){...} 6844Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 6845 StmtArg body, Scope *CurScope) { 6846 // If blocks are disabled, emit an error. 6847 if (!LangOpts.Blocks) 6848 Diag(CaretLoc, diag::err_blocks_disable); 6849 6850 // Ensure that CurBlock is deleted. 6851 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock); 6852 6853 PopDeclContext(); 6854 6855 // Pop off CurBlock, handle nested blocks. 6856 CurBlock = CurBlock->PrevBlockInfo; 6857 6858 QualType RetTy = Context.VoidTy; 6859 if (!BSI->ReturnType.isNull()) 6860 RetTy = BSI->ReturnType; 6861 6862 llvm::SmallVector<QualType, 8> ArgTypes; 6863 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i) 6864 ArgTypes.push_back(BSI->Params[i]->getType()); 6865 6866 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>(); 6867 QualType BlockTy; 6868 if (!BSI->hasPrototype) 6869 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0, 6870 NoReturn); 6871 else 6872 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(), 6873 BSI->isVariadic, 0, false, false, 0, 0, 6874 NoReturn); 6875 6876 // FIXME: Check that return/parameter types are complete/non-abstract 6877 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end()); 6878 BlockTy = Context.getBlockPointerType(BlockTy); 6879 6880 // If needed, diagnose invalid gotos and switches in the block. 6881 if (CurFunctionNeedsScopeChecking) 6882 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get())); 6883 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking; 6884 6885 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>()); 6886 6887 bool Good = true; 6888 // Check goto/label use. 6889 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator 6890 I = BSI->LabelMap.begin(), E = BSI->LabelMap.end(); I != E; ++I) { 6891 LabelStmt *L = I->second; 6892 6893 // Verify that we have no forward references left. If so, there was a goto 6894 // or address of a label taken, but no definition of it. 6895 if (L->getSubStmt() != 0) 6896 continue; 6897 6898 // Emit error. 6899 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName(); 6900 Good = false; 6901 } 6902 BSI->LabelMap.clear(); 6903 if (!Good) 6904 return ExprError(); 6905 6906 AnalysisContext AC(BSI->TheDecl); 6907 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody(), AC); 6908 CheckUnreachable(AC); 6909 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy, 6910 BSI->hasBlockDeclRefExprs)); 6911} 6912 6913Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 6914 ExprArg expr, TypeTy *type, 6915 SourceLocation RPLoc) { 6916 QualType T = GetTypeFromParser(type); 6917 Expr *E = static_cast<Expr*>(expr.get()); 6918 Expr *OrigExpr = E; 6919 6920 InitBuiltinVaListType(); 6921 6922 // Get the va_list type 6923 QualType VaListType = Context.getBuiltinVaListType(); 6924 if (VaListType->isArrayType()) { 6925 // Deal with implicit array decay; for example, on x86-64, 6926 // va_list is an array, but it's supposed to decay to 6927 // a pointer for va_arg. 6928 VaListType = Context.getArrayDecayedType(VaListType); 6929 // Make sure the input expression also decays appropriately. 6930 UsualUnaryConversions(E); 6931 } else { 6932 // Otherwise, the va_list argument must be an l-value because 6933 // it is modified by va_arg. 6934 if (!E->isTypeDependent() && 6935 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 6936 return ExprError(); 6937 } 6938 6939 if (!E->isTypeDependent() && 6940 !Context.hasSameType(VaListType, E->getType())) { 6941 return ExprError(Diag(E->getLocStart(), 6942 diag::err_first_argument_to_va_arg_not_of_type_va_list) 6943 << OrigExpr->getType() << E->getSourceRange()); 6944 } 6945 6946 // FIXME: Check that type is complete/non-abstract 6947 // FIXME: Warn if a non-POD type is passed in. 6948 6949 expr.release(); 6950 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), 6951 RPLoc)); 6952} 6953 6954Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 6955 // The type of __null will be int or long, depending on the size of 6956 // pointers on the target. 6957 QualType Ty; 6958 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth()) 6959 Ty = Context.IntTy; 6960 else 6961 Ty = Context.LongTy; 6962 6963 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc)); 6964} 6965 6966static void 6967MakeObjCStringLiteralCodeModificationHint(Sema& SemaRef, 6968 QualType DstType, 6969 Expr *SrcExpr, 6970 CodeModificationHint &Hint) { 6971 if (!SemaRef.getLangOptions().ObjC1) 6972 return; 6973 6974 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 6975 if (!PT) 6976 return; 6977 6978 // Check if the destination is of type 'id'. 6979 if (!PT->isObjCIdType()) { 6980 // Check if the destination is the 'NSString' interface. 6981 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 6982 if (!ID || !ID->getIdentifier()->isStr("NSString")) 6983 return; 6984 } 6985 6986 // Strip off any parens and casts. 6987 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts()); 6988 if (!SL || SL->isWide()) 6989 return; 6990 6991 Hint = CodeModificationHint::CreateInsertion(SL->getLocStart(), "@"); 6992} 6993 6994bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 6995 SourceLocation Loc, 6996 QualType DstType, QualType SrcType, 6997 Expr *SrcExpr, AssignmentAction Action) { 6998 // Decode the result (notice that AST's are still created for extensions). 6999 bool isInvalid = false; 7000 unsigned DiagKind; 7001 CodeModificationHint Hint; 7002 7003 switch (ConvTy) { 7004 default: assert(0 && "Unknown conversion type"); 7005 case Compatible: return false; 7006 case PointerToInt: 7007 DiagKind = diag::ext_typecheck_convert_pointer_int; 7008 break; 7009 case IntToPointer: 7010 DiagKind = diag::ext_typecheck_convert_int_pointer; 7011 break; 7012 case IncompatiblePointer: 7013 MakeObjCStringLiteralCodeModificationHint(*this, DstType, SrcExpr, Hint); 7014 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 7015 break; 7016 case IncompatiblePointerSign: 7017 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 7018 break; 7019 case FunctionVoidPointer: 7020 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 7021 break; 7022 case CompatiblePointerDiscardsQualifiers: 7023 // If the qualifiers lost were because we were applying the 7024 // (deprecated) C++ conversion from a string literal to a char* 7025 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 7026 // Ideally, this check would be performed in 7027 // CheckPointerTypesForAssignment. However, that would require a 7028 // bit of refactoring (so that the second argument is an 7029 // expression, rather than a type), which should be done as part 7030 // of a larger effort to fix CheckPointerTypesForAssignment for 7031 // C++ semantics. 7032 if (getLangOptions().CPlusPlus && 7033 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 7034 return false; 7035 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 7036 break; 7037 case IncompatibleNestedPointerQualifiers: 7038 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 7039 break; 7040 case IntToBlockPointer: 7041 DiagKind = diag::err_int_to_block_pointer; 7042 break; 7043 case IncompatibleBlockPointer: 7044 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 7045 break; 7046 case IncompatibleObjCQualifiedId: 7047 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since 7048 // it can give a more specific diagnostic. 7049 DiagKind = diag::warn_incompatible_qualified_id; 7050 break; 7051 case IncompatibleVectors: 7052 DiagKind = diag::warn_incompatible_vectors; 7053 break; 7054 case Incompatible: 7055 DiagKind = diag::err_typecheck_convert_incompatible; 7056 isInvalid = true; 7057 break; 7058 } 7059 7060 Diag(Loc, DiagKind) << DstType << SrcType << Action 7061 << SrcExpr->getSourceRange() << Hint; 7062 return isInvalid; 7063} 7064 7065bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){ 7066 llvm::APSInt ICEResult; 7067 if (E->isIntegerConstantExpr(ICEResult, Context)) { 7068 if (Result) 7069 *Result = ICEResult; 7070 return false; 7071 } 7072 7073 Expr::EvalResult EvalResult; 7074 7075 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() || 7076 EvalResult.HasSideEffects) { 7077 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange(); 7078 7079 if (EvalResult.Diag) { 7080 // We only show the note if it's not the usual "invalid subexpression" 7081 // or if it's actually in a subexpression. 7082 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice || 7083 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens()) 7084 Diag(EvalResult.DiagLoc, EvalResult.Diag); 7085 } 7086 7087 return true; 7088 } 7089 7090 Diag(E->getExprLoc(), diag::ext_expr_not_ice) << 7091 E->getSourceRange(); 7092 7093 if (EvalResult.Diag && 7094 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored) 7095 Diag(EvalResult.DiagLoc, EvalResult.Diag); 7096 7097 if (Result) 7098 *Result = EvalResult.Val.getInt(); 7099 return false; 7100} 7101 7102void 7103Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) { 7104 ExprEvalContexts.push_back( 7105 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size())); 7106} 7107 7108void 7109Sema::PopExpressionEvaluationContext() { 7110 // Pop the current expression evaluation context off the stack. 7111 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back(); 7112 ExprEvalContexts.pop_back(); 7113 7114 if (Rec.Context == PotentiallyPotentiallyEvaluated) { 7115 if (Rec.PotentiallyReferenced) { 7116 // Mark any remaining declarations in the current position of the stack 7117 // as "referenced". If they were not meant to be referenced, semantic 7118 // analysis would have eliminated them (e.g., in ActOnCXXTypeId). 7119 for (PotentiallyReferencedDecls::iterator 7120 I = Rec.PotentiallyReferenced->begin(), 7121 IEnd = Rec.PotentiallyReferenced->end(); 7122 I != IEnd; ++I) 7123 MarkDeclarationReferenced(I->first, I->second); 7124 } 7125 7126 if (Rec.PotentiallyDiagnosed) { 7127 // Emit any pending diagnostics. 7128 for (PotentiallyEmittedDiagnostics::iterator 7129 I = Rec.PotentiallyDiagnosed->begin(), 7130 IEnd = Rec.PotentiallyDiagnosed->end(); 7131 I != IEnd; ++I) 7132 Diag(I->first, I->second); 7133 } 7134 } 7135 7136 // When are coming out of an unevaluated context, clear out any 7137 // temporaries that we may have created as part of the evaluation of 7138 // the expression in that context: they aren't relevant because they 7139 // will never be constructed. 7140 if (Rec.Context == Unevaluated && 7141 ExprTemporaries.size() > Rec.NumTemporaries) 7142 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries, 7143 ExprTemporaries.end()); 7144 7145 // Destroy the popped expression evaluation record. 7146 Rec.Destroy(); 7147} 7148 7149/// \brief Note that the given declaration was referenced in the source code. 7150/// 7151/// This routine should be invoke whenever a given declaration is referenced 7152/// in the source code, and where that reference occurred. If this declaration 7153/// reference means that the the declaration is used (C++ [basic.def.odr]p2, 7154/// C99 6.9p3), then the declaration will be marked as used. 7155/// 7156/// \param Loc the location where the declaration was referenced. 7157/// 7158/// \param D the declaration that has been referenced by the source code. 7159void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) { 7160 assert(D && "No declaration?"); 7161 7162 if (D->isUsed()) 7163 return; 7164 7165 // Mark a parameter or variable declaration "used", regardless of whether we're in a 7166 // template or not. The reason for this is that unevaluated expressions 7167 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and 7168 // -Wunused-parameters) 7169 if (isa<ParmVarDecl>(D) || 7170 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) 7171 D->setUsed(true); 7172 7173 // Do not mark anything as "used" within a dependent context; wait for 7174 // an instantiation. 7175 if (CurContext->isDependentContext()) 7176 return; 7177 7178 switch (ExprEvalContexts.back().Context) { 7179 case Unevaluated: 7180 // We are in an expression that is not potentially evaluated; do nothing. 7181 return; 7182 7183 case PotentiallyEvaluated: 7184 // We are in a potentially-evaluated expression, so this declaration is 7185 // "used"; handle this below. 7186 break; 7187 7188 case PotentiallyPotentiallyEvaluated: 7189 // We are in an expression that may be potentially evaluated; queue this 7190 // declaration reference until we know whether the expression is 7191 // potentially evaluated. 7192 ExprEvalContexts.back().addReferencedDecl(Loc, D); 7193 return; 7194 } 7195 7196 // Note that this declaration has been used. 7197 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) { 7198 unsigned TypeQuals; 7199 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) { 7200 if (!Constructor->isUsed()) 7201 DefineImplicitDefaultConstructor(Loc, Constructor); 7202 } else if (Constructor->isImplicit() && 7203 Constructor->isCopyConstructor(TypeQuals)) { 7204 if (!Constructor->isUsed()) 7205 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals); 7206 } 7207 7208 MaybeMarkVirtualMembersReferenced(Loc, Constructor); 7209 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) { 7210 if (Destructor->isImplicit() && !Destructor->isUsed()) 7211 DefineImplicitDestructor(Loc, Destructor); 7212 7213 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) { 7214 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() && 7215 MethodDecl->getOverloadedOperator() == OO_Equal) { 7216 if (!MethodDecl->isUsed()) 7217 DefineImplicitOverloadedAssign(Loc, MethodDecl); 7218 } 7219 } 7220 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 7221 // Implicit instantiation of function templates and member functions of 7222 // class templates. 7223 if (!Function->getBody() && Function->isImplicitlyInstantiable()) { 7224 bool AlreadyInstantiated = false; 7225 if (FunctionTemplateSpecializationInfo *SpecInfo 7226 = Function->getTemplateSpecializationInfo()) { 7227 if (SpecInfo->getPointOfInstantiation().isInvalid()) 7228 SpecInfo->setPointOfInstantiation(Loc); 7229 else if (SpecInfo->getTemplateSpecializationKind() 7230 == TSK_ImplicitInstantiation) 7231 AlreadyInstantiated = true; 7232 } else if (MemberSpecializationInfo *MSInfo 7233 = Function->getMemberSpecializationInfo()) { 7234 if (MSInfo->getPointOfInstantiation().isInvalid()) 7235 MSInfo->setPointOfInstantiation(Loc); 7236 else if (MSInfo->getTemplateSpecializationKind() 7237 == TSK_ImplicitInstantiation) 7238 AlreadyInstantiated = true; 7239 } 7240 7241 if (!AlreadyInstantiated) { 7242 if (isa<CXXRecordDecl>(Function->getDeclContext()) && 7243 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass()) 7244 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function, 7245 Loc)); 7246 else 7247 PendingImplicitInstantiations.push_back(std::make_pair(Function, 7248 Loc)); 7249 } 7250 } 7251 7252 // FIXME: keep track of references to static functions 7253 Function->setUsed(true); 7254 return; 7255 } 7256 7257 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 7258 // Implicit instantiation of static data members of class templates. 7259 if (Var->isStaticDataMember() && 7260 Var->getInstantiatedFromStaticDataMember()) { 7261 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo(); 7262 assert(MSInfo && "Missing member specialization information?"); 7263 if (MSInfo->getPointOfInstantiation().isInvalid() && 7264 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) { 7265 MSInfo->setPointOfInstantiation(Loc); 7266 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc)); 7267 } 7268 } 7269 7270 // FIXME: keep track of references to static data? 7271 7272 D->setUsed(true); 7273 return; 7274 } 7275} 7276 7277/// \brief Emit a diagnostic that describes an effect on the run-time behavior 7278/// of the program being compiled. 7279/// 7280/// This routine emits the given diagnostic when the code currently being 7281/// type-checked is "potentially evaluated", meaning that there is a 7282/// possibility that the code will actually be executable. Code in sizeof() 7283/// expressions, code used only during overload resolution, etc., are not 7284/// potentially evaluated. This routine will suppress such diagnostics or, 7285/// in the absolutely nutty case of potentially potentially evaluated 7286/// expressions (C++ typeid), queue the diagnostic to potentially emit it 7287/// later. 7288/// 7289/// This routine should be used for all diagnostics that describe the run-time 7290/// behavior of a program, such as passing a non-POD value through an ellipsis. 7291/// Failure to do so will likely result in spurious diagnostics or failures 7292/// during overload resolution or within sizeof/alignof/typeof/typeid. 7293bool Sema::DiagRuntimeBehavior(SourceLocation Loc, 7294 const PartialDiagnostic &PD) { 7295 switch (ExprEvalContexts.back().Context ) { 7296 case Unevaluated: 7297 // The argument will never be evaluated, so don't complain. 7298 break; 7299 7300 case PotentiallyEvaluated: 7301 Diag(Loc, PD); 7302 return true; 7303 7304 case PotentiallyPotentiallyEvaluated: 7305 ExprEvalContexts.back().addDiagnostic(Loc, PD); 7306 break; 7307 } 7308 7309 return false; 7310} 7311 7312bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 7313 CallExpr *CE, FunctionDecl *FD) { 7314 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 7315 return false; 7316 7317 PartialDiagnostic Note = 7318 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here) 7319 << FD->getDeclName() : PDiag(); 7320 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation(); 7321 7322 if (RequireCompleteType(Loc, ReturnType, 7323 FD ? 7324 PDiag(diag::err_call_function_incomplete_return) 7325 << CE->getSourceRange() << FD->getDeclName() : 7326 PDiag(diag::err_call_incomplete_return) 7327 << CE->getSourceRange(), 7328 std::make_pair(NoteLoc, Note))) 7329 return true; 7330 7331 return false; 7332} 7333 7334// Diagnose the common s/=/==/ typo. Note that adding parentheses 7335// will prevent this condition from triggering, which is what we want. 7336void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 7337 SourceLocation Loc; 7338 7339 unsigned diagnostic = diag::warn_condition_is_assignment; 7340 7341 if (isa<BinaryOperator>(E)) { 7342 BinaryOperator *Op = cast<BinaryOperator>(E); 7343 if (Op->getOpcode() != BinaryOperator::Assign) 7344 return; 7345 7346 // Greylist some idioms by putting them into a warning subcategory. 7347 if (ObjCMessageExpr *ME 7348 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 7349 Selector Sel = ME->getSelector(); 7350 7351 // self = [<foo> init...] 7352 if (isSelfExpr(Op->getLHS()) 7353 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init")) 7354 diagnostic = diag::warn_condition_is_idiomatic_assignment; 7355 7356 // <foo> = [<bar> nextObject] 7357 else if (Sel.isUnarySelector() && 7358 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject") 7359 diagnostic = diag::warn_condition_is_idiomatic_assignment; 7360 } 7361 7362 Loc = Op->getOperatorLoc(); 7363 } else if (isa<CXXOperatorCallExpr>(E)) { 7364 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E); 7365 if (Op->getOperator() != OO_Equal) 7366 return; 7367 7368 Loc = Op->getOperatorLoc(); 7369 } else { 7370 // Not an assignment. 7371 return; 7372 } 7373 7374 SourceLocation Open = E->getSourceRange().getBegin(); 7375 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd()); 7376 7377 Diag(Loc, diagnostic) 7378 << E->getSourceRange() 7379 << CodeModificationHint::CreateInsertion(Open, "(") 7380 << CodeModificationHint::CreateInsertion(Close, ")"); 7381 Diag(Loc, diag::note_condition_assign_to_comparison) 7382 << CodeModificationHint::CreateReplacement(Loc, "=="); 7383} 7384 7385bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) { 7386 DiagnoseAssignmentAsCondition(E); 7387 7388 if (!E->isTypeDependent()) { 7389 DefaultFunctionArrayConversion(E); 7390 7391 QualType T = E->getType(); 7392 7393 if (getLangOptions().CPlusPlus) { 7394 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4 7395 return true; 7396 } else if (!T->isScalarType()) { // C99 6.8.4.1p1 7397 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 7398 << T << E->getSourceRange(); 7399 return true; 7400 } 7401 } 7402 7403 return false; 7404} 7405