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