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