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