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