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