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