SemaExpr.cpp revision 2d2e9cfdc1dbb6e4a22f8c0b1abcd30437e3795d
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 "clang/AST/ASTContext.h" 16#include "clang/AST/DeclObjC.h" 17#include "clang/AST/ExprCXX.h" 18#include "clang/AST/ExprObjC.h" 19#include "clang/AST/DeclTemplate.h" 20#include "clang/Lex/Preprocessor.h" 21#include "clang/Lex/LiteralSupport.h" 22#include "clang/Basic/SourceManager.h" 23#include "clang/Basic/TargetInfo.h" 24#include "clang/Parse/DeclSpec.h" 25#include "clang/Parse/Designator.h" 26#include "clang/Parse/Scope.h" 27using namespace clang; 28 29/// \brief Determine whether the use of this declaration is valid, and 30/// emit any corresponding diagnostics. 31/// 32/// This routine diagnoses various problems with referencing 33/// declarations that can occur when using a declaration. For example, 34/// it might warn if a deprecated or unavailable declaration is being 35/// used, or produce an error (and return true) if a C++0x deleted 36/// function is being used. 37/// 38/// \returns true if there was an error (this declaration cannot be 39/// referenced), false otherwise. 40bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) { 41 // See if the decl is deprecated. 42 if (D->getAttr<DeprecatedAttr>()) { 43 // Implementing deprecated stuff requires referencing deprecated 44 // stuff. Don't warn if we are implementing a deprecated 45 // construct. 46 bool isSilenced = false; 47 48 if (NamedDecl *ND = getCurFunctionOrMethodDecl()) { 49 // If this reference happens *in* a deprecated function or method, don't 50 // warn. 51 isSilenced = ND->getAttr<DeprecatedAttr>(); 52 53 // If this is an Objective-C method implementation, check to see if the 54 // method was deprecated on the declaration, not the definition. 55 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND)) { 56 // The semantic decl context of a ObjCMethodDecl is the 57 // ObjCImplementationDecl. 58 if (ObjCImplementationDecl *Impl 59 = dyn_cast<ObjCImplementationDecl>(MD->getParent())) { 60 61 MD = Impl->getClassInterface()->getMethod(MD->getSelector(), 62 MD->isInstanceMethod()); 63 isSilenced |= MD && MD->getAttr<DeprecatedAttr>(); 64 } 65 } 66 } 67 68 if (!isSilenced) 69 Diag(Loc, diag::warn_deprecated) << D->getDeclName(); 70 } 71 72 // See if this is a deleted function. 73 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 74 if (FD->isDeleted()) { 75 Diag(Loc, diag::err_deleted_function_use); 76 Diag(D->getLocation(), diag::note_unavailable_here) << true; 77 return true; 78 } 79 } 80 81 // See if the decl is unavailable 82 if (D->getAttr<UnavailableAttr>()) { 83 Diag(Loc, diag::warn_unavailable) << D->getDeclName(); 84 Diag(D->getLocation(), diag::note_unavailable_here) << 0; 85 } 86 87 return false; 88} 89 90SourceRange Sema::getExprRange(ExprTy *E) const { 91 Expr *Ex = (Expr *)E; 92 return Ex? Ex->getSourceRange() : SourceRange(); 93} 94 95//===----------------------------------------------------------------------===// 96// Standard Promotions and Conversions 97//===----------------------------------------------------------------------===// 98 99/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 100void Sema::DefaultFunctionArrayConversion(Expr *&E) { 101 QualType Ty = E->getType(); 102 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 103 104 if (Ty->isFunctionType()) 105 ImpCastExprToType(E, Context.getPointerType(Ty)); 106 else if (Ty->isArrayType()) { 107 // In C90 mode, arrays only promote to pointers if the array expression is 108 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 109 // type 'array of type' is converted to an expression that has type 'pointer 110 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 111 // that has type 'array of type' ...". The relevant change is "an lvalue" 112 // (C90) to "an expression" (C99). 113 // 114 // C++ 4.2p1: 115 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 116 // T" can be converted to an rvalue of type "pointer to T". 117 // 118 if (getLangOptions().C99 || getLangOptions().CPlusPlus || 119 E->isLvalue(Context) == Expr::LV_Valid) 120 ImpCastExprToType(E, Context.getArrayDecayedType(Ty)); 121 } 122} 123 124/// UsualUnaryConversions - Performs various conversions that are common to most 125/// operators (C99 6.3). The conversions of array and function types are 126/// sometimes surpressed. For example, the array->pointer conversion doesn't 127/// apply if the array is an argument to the sizeof or address (&) operators. 128/// In these instances, this routine should *not* be called. 129Expr *Sema::UsualUnaryConversions(Expr *&Expr) { 130 QualType Ty = Expr->getType(); 131 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 132 133 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2 134 ImpCastExprToType(Expr, Context.IntTy); 135 else 136 DefaultFunctionArrayConversion(Expr); 137 138 return Expr; 139} 140 141/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 142/// do not have a prototype. Arguments that have type float are promoted to 143/// double. All other argument types are converted by UsualUnaryConversions(). 144void Sema::DefaultArgumentPromotion(Expr *&Expr) { 145 QualType Ty = Expr->getType(); 146 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 147 148 // If this is a 'float' (CVR qualified or typedef) promote to double. 149 if (const BuiltinType *BT = Ty->getAsBuiltinType()) 150 if (BT->getKind() == BuiltinType::Float) 151 return ImpCastExprToType(Expr, Context.DoubleTy); 152 153 UsualUnaryConversions(Expr); 154} 155 156// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 157// will warn if the resulting type is not a POD type. 158void Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) { 159 DefaultArgumentPromotion(Expr); 160 161 if (!Expr->getType()->isPODType()) { 162 Diag(Expr->getLocStart(), 163 diag::warn_cannot_pass_non_pod_arg_to_vararg) << 164 Expr->getType() << CT; 165 } 166} 167 168 169/// UsualArithmeticConversions - Performs various conversions that are common to 170/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 171/// routine returns the first non-arithmetic type found. The client is 172/// responsible for emitting appropriate error diagnostics. 173/// FIXME: verify the conversion rules for "complex int" are consistent with 174/// GCC. 175QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr, 176 bool isCompAssign) { 177 if (!isCompAssign) { 178 UsualUnaryConversions(lhsExpr); 179 UsualUnaryConversions(rhsExpr); 180 } 181 182 // For conversion purposes, we ignore any qualifiers. 183 // For example, "const float" and "float" are equivalent. 184 QualType lhs = 185 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType(); 186 QualType rhs = 187 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType(); 188 189 // If both types are identical, no conversion is needed. 190 if (lhs == rhs) 191 return lhs; 192 193 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 194 // The caller can deal with this (e.g. pointer + int). 195 if (!lhs->isArithmeticType() || !rhs->isArithmeticType()) 196 return lhs; 197 198 QualType destType = UsualArithmeticConversionsType(lhs, rhs); 199 if (!isCompAssign) { 200 ImpCastExprToType(lhsExpr, destType); 201 ImpCastExprToType(rhsExpr, destType); 202 } 203 return destType; 204} 205 206QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) { 207 // Perform the usual unary conversions. We do this early so that 208 // integral promotions to "int" can allow us to exit early, in the 209 // lhs == rhs check. Also, for conversion purposes, we ignore any 210 // qualifiers. For example, "const float" and "float" are 211 // equivalent. 212 if (lhs->isPromotableIntegerType()) 213 lhs = Context.IntTy; 214 else 215 lhs = lhs.getUnqualifiedType(); 216 if (rhs->isPromotableIntegerType()) 217 rhs = Context.IntTy; 218 else 219 rhs = rhs.getUnqualifiedType(); 220 221 // If both types are identical, no conversion is needed. 222 if (lhs == rhs) 223 return lhs; 224 225 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 226 // The caller can deal with this (e.g. pointer + int). 227 if (!lhs->isArithmeticType() || !rhs->isArithmeticType()) 228 return lhs; 229 230 // At this point, we have two different arithmetic types. 231 232 // Handle complex types first (C99 6.3.1.8p1). 233 if (lhs->isComplexType() || rhs->isComplexType()) { 234 // if we have an integer operand, the result is the complex type. 235 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) { 236 // convert the rhs to the lhs complex type. 237 return lhs; 238 } 239 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) { 240 // convert the lhs to the rhs complex type. 241 return rhs; 242 } 243 // This handles complex/complex, complex/float, or float/complex. 244 // When both operands are complex, the shorter operand is converted to the 245 // type of the longer, and that is the type of the result. This corresponds 246 // to what is done when combining two real floating-point operands. 247 // The fun begins when size promotion occur across type domains. 248 // From H&S 6.3.4: When one operand is complex and the other is a real 249 // floating-point type, the less precise type is converted, within it's 250 // real or complex domain, to the precision of the other type. For example, 251 // when combining a "long double" with a "double _Complex", the 252 // "double _Complex" is promoted to "long double _Complex". 253 int result = Context.getFloatingTypeOrder(lhs, rhs); 254 255 if (result > 0) { // The left side is bigger, convert rhs. 256 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs); 257 } else if (result < 0) { // The right side is bigger, convert lhs. 258 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs); 259 } 260 // At this point, lhs and rhs have the same rank/size. Now, make sure the 261 // domains match. This is a requirement for our implementation, C99 262 // does not require this promotion. 263 if (lhs != rhs) { // Domains don't match, we have complex/float mix. 264 if (lhs->isRealFloatingType()) { // handle "double, _Complex double". 265 return rhs; 266 } else { // handle "_Complex double, double". 267 return lhs; 268 } 269 } 270 return lhs; // The domain/size match exactly. 271 } 272 // Now handle "real" floating types (i.e. float, double, long double). 273 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) { 274 // if we have an integer operand, the result is the real floating type. 275 if (rhs->isIntegerType()) { 276 // convert rhs to the lhs floating point type. 277 return lhs; 278 } 279 if (rhs->isComplexIntegerType()) { 280 // convert rhs to the complex floating point type. 281 return Context.getComplexType(lhs); 282 } 283 if (lhs->isIntegerType()) { 284 // convert lhs to the rhs floating point type. 285 return rhs; 286 } 287 if (lhs->isComplexIntegerType()) { 288 // convert lhs to the complex floating point type. 289 return Context.getComplexType(rhs); 290 } 291 // We have two real floating types, float/complex combos were handled above. 292 // Convert the smaller operand to the bigger result. 293 int result = Context.getFloatingTypeOrder(lhs, rhs); 294 if (result > 0) // convert the rhs 295 return lhs; 296 assert(result < 0 && "illegal float comparison"); 297 return rhs; // convert the lhs 298 } 299 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) { 300 // Handle GCC complex int extension. 301 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType(); 302 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType(); 303 304 if (lhsComplexInt && rhsComplexInt) { 305 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(), 306 rhsComplexInt->getElementType()) >= 0) 307 return lhs; // convert the rhs 308 return rhs; 309 } else if (lhsComplexInt && rhs->isIntegerType()) { 310 // convert the rhs to the lhs complex type. 311 return lhs; 312 } else if (rhsComplexInt && lhs->isIntegerType()) { 313 // convert the lhs to the rhs complex type. 314 return rhs; 315 } 316 } 317 // Finally, we have two differing integer types. 318 // The rules for this case are in C99 6.3.1.8 319 int compare = Context.getIntegerTypeOrder(lhs, rhs); 320 bool lhsSigned = lhs->isSignedIntegerType(), 321 rhsSigned = rhs->isSignedIntegerType(); 322 QualType destType; 323 if (lhsSigned == rhsSigned) { 324 // Same signedness; use the higher-ranked type 325 destType = compare >= 0 ? lhs : rhs; 326 } else if (compare != (lhsSigned ? 1 : -1)) { 327 // The unsigned type has greater than or equal rank to the 328 // signed type, so use the unsigned type 329 destType = lhsSigned ? rhs : lhs; 330 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) { 331 // The two types are different widths; if we are here, that 332 // means the signed type is larger than the unsigned type, so 333 // use the signed type. 334 destType = lhsSigned ? lhs : rhs; 335 } else { 336 // The signed type is higher-ranked than the unsigned type, 337 // but isn't actually any bigger (like unsigned int and long 338 // on most 32-bit systems). Use the unsigned type corresponding 339 // to the signed type. 340 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs); 341 } 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/// FIXME: This will create BlockDeclRefExprs for global variables, 397/// function references, etc which is suboptimal :) and breaks 398/// things like "integer constant expression" tests. 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 return Var->hasLocalStorage(); 415 416 return true; 417} 418 419 420 421/// ActOnIdentifierExpr - The parser read an identifier in expression context, 422/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this 423/// identifier is used in a function call context. 424/// SS is only used for a C++ qualified-id (foo::bar) to indicate the 425/// class or namespace that the identifier must be a member of. 426Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc, 427 IdentifierInfo &II, 428 bool HasTrailingLParen, 429 const CXXScopeSpec *SS, 430 bool isAddressOfOperand) { 431 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS, 432 isAddressOfOperand); 433} 434 435/// BuildDeclRefExpr - Build either a DeclRefExpr or a 436/// QualifiedDeclRefExpr based on whether or not SS is a 437/// nested-name-specifier. 438DeclRefExpr * 439Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc, 440 bool TypeDependent, bool ValueDependent, 441 const CXXScopeSpec *SS) { 442 if (SS && !SS->isEmpty()) 443 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent, 444 ValueDependent, 445 SS->getRange().getBegin()); 446 else 447 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent); 448} 449 450/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or 451/// variable corresponding to the anonymous union or struct whose type 452/// is Record. 453static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) { 454 assert(Record->isAnonymousStructOrUnion() && 455 "Record must be an anonymous struct or union!"); 456 457 // FIXME: Once Decls are directly linked together, this will 458 // be an O(1) operation rather than a slow walk through DeclContext's 459 // vector (which itself will be eliminated). DeclGroups might make 460 // this even better. 461 DeclContext *Ctx = Record->getDeclContext(); 462 for (DeclContext::decl_iterator D = Ctx->decls_begin(), 463 DEnd = Ctx->decls_end(); 464 D != DEnd; ++D) { 465 if (*D == Record) { 466 // The object for the anonymous struct/union directly 467 // follows its type in the list of declarations. 468 ++D; 469 assert(D != DEnd && "Missing object for anonymous record"); 470 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed"); 471 return *D; 472 } 473 } 474 475 assert(false && "Missing object for anonymous record"); 476 return 0; 477} 478 479Sema::OwningExprResult 480Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc, 481 FieldDecl *Field, 482 Expr *BaseObjectExpr, 483 SourceLocation OpLoc) { 484 assert(Field->getDeclContext()->isRecord() && 485 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion() 486 && "Field must be stored inside an anonymous struct or union"); 487 488 // Construct the sequence of field member references 489 // we'll have to perform to get to the field in the anonymous 490 // union/struct. The list of members is built from the field 491 // outward, so traverse it backwards to go from an object in 492 // the current context to the field we found. 493 llvm::SmallVector<FieldDecl *, 4> AnonFields; 494 AnonFields.push_back(Field); 495 VarDecl *BaseObject = 0; 496 DeclContext *Ctx = Field->getDeclContext(); 497 do { 498 RecordDecl *Record = cast<RecordDecl>(Ctx); 499 Decl *AnonObject = getObjectForAnonymousRecordDecl(Record); 500 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject)) 501 AnonFields.push_back(AnonField); 502 else { 503 BaseObject = cast<VarDecl>(AnonObject); 504 break; 505 } 506 Ctx = Ctx->getParent(); 507 } while (Ctx->isRecord() && 508 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()); 509 510 // Build the expression that refers to the base object, from 511 // which we will build a sequence of member references to each 512 // of the anonymous union objects and, eventually, the field we 513 // found via name lookup. 514 bool BaseObjectIsPointer = false; 515 unsigned ExtraQuals = 0; 516 if (BaseObject) { 517 // BaseObject is an anonymous struct/union variable (and is, 518 // therefore, not part of another non-anonymous record). 519 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context); 520 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(), 521 SourceLocation()); 522 ExtraQuals 523 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers(); 524 } else if (BaseObjectExpr) { 525 // The caller provided the base object expression. Determine 526 // whether its a pointer and whether it adds any qualifiers to the 527 // anonymous struct/union fields we're looking into. 528 QualType ObjectType = BaseObjectExpr->getType(); 529 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) { 530 BaseObjectIsPointer = true; 531 ObjectType = ObjectPtr->getPointeeType(); 532 } 533 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers(); 534 } else { 535 // We've found a member of an anonymous struct/union that is 536 // inside a non-anonymous struct/union, so in a well-formed 537 // program our base object expression is "this". 538 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) { 539 if (!MD->isStatic()) { 540 QualType AnonFieldType 541 = Context.getTagDeclType( 542 cast<RecordDecl>(AnonFields.back()->getDeclContext())); 543 QualType ThisType = Context.getTagDeclType(MD->getParent()); 544 if ((Context.getCanonicalType(AnonFieldType) 545 == Context.getCanonicalType(ThisType)) || 546 IsDerivedFrom(ThisType, AnonFieldType)) { 547 // Our base object expression is "this". 548 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(), 549 MD->getThisType(Context)); 550 BaseObjectIsPointer = true; 551 } 552 } else { 553 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method) 554 << Field->getDeclName()); 555 } 556 ExtraQuals = MD->getTypeQualifiers(); 557 } 558 559 if (!BaseObjectExpr) 560 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use) 561 << Field->getDeclName()); 562 } 563 564 // Build the implicit member references to the field of the 565 // anonymous struct/union. 566 Expr *Result = BaseObjectExpr; 567 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator 568 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend(); 569 FI != FIEnd; ++FI) { 570 QualType MemberType = (*FI)->getType(); 571 if (!(*FI)->isMutable()) { 572 unsigned combinedQualifiers 573 = MemberType.getCVRQualifiers() | ExtraQuals; 574 MemberType = MemberType.getQualifiedType(combinedQualifiers); 575 } 576 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI, 577 OpLoc, MemberType); 578 BaseObjectIsPointer = false; 579 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers(); 580 } 581 582 return Owned(Result); 583} 584 585/// ActOnDeclarationNameExpr - The parser has read some kind of name 586/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine 587/// performs lookup on that name and returns an expression that refers 588/// to that name. This routine isn't directly called from the parser, 589/// because the parser doesn't know about DeclarationName. Rather, 590/// this routine is called by ActOnIdentifierExpr, 591/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr, 592/// which form the DeclarationName from the corresponding syntactic 593/// forms. 594/// 595/// HasTrailingLParen indicates whether this identifier is used in a 596/// function call context. LookupCtx is only used for a C++ 597/// qualified-id (foo::bar) to indicate the class or namespace that 598/// the identifier must be a member of. 599/// 600/// isAddressOfOperand means that this expression is the direct operand 601/// of an address-of operator. This matters because this is the only 602/// situation where a qualified name referencing a non-static member may 603/// appear outside a member function of this class. 604Sema::OwningExprResult 605Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc, 606 DeclarationName Name, bool HasTrailingLParen, 607 const CXXScopeSpec *SS, 608 bool isAddressOfOperand) { 609 // Could be enum-constant, value decl, instance variable, etc. 610 if (SS && SS->isInvalid()) 611 return ExprError(); 612 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName, 613 false, true, Loc); 614 615 NamedDecl *D = 0; 616 if (Lookup.isAmbiguous()) { 617 DiagnoseAmbiguousLookup(Lookup, Name, Loc, 618 SS && SS->isSet() ? SS->getRange() 619 : SourceRange()); 620 return ExprError(); 621 } else 622 D = Lookup.getAsDecl(); 623 624 // If this reference is in an Objective-C method, then ivar lookup happens as 625 // well. 626 IdentifierInfo *II = Name.getAsIdentifierInfo(); 627 if (II && getCurMethodDecl()) { 628 // There are two cases to handle here. 1) scoped lookup could have failed, 629 // in which case we should look for an ivar. 2) scoped lookup could have 630 // found a decl, but that decl is outside the current instance method (i.e. 631 // a global variable). In these two cases, we do a lookup for an ivar with 632 // this name, if the lookup sucedes, we replace it our current decl. 633 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) { 634 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface(); 635 ObjCInterfaceDecl *ClassDeclared; 636 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 637 // Check if referencing a field with __attribute__((deprecated)). 638 if (DiagnoseUseOfDecl(IV, Loc)) 639 return ExprError(); 640 bool IsClsMethod = getCurMethodDecl()->isClassMethod(); 641 // If a class method attemps to use a free standing ivar, this is 642 // an error. 643 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod()) 644 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 645 << IV->getDeclName()); 646 // If a class method uses a global variable, even if an ivar with 647 // same name exists, use the global. 648 if (!IsClsMethod) { 649 if (IV->getAccessControl() == ObjCIvarDecl::Private && 650 ClassDeclared != IFace) 651 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 652 // FIXME: This should use a new expr for a direct reference, don't turn 653 // this into Self->ivar, just return a BareIVarExpr or something. 654 IdentifierInfo &II = Context.Idents.get("self"); 655 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false); 656 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(), 657 Loc, static_cast<Expr*>(SelfExpr.release()), 658 true, true); 659 Context.setFieldDecl(IFace, IV, MRef); 660 return Owned(MRef); 661 } 662 } 663 } 664 else if (getCurMethodDecl()->isInstanceMethod()) { 665 // We should warn if a local variable hides an ivar. 666 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface(); 667 ObjCInterfaceDecl *ClassDeclared; 668 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 669 if (IV->getAccessControl() != ObjCIvarDecl::Private || 670 IFace == ClassDeclared) 671 Diag(Loc, diag::warn_ivar_use_hidden)<<IV->getDeclName(); 672 } 673 } 674 // Needed to implement property "super.method" notation. 675 if (D == 0 && II->isStr("super")) { 676 QualType T; 677 678 if (getCurMethodDecl()->isInstanceMethod()) 679 T = Context.getPointerType(Context.getObjCInterfaceType( 680 getCurMethodDecl()->getClassInterface())); 681 else 682 T = Context.getObjCClassType(); 683 return Owned(new (Context) ObjCSuperExpr(Loc, T)); 684 } 685 } 686 687 // Determine whether this name might be a candidate for 688 // argument-dependent lookup. 689 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) && 690 HasTrailingLParen; 691 692 if (ADL && D == 0) { 693 // We've seen something of the form 694 // 695 // identifier( 696 // 697 // and we did not find any entity by the name 698 // "identifier". However, this identifier is still subject to 699 // argument-dependent lookup, so keep track of the name. 700 return Owned(new (Context) UnresolvedFunctionNameExpr(Name, 701 Context.OverloadTy, 702 Loc)); 703 } 704 705 if (D == 0) { 706 // Otherwise, this could be an implicitly declared function reference (legal 707 // in C90, extension in C99). 708 if (HasTrailingLParen && II && 709 !getLangOptions().CPlusPlus) // Not in C++. 710 D = ImplicitlyDefineFunction(Loc, *II, S); 711 else { 712 // If this name wasn't predeclared and if this is not a function call, 713 // diagnose the problem. 714 if (SS && !SS->isEmpty()) 715 return ExprError(Diag(Loc, diag::err_typecheck_no_member) 716 << Name << SS->getRange()); 717 else if (Name.getNameKind() == DeclarationName::CXXOperatorName || 718 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) 719 return ExprError(Diag(Loc, diag::err_undeclared_use) 720 << Name.getAsString()); 721 else 722 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name); 723 } 724 } 725 726 // If this is an expression of the form &Class::member, don't build an 727 // implicit member ref, because we want a pointer to the member in general, 728 // not any specific instance's member. 729 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) { 730 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep()); 731 if (D && isa<CXXRecordDecl>(DC)) { 732 QualType DType; 733 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 734 DType = FD->getType().getNonReferenceType(); 735 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 736 DType = Method->getType(); 737 } else if (isa<OverloadedFunctionDecl>(D)) { 738 DType = Context.OverloadTy; 739 } 740 // Could be an inner type. That's diagnosed below, so ignore it here. 741 if (!DType.isNull()) { 742 // The pointer is type- and value-dependent if it points into something 743 // dependent. 744 bool Dependent = false; 745 for (; DC; DC = DC->getParent()) { 746 // FIXME: could stop early at namespace scope. 747 if (DC->isRecord()) { 748 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 749 if (Context.getTypeDeclType(Record)->isDependentType()) { 750 Dependent = true; 751 break; 752 } 753 } 754 } 755 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS)); 756 } 757 } 758 } 759 760 // We may have found a field within an anonymous union or struct 761 // (C++ [class.union]). 762 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) 763 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion()) 764 return BuildAnonymousStructUnionMemberReference(Loc, FD); 765 766 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) { 767 if (!MD->isStatic()) { 768 // C++ [class.mfct.nonstatic]p2: 769 // [...] if name lookup (3.4.1) resolves the name in the 770 // id-expression to a nonstatic nontype member of class X or of 771 // a base class of X, the id-expression is transformed into a 772 // class member access expression (5.2.5) using (*this) (9.3.2) 773 // as the postfix-expression to the left of the '.' operator. 774 DeclContext *Ctx = 0; 775 QualType MemberType; 776 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 777 Ctx = FD->getDeclContext(); 778 MemberType = FD->getType(); 779 780 if (const ReferenceType *RefType = MemberType->getAsReferenceType()) 781 MemberType = RefType->getPointeeType(); 782 else if (!FD->isMutable()) { 783 unsigned combinedQualifiers 784 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers(); 785 MemberType = MemberType.getQualifiedType(combinedQualifiers); 786 } 787 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 788 if (!Method->isStatic()) { 789 Ctx = Method->getParent(); 790 MemberType = Method->getType(); 791 } 792 } else if (OverloadedFunctionDecl *Ovl 793 = dyn_cast<OverloadedFunctionDecl>(D)) { 794 for (OverloadedFunctionDecl::function_iterator 795 Func = Ovl->function_begin(), 796 FuncEnd = Ovl->function_end(); 797 Func != FuncEnd; ++Func) { 798 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func)) 799 if (!DMethod->isStatic()) { 800 Ctx = Ovl->getDeclContext(); 801 MemberType = Context.OverloadTy; 802 break; 803 } 804 } 805 } 806 807 if (Ctx && Ctx->isRecord()) { 808 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx)); 809 QualType ThisType = Context.getTagDeclType(MD->getParent()); 810 if ((Context.getCanonicalType(CtxType) 811 == Context.getCanonicalType(ThisType)) || 812 IsDerivedFrom(ThisType, CtxType)) { 813 // Build the implicit member access expression. 814 Expr *This = new (Context) CXXThisExpr(SourceLocation(), 815 MD->getThisType(Context)); 816 return Owned(new (Context) MemberExpr(This, true, D, 817 SourceLocation(), MemberType)); 818 } 819 } 820 } 821 } 822 823 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 824 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) { 825 if (MD->isStatic()) 826 // "invalid use of member 'x' in static member function" 827 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method) 828 << FD->getDeclName()); 829 } 830 831 // Any other ways we could have found the field in a well-formed 832 // program would have been turned into implicit member expressions 833 // above. 834 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use) 835 << FD->getDeclName()); 836 } 837 838 if (isa<TypedefDecl>(D)) 839 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name); 840 if (isa<ObjCInterfaceDecl>(D)) 841 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name); 842 if (isa<NamespaceDecl>(D)) 843 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name); 844 845 // Make the DeclRefExpr or BlockDeclRefExpr for the decl. 846 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D)) 847 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc, 848 false, false, SS)); 849 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 850 return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc, 851 false, false, SS)); 852 ValueDecl *VD = cast<ValueDecl>(D); 853 854 // Check whether this declaration can be used. Note that we suppress 855 // this check when we're going to perform argument-dependent lookup 856 // on this function name, because this might not be the function 857 // that overload resolution actually selects. 858 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc)) 859 return ExprError(); 860 861 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) { 862 // Warn about constructs like: 863 // if (void *X = foo()) { ... } else { X }. 864 // In the else block, the pointer is always false. 865 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) { 866 Scope *CheckS = S; 867 while (CheckS) { 868 if (CheckS->isWithinElse() && 869 CheckS->getControlParent()->isDeclScope(Var)) { 870 if (Var->getType()->isBooleanType()) 871 ExprError(Diag(Loc, diag::warn_value_always_false) 872 << Var->getDeclName()); 873 else 874 ExprError(Diag(Loc, diag::warn_value_always_zero) 875 << Var->getDeclName()); 876 break; 877 } 878 879 // Move up one more control parent to check again. 880 CheckS = CheckS->getControlParent(); 881 if (CheckS) 882 CheckS = CheckS->getParent(); 883 } 884 } 885 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(VD)) { 886 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) { 887 // C99 DR 316 says that, if a function type comes from a 888 // function definition (without a prototype), that type is only 889 // used for checking compatibility. Therefore, when referencing 890 // the function, we pretend that we don't have the full function 891 // type. 892 QualType T = Func->getType(); 893 QualType NoProtoType = T; 894 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType()) 895 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType()); 896 return Owned(BuildDeclRefExpr(VD, NoProtoType, Loc, false, false, SS)); 897 } 898 } 899 900 // Only create DeclRefExpr's for valid Decl's. 901 if (VD->isInvalidDecl()) 902 return ExprError(); 903 904 // If the identifier reference is inside a block, and it refers to a value 905 // that is outside the block, create a BlockDeclRefExpr instead of a 906 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when 907 // the block is formed. 908 // 909 // We do not do this for things like enum constants, global variables, etc, 910 // as they do not get snapshotted. 911 // 912 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) { 913 // Blocks that have these can't be constant. 914 CurBlock->hasBlockDeclRefExprs = true; 915 916 // The BlocksAttr indicates the variable is bound by-reference. 917 if (VD->getAttr<BlocksAttr>()) 918 return Owned(new (Context) BlockDeclRefExpr(VD, 919 VD->getType().getNonReferenceType(), Loc, true)); 920 921 // Variable will be bound by-copy, make it const within the closure. 922 VD->getType().addConst(); 923 return Owned(new (Context) BlockDeclRefExpr(VD, 924 VD->getType().getNonReferenceType(), Loc, false)); 925 } 926 // If this reference is not in a block or if the referenced variable is 927 // within the block, create a normal DeclRefExpr. 928 929 bool TypeDependent = false; 930 bool ValueDependent = false; 931 if (getLangOptions().CPlusPlus) { 932 // C++ [temp.dep.expr]p3: 933 // An id-expression is type-dependent if it contains: 934 // - an identifier that was declared with a dependent type, 935 if (VD->getType()->isDependentType()) 936 TypeDependent = true; 937 // - FIXME: a template-id that is dependent, 938 // - a conversion-function-id that specifies a dependent type, 939 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 940 Name.getCXXNameType()->isDependentType()) 941 TypeDependent = true; 942 // - a nested-name-specifier that contains a class-name that 943 // names a dependent type. 944 else if (SS && !SS->isEmpty()) { 945 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep()); 946 DC; DC = DC->getParent()) { 947 // FIXME: could stop early at namespace scope. 948 if (DC->isRecord()) { 949 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 950 if (Context.getTypeDeclType(Record)->isDependentType()) { 951 TypeDependent = true; 952 break; 953 } 954 } 955 } 956 } 957 958 // C++ [temp.dep.constexpr]p2: 959 // 960 // An identifier is value-dependent if it is: 961 // - a name declared with a dependent type, 962 if (TypeDependent) 963 ValueDependent = true; 964 // - the name of a non-type template parameter, 965 else if (isa<NonTypeTemplateParmDecl>(VD)) 966 ValueDependent = true; 967 // - a constant with integral or enumeration type and is 968 // initialized with an expression that is value-dependent 969 // (FIXME!). 970 } 971 972 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, 973 TypeDependent, ValueDependent, SS)); 974} 975 976Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, 977 tok::TokenKind Kind) { 978 PredefinedExpr::IdentType IT; 979 980 switch (Kind) { 981 default: assert(0 && "Unknown simple primary expr!"); 982 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 983 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 984 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 985 } 986 987 // Pre-defined identifiers are of type char[x], where x is the length of the 988 // string. 989 unsigned Length; 990 if (FunctionDecl *FD = getCurFunctionDecl()) 991 Length = FD->getIdentifier()->getLength(); 992 else if (ObjCMethodDecl *MD = getCurMethodDecl()) 993 Length = MD->getSynthesizedMethodSize(); 994 else { 995 Diag(Loc, diag::ext_predef_outside_function); 996 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string. 997 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0; 998 } 999 1000 1001 llvm::APInt LengthI(32, Length + 1); 1002 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const); 1003 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); 1004 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT)); 1005} 1006 1007Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) { 1008 llvm::SmallString<16> CharBuffer; 1009 CharBuffer.resize(Tok.getLength()); 1010 const char *ThisTokBegin = &CharBuffer[0]; 1011 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin); 1012 1013 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength, 1014 Tok.getLocation(), PP); 1015 if (Literal.hadError()) 1016 return ExprError(); 1017 1018 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy; 1019 1020 return Owned(new (Context) CharacterLiteral(Literal.getValue(), 1021 Literal.isWide(), 1022 type, Tok.getLocation())); 1023} 1024 1025Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) { 1026 // Fast path for a single digit (which is quite common). A single digit 1027 // cannot have a trigraph, escaped newline, radix prefix, or type suffix. 1028 if (Tok.getLength() == 1) { 1029 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 1030 unsigned IntSize = Context.Target.getIntWidth(); 1031 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'), 1032 Context.IntTy, Tok.getLocation())); 1033 } 1034 1035 llvm::SmallString<512> IntegerBuffer; 1036 // Add padding so that NumericLiteralParser can overread by one character. 1037 IntegerBuffer.resize(Tok.getLength()+1); 1038 const char *ThisTokBegin = &IntegerBuffer[0]; 1039 1040 // Get the spelling of the token, which eliminates trigraphs, etc. 1041 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin); 1042 1043 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength, 1044 Tok.getLocation(), PP); 1045 if (Literal.hadError) 1046 return ExprError(); 1047 1048 Expr *Res; 1049 1050 if (Literal.isFloatingLiteral()) { 1051 QualType Ty; 1052 if (Literal.isFloat) 1053 Ty = Context.FloatTy; 1054 else if (!Literal.isLong) 1055 Ty = Context.DoubleTy; 1056 else 1057 Ty = Context.LongDoubleTy; 1058 1059 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty); 1060 1061 // isExact will be set by GetFloatValue(). 1062 bool isExact = false; 1063 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact), 1064 &isExact, Ty, Tok.getLocation()); 1065 1066 } else if (!Literal.isIntegerLiteral()) { 1067 return ExprError(); 1068 } else { 1069 QualType Ty; 1070 1071 // long long is a C99 feature. 1072 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x && 1073 Literal.isLongLong) 1074 Diag(Tok.getLocation(), diag::ext_longlong); 1075 1076 // Get the value in the widest-possible width. 1077 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0); 1078 1079 if (Literal.GetIntegerValue(ResultVal)) { 1080 // If this value didn't fit into uintmax_t, warn and force to ull. 1081 Diag(Tok.getLocation(), diag::warn_integer_too_large); 1082 Ty = Context.UnsignedLongLongTy; 1083 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 1084 "long long is not intmax_t?"); 1085 } else { 1086 // If this value fits into a ULL, try to figure out what else it fits into 1087 // according to the rules of C99 6.4.4.1p5. 1088 1089 // Octal, Hexadecimal, and integers with a U suffix are allowed to 1090 // be an unsigned int. 1091 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 1092 1093 // Check from smallest to largest, picking the smallest type we can. 1094 unsigned Width = 0; 1095 if (!Literal.isLong && !Literal.isLongLong) { 1096 // Are int/unsigned possibilities? 1097 unsigned IntSize = Context.Target.getIntWidth(); 1098 1099 // Does it fit in a unsigned int? 1100 if (ResultVal.isIntN(IntSize)) { 1101 // Does it fit in a signed int? 1102 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 1103 Ty = Context.IntTy; 1104 else if (AllowUnsigned) 1105 Ty = Context.UnsignedIntTy; 1106 Width = IntSize; 1107 } 1108 } 1109 1110 // Are long/unsigned long possibilities? 1111 if (Ty.isNull() && !Literal.isLongLong) { 1112 unsigned LongSize = Context.Target.getLongWidth(); 1113 1114 // Does it fit in a unsigned long? 1115 if (ResultVal.isIntN(LongSize)) { 1116 // Does it fit in a signed long? 1117 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 1118 Ty = Context.LongTy; 1119 else if (AllowUnsigned) 1120 Ty = Context.UnsignedLongTy; 1121 Width = LongSize; 1122 } 1123 } 1124 1125 // Finally, check long long if needed. 1126 if (Ty.isNull()) { 1127 unsigned LongLongSize = Context.Target.getLongLongWidth(); 1128 1129 // Does it fit in a unsigned long long? 1130 if (ResultVal.isIntN(LongLongSize)) { 1131 // Does it fit in a signed long long? 1132 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0) 1133 Ty = Context.LongLongTy; 1134 else if (AllowUnsigned) 1135 Ty = Context.UnsignedLongLongTy; 1136 Width = LongLongSize; 1137 } 1138 } 1139 1140 // If we still couldn't decide a type, we probably have something that 1141 // does not fit in a signed long long, but has no U suffix. 1142 if (Ty.isNull()) { 1143 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed); 1144 Ty = Context.UnsignedLongLongTy; 1145 Width = Context.Target.getLongLongWidth(); 1146 } 1147 1148 if (ResultVal.getBitWidth() != Width) 1149 ResultVal.trunc(Width); 1150 } 1151 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation()); 1152 } 1153 1154 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 1155 if (Literal.isImaginary) 1156 Res = new (Context) ImaginaryLiteral(Res, 1157 Context.getComplexType(Res->getType())); 1158 1159 return Owned(Res); 1160} 1161 1162Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L, 1163 SourceLocation R, ExprArg Val) { 1164 Expr *E = (Expr *)Val.release(); 1165 assert((E != 0) && "ActOnParenExpr() missing expr"); 1166 return Owned(new (Context) ParenExpr(L, R, E)); 1167} 1168 1169/// The UsualUnaryConversions() function is *not* called by this routine. 1170/// See C99 6.3.2.1p[2-4] for more details. 1171bool Sema::CheckSizeOfAlignOfOperand(QualType exprType, 1172 SourceLocation OpLoc, 1173 const SourceRange &ExprRange, 1174 bool isSizeof) { 1175 if (exprType->isDependentType()) 1176 return false; 1177 1178 // C99 6.5.3.4p1: 1179 if (isa<FunctionType>(exprType)) { 1180 // alignof(function) is allowed. 1181 if (isSizeof) 1182 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange; 1183 return false; 1184 } 1185 1186 if (exprType->isVoidType()) { 1187 Diag(OpLoc, diag::ext_sizeof_void_type) 1188 << (isSizeof ? "sizeof" : "__alignof") << ExprRange; 1189 return false; 1190 } 1191 1192 return RequireCompleteType(OpLoc, exprType, 1193 isSizeof ? diag::err_sizeof_incomplete_type : 1194 diag::err_alignof_incomplete_type, 1195 ExprRange); 1196} 1197 1198bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc, 1199 const SourceRange &ExprRange) { 1200 E = E->IgnoreParens(); 1201 1202 // alignof decl is always ok. 1203 if (isa<DeclRefExpr>(E)) 1204 return false; 1205 1206 // Cannot know anything else if the expression is dependent. 1207 if (E->isTypeDependent()) 1208 return false; 1209 1210 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 1211 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 1212 if (FD->isBitField()) { 1213 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange; 1214 return true; 1215 } 1216 // Other fields are ok. 1217 return false; 1218 } 1219 } 1220 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false); 1221} 1222 1223/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and 1224/// the same for @c alignof and @c __alignof 1225/// Note that the ArgRange is invalid if isType is false. 1226Action::OwningExprResult 1227Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType, 1228 void *TyOrEx, const SourceRange &ArgRange) { 1229 // If error parsing type, ignore. 1230 if (TyOrEx == 0) return ExprError(); 1231 1232 QualType ArgTy; 1233 SourceRange Range; 1234 if (isType) { 1235 ArgTy = QualType::getFromOpaquePtr(TyOrEx); 1236 Range = ArgRange; 1237 1238 // Verify that the operand is valid. 1239 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof)) 1240 return ExprError(); 1241 } else { 1242 // Get the end location. 1243 Expr *ArgEx = (Expr *)TyOrEx; 1244 Range = ArgEx->getSourceRange(); 1245 ArgTy = ArgEx->getType(); 1246 1247 // Verify that the operand is valid. 1248 bool isInvalid; 1249 if (!isSizeof) { 1250 isInvalid = CheckAlignOfExpr(ArgEx, OpLoc, Range); 1251 } else if (ArgEx->isBitField()) { // C99 6.5.3.4p1. 1252 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0; 1253 isInvalid = true; 1254 } else { 1255 isInvalid = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, true); 1256 } 1257 1258 if (isInvalid) { 1259 DeleteExpr(ArgEx); 1260 return ExprError(); 1261 } 1262 } 1263 1264 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 1265 return Owned(new (Context) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx, 1266 Context.getSizeType(), OpLoc, 1267 Range.getEnd())); 1268} 1269 1270QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) { 1271 if (V->isTypeDependent()) 1272 return Context.DependentTy; 1273 1274 DefaultFunctionArrayConversion(V); 1275 1276 // These operators return the element type of a complex type. 1277 if (const ComplexType *CT = V->getType()->getAsComplexType()) 1278 return CT->getElementType(); 1279 1280 // Otherwise they pass through real integer and floating point types here. 1281 if (V->getType()->isArithmeticType()) 1282 return V->getType(); 1283 1284 // Reject anything else. 1285 Diag(Loc, diag::err_realimag_invalid_type) << V->getType() 1286 << (isReal ? "__real" : "__imag"); 1287 return QualType(); 1288} 1289 1290 1291 1292Action::OwningExprResult 1293Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 1294 tok::TokenKind Kind, ExprArg Input) { 1295 Expr *Arg = (Expr *)Input.get(); 1296 1297 UnaryOperator::Opcode Opc; 1298 switch (Kind) { 1299 default: assert(0 && "Unknown unary op!"); 1300 case tok::plusplus: Opc = UnaryOperator::PostInc; break; 1301 case tok::minusminus: Opc = UnaryOperator::PostDec; break; 1302 } 1303 1304 if (getLangOptions().CPlusPlus && 1305 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) { 1306 // Which overloaded operator? 1307 OverloadedOperatorKind OverOp = 1308 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus; 1309 1310 // C++ [over.inc]p1: 1311 // 1312 // [...] If the function is a member function with one 1313 // parameter (which shall be of type int) or a non-member 1314 // function with two parameters (the second of which shall be 1315 // of type int), it defines the postfix increment operator ++ 1316 // for objects of that type. When the postfix increment is 1317 // called as a result of using the ++ operator, the int 1318 // argument will have value zero. 1319 Expr *Args[2] = { 1320 Arg, 1321 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0, 1322 /*isSigned=*/true), Context.IntTy, SourceLocation()) 1323 }; 1324 1325 // Build the candidate set for overloading 1326 OverloadCandidateSet CandidateSet; 1327 if (AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet)) 1328 return ExprError(); 1329 1330 // Perform overload resolution. 1331 OverloadCandidateSet::iterator Best; 1332 switch (BestViableFunction(CandidateSet, Best)) { 1333 case OR_Success: { 1334 // We found a built-in operator or an overloaded operator. 1335 FunctionDecl *FnDecl = Best->Function; 1336 1337 if (FnDecl) { 1338 // We matched an overloaded operator. Build a call to that 1339 // operator. 1340 1341 // Convert the arguments. 1342 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 1343 if (PerformObjectArgumentInitialization(Arg, Method)) 1344 return ExprError(); 1345 } else { 1346 // Convert the arguments. 1347 if (PerformCopyInitialization(Arg, 1348 FnDecl->getParamDecl(0)->getType(), 1349 "passing")) 1350 return ExprError(); 1351 } 1352 1353 // Determine the result type 1354 QualType ResultTy 1355 = FnDecl->getType()->getAsFunctionType()->getResultType(); 1356 ResultTy = ResultTy.getNonReferenceType(); 1357 1358 // Build the actual expression node. 1359 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(), 1360 SourceLocation()); 1361 UsualUnaryConversions(FnExpr); 1362 1363 Input.release(); 1364 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2, 1365 ResultTy, OpLoc)); 1366 } else { 1367 // We matched a built-in operator. Convert the arguments, then 1368 // break out so that we will build the appropriate built-in 1369 // operator node. 1370 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0], 1371 "passing")) 1372 return ExprError(); 1373 1374 break; 1375 } 1376 } 1377 1378 case OR_No_Viable_Function: 1379 // No viable function; fall through to handling this as a 1380 // built-in operator, which will produce an error message for us. 1381 break; 1382 1383 case OR_Ambiguous: 1384 Diag(OpLoc, diag::err_ovl_ambiguous_oper) 1385 << UnaryOperator::getOpcodeStr(Opc) 1386 << Arg->getSourceRange(); 1387 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 1388 return ExprError(); 1389 1390 case OR_Deleted: 1391 Diag(OpLoc, diag::err_ovl_deleted_oper) 1392 << Best->Function->isDeleted() 1393 << UnaryOperator::getOpcodeStr(Opc) 1394 << Arg->getSourceRange(); 1395 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 1396 return ExprError(); 1397 } 1398 1399 // Either we found no viable overloaded operator or we matched a 1400 // built-in operator. In either case, fall through to trying to 1401 // build a built-in operation. 1402 } 1403 1404 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc, 1405 Opc == UnaryOperator::PostInc); 1406 if (result.isNull()) 1407 return ExprError(); 1408 Input.release(); 1409 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc)); 1410} 1411 1412Action::OwningExprResult 1413Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc, 1414 ExprArg Idx, SourceLocation RLoc) { 1415 Expr *LHSExp = static_cast<Expr*>(Base.get()), 1416 *RHSExp = static_cast<Expr*>(Idx.get()); 1417 1418 if (getLangOptions().CPlusPlus && 1419 (LHSExp->getType()->isRecordType() || 1420 LHSExp->getType()->isEnumeralType() || 1421 RHSExp->getType()->isRecordType() || 1422 RHSExp->getType()->isEnumeralType())) { 1423 // Add the appropriate overloaded operators (C++ [over.match.oper]) 1424 // to the candidate set. 1425 OverloadCandidateSet CandidateSet; 1426 Expr *Args[2] = { LHSExp, RHSExp }; 1427 if (AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet, 1428 SourceRange(LLoc, RLoc))) 1429 return ExprError(); 1430 1431 // Perform overload resolution. 1432 OverloadCandidateSet::iterator Best; 1433 switch (BestViableFunction(CandidateSet, Best)) { 1434 case OR_Success: { 1435 // We found a built-in operator or an overloaded operator. 1436 FunctionDecl *FnDecl = Best->Function; 1437 1438 if (FnDecl) { 1439 // We matched an overloaded operator. Build a call to that 1440 // operator. 1441 1442 // Convert the arguments. 1443 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 1444 if (PerformObjectArgumentInitialization(LHSExp, Method) || 1445 PerformCopyInitialization(RHSExp, 1446 FnDecl->getParamDecl(0)->getType(), 1447 "passing")) 1448 return ExprError(); 1449 } else { 1450 // Convert the arguments. 1451 if (PerformCopyInitialization(LHSExp, 1452 FnDecl->getParamDecl(0)->getType(), 1453 "passing") || 1454 PerformCopyInitialization(RHSExp, 1455 FnDecl->getParamDecl(1)->getType(), 1456 "passing")) 1457 return ExprError(); 1458 } 1459 1460 // Determine the result type 1461 QualType ResultTy 1462 = FnDecl->getType()->getAsFunctionType()->getResultType(); 1463 ResultTy = ResultTy.getNonReferenceType(); 1464 1465 // Build the actual expression node. 1466 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(), 1467 SourceLocation()); 1468 UsualUnaryConversions(FnExpr); 1469 1470 Base.release(); 1471 Idx.release(); 1472 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2, 1473 ResultTy, LLoc)); 1474 } else { 1475 // We matched a built-in operator. Convert the arguments, then 1476 // break out so that we will build the appropriate built-in 1477 // operator node. 1478 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0], 1479 "passing") || 1480 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1], 1481 "passing")) 1482 return ExprError(); 1483 1484 break; 1485 } 1486 } 1487 1488 case OR_No_Viable_Function: 1489 // No viable function; fall through to handling this as a 1490 // built-in operator, which will produce an error message for us. 1491 break; 1492 1493 case OR_Ambiguous: 1494 Diag(LLoc, diag::err_ovl_ambiguous_oper) 1495 << "[]" 1496 << LHSExp->getSourceRange() << RHSExp->getSourceRange(); 1497 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 1498 return ExprError(); 1499 1500 case OR_Deleted: 1501 Diag(LLoc, diag::err_ovl_deleted_oper) 1502 << Best->Function->isDeleted() 1503 << "[]" 1504 << LHSExp->getSourceRange() << RHSExp->getSourceRange(); 1505 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 1506 return ExprError(); 1507 } 1508 1509 // Either we found no viable overloaded operator or we matched a 1510 // built-in operator. In either case, fall through to trying to 1511 // build a built-in operation. 1512 } 1513 1514 // Perform default conversions. 1515 DefaultFunctionArrayConversion(LHSExp); 1516 DefaultFunctionArrayConversion(RHSExp); 1517 1518 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 1519 1520 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 1521 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 1522 // in the subscript position. As a result, we need to derive the array base 1523 // and index from the expression types. 1524 Expr *BaseExpr, *IndexExpr; 1525 QualType ResultType; 1526 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 1527 BaseExpr = LHSExp; 1528 IndexExpr = RHSExp; 1529 ResultType = Context.DependentTy; 1530 } else if (const PointerType *PTy = LHSTy->getAsPointerType()) { 1531 BaseExpr = LHSExp; 1532 IndexExpr = RHSExp; 1533 // FIXME: need to deal with const... 1534 ResultType = PTy->getPointeeType(); 1535 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) { 1536 // Handle the uncommon case of "123[Ptr]". 1537 BaseExpr = RHSExp; 1538 IndexExpr = LHSExp; 1539 // FIXME: need to deal with const... 1540 ResultType = PTy->getPointeeType(); 1541 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) { 1542 BaseExpr = LHSExp; // vectors: V[123] 1543 IndexExpr = RHSExp; 1544 1545 // FIXME: need to deal with const... 1546 ResultType = VTy->getElementType(); 1547 } else { 1548 return ExprError(Diag(LHSExp->getLocStart(), 1549 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange()); 1550 } 1551 // C99 6.5.2.1p1 1552 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 1553 return ExprError(Diag(IndexExpr->getLocStart(), 1554 diag::err_typecheck_subscript) << IndexExpr->getSourceRange()); 1555 1556 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice, 1557 // the following check catches trying to index a pointer to a function (e.g. 1558 // void (*)(int)) and pointers to incomplete types. Functions are not 1559 // objects in C99. 1560 if (!ResultType->isObjectType() && !ResultType->isDependentType()) 1561 return ExprError(Diag(BaseExpr->getLocStart(), 1562 diag::err_typecheck_subscript_not_object) 1563 << BaseExpr->getType() << BaseExpr->getSourceRange()); 1564 1565 Base.release(); 1566 Idx.release(); 1567 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 1568 ResultType, RLoc)); 1569} 1570 1571QualType Sema:: 1572CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc, 1573 IdentifierInfo &CompName, SourceLocation CompLoc) { 1574 const ExtVectorType *vecType = baseType->getAsExtVectorType(); 1575 1576 // The vector accessor can't exceed the number of elements. 1577 const char *compStr = CompName.getName(); 1578 1579 // This flag determines whether or not the component is one of the four 1580 // special names that indicate a subset of exactly half the elements are 1581 // to be selected. 1582 bool HalvingSwizzle = false; 1583 1584 // This flag determines whether or not CompName has an 's' char prefix, 1585 // indicating that it is a string of hex values to be used as vector indices. 1586 bool HexSwizzle = *compStr == 's'; 1587 1588 // Check that we've found one of the special components, or that the component 1589 // names must come from the same set. 1590 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") || 1591 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) { 1592 HalvingSwizzle = true; 1593 } else if (vecType->getPointAccessorIdx(*compStr) != -1) { 1594 do 1595 compStr++; 1596 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1); 1597 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) { 1598 do 1599 compStr++; 1600 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1); 1601 } 1602 1603 if (!HalvingSwizzle && *compStr) { 1604 // We didn't get to the end of the string. This means the component names 1605 // didn't come from the same set *or* we encountered an illegal name. 1606 Diag(OpLoc, diag::err_ext_vector_component_name_illegal) 1607 << std::string(compStr,compStr+1) << SourceRange(CompLoc); 1608 return QualType(); 1609 } 1610 1611 // Ensure no component accessor exceeds the width of the vector type it 1612 // operates on. 1613 if (!HalvingSwizzle) { 1614 compStr = CompName.getName(); 1615 1616 if (HexSwizzle) 1617 compStr++; 1618 1619 while (*compStr) { 1620 if (!vecType->isAccessorWithinNumElements(*compStr++)) { 1621 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length) 1622 << baseType << SourceRange(CompLoc); 1623 return QualType(); 1624 } 1625 } 1626 } 1627 1628 // If this is a halving swizzle, verify that the base type has an even 1629 // number of elements. 1630 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) { 1631 Diag(OpLoc, diag::err_ext_vector_component_requires_even) 1632 << baseType << SourceRange(CompLoc); 1633 return QualType(); 1634 } 1635 1636 // The component accessor looks fine - now we need to compute the actual type. 1637 // The vector type is implied by the component accessor. For example, 1638 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc. 1639 // vec4.s0 is a float, vec4.s23 is a vec3, etc. 1640 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2. 1641 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2 1642 : CompName.getLength(); 1643 if (HexSwizzle) 1644 CompSize--; 1645 1646 if (CompSize == 1) 1647 return vecType->getElementType(); 1648 1649 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize); 1650 // Now look up the TypeDefDecl from the vector type. Without this, 1651 // diagostics look bad. We want extended vector types to appear built-in. 1652 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) { 1653 if (ExtVectorDecls[i]->getUnderlyingType() == VT) 1654 return Context.getTypedefType(ExtVectorDecls[i]); 1655 } 1656 return VT; // should never get here (a typedef type should always be found). 1657} 1658 1659 1660Action::OwningExprResult 1661Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc, 1662 tok::TokenKind OpKind, SourceLocation MemberLoc, 1663 IdentifierInfo &Member, 1664 DeclTy *ObjCImpDecl) { 1665 Expr *BaseExpr = static_cast<Expr *>(Base.release()); 1666 assert(BaseExpr && "no record expression"); 1667 1668 // Perform default conversions. 1669 DefaultFunctionArrayConversion(BaseExpr); 1670 1671 QualType BaseType = BaseExpr->getType(); 1672 assert(!BaseType.isNull() && "no type for member expression"); 1673 1674 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr 1675 // must have pointer type, and the accessed type is the pointee. 1676 if (OpKind == tok::arrow) { 1677 if (const PointerType *PT = BaseType->getAsPointerType()) 1678 BaseType = PT->getPointeeType(); 1679 else if (getLangOptions().CPlusPlus && BaseType->isRecordType()) 1680 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc, 1681 MemberLoc, Member)); 1682 else 1683 return ExprError(Diag(MemberLoc, 1684 diag::err_typecheck_member_reference_arrow) 1685 << BaseType << BaseExpr->getSourceRange()); 1686 } 1687 1688 // Handle field access to simple records. This also handles access to fields 1689 // of the ObjC 'id' struct. 1690 if (const RecordType *RTy = BaseType->getAsRecordType()) { 1691 RecordDecl *RDecl = RTy->getDecl(); 1692 if (RequireCompleteType(OpLoc, BaseType, 1693 diag::err_typecheck_incomplete_tag, 1694 BaseExpr->getSourceRange())) 1695 return ExprError(); 1696 1697 // The record definition is complete, now make sure the member is valid. 1698 // FIXME: Qualified name lookup for C++ is a bit more complicated 1699 // than this. 1700 LookupResult Result 1701 = LookupQualifiedName(RDecl, DeclarationName(&Member), 1702 LookupMemberName, false); 1703 1704 NamedDecl *MemberDecl = 0; 1705 if (!Result) 1706 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member) 1707 << &Member << BaseExpr->getSourceRange()); 1708 else if (Result.isAmbiguous()) { 1709 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member), 1710 MemberLoc, BaseExpr->getSourceRange()); 1711 return ExprError(); 1712 } else 1713 MemberDecl = Result; 1714 1715 // If the decl being referenced had an error, return an error for this 1716 // sub-expr without emitting another error, in order to avoid cascading 1717 // error cases. 1718 if (MemberDecl->isInvalidDecl()) 1719 return ExprError(); 1720 1721 // Check the use of this field 1722 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc)) 1723 return ExprError(); 1724 1725 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) { 1726 // We may have found a field within an anonymous union or struct 1727 // (C++ [class.union]). 1728 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion()) 1729 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD, 1730 BaseExpr, OpLoc); 1731 1732 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref] 1733 // FIXME: Handle address space modifiers 1734 QualType MemberType = FD->getType(); 1735 if (const ReferenceType *Ref = MemberType->getAsReferenceType()) 1736 MemberType = Ref->getPointeeType(); 1737 else { 1738 unsigned combinedQualifiers = 1739 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers(); 1740 if (FD->isMutable()) 1741 combinedQualifiers &= ~QualType::Const; 1742 MemberType = MemberType.getQualifiedType(combinedQualifiers); 1743 } 1744 1745 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD, 1746 MemberLoc, MemberType)); 1747 } else if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) 1748 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, 1749 Var, MemberLoc, 1750 Var->getType().getNonReferenceType())); 1751 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) 1752 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, 1753 MemberFn, MemberLoc, MemberFn->getType())); 1754 else if (OverloadedFunctionDecl *Ovl 1755 = dyn_cast<OverloadedFunctionDecl>(MemberDecl)) 1756 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl, 1757 MemberLoc, Context.OverloadTy)); 1758 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) 1759 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, 1760 Enum, MemberLoc, Enum->getType())); 1761 else if (isa<TypeDecl>(MemberDecl)) 1762 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type) 1763 << DeclarationName(&Member) << int(OpKind == tok::arrow)); 1764 1765 // We found a declaration kind that we didn't expect. This is a 1766 // generic error message that tells the user that she can't refer 1767 // to this member with '.' or '->'. 1768 return ExprError(Diag(MemberLoc, 1769 diag::err_typecheck_member_reference_unknown) 1770 << DeclarationName(&Member) << int(OpKind == tok::arrow)); 1771 } 1772 1773 // Handle access to Objective-C instance variables, such as "Obj->ivar" and 1774 // (*Obj).ivar. 1775 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) { 1776 ObjCInterfaceDecl *ClassDeclared; 1777 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member, 1778 ClassDeclared)) { 1779 // If the decl being referenced had an error, return an error for this 1780 // sub-expr without emitting another error, in order to avoid cascading 1781 // error cases. 1782 if (IV->isInvalidDecl()) 1783 return ExprError(); 1784 1785 // Check whether we can reference this field. 1786 if (DiagnoseUseOfDecl(IV, MemberLoc)) 1787 return ExprError(); 1788 if (IV->getAccessControl() != ObjCIvarDecl::Public) { 1789 ObjCInterfaceDecl *ClassOfMethodDecl = 0; 1790 if (ObjCMethodDecl *MD = getCurMethodDecl()) 1791 ClassOfMethodDecl = MD->getClassInterface(); 1792 else if (ObjCImpDecl && getCurFunctionDecl()) { 1793 // Case of a c-function declared inside an objc implementation. 1794 // FIXME: For a c-style function nested inside an objc implementation 1795 // class, there is no implementation context available, so we pass down 1796 // the context as argument to this routine. Ideally, this context need 1797 // be passed down in the AST node and somehow calculated from the AST 1798 // for a function decl. 1799 Decl *ImplDecl = static_cast<Decl *>(ObjCImpDecl); 1800 if (ObjCImplementationDecl *IMPD = 1801 dyn_cast<ObjCImplementationDecl>(ImplDecl)) 1802 ClassOfMethodDecl = IMPD->getClassInterface(); 1803 else if (ObjCCategoryImplDecl* CatImplClass = 1804 dyn_cast<ObjCCategoryImplDecl>(ImplDecl)) 1805 ClassOfMethodDecl = CatImplClass->getClassInterface(); 1806 } 1807 if (IV->getAccessControl() == ObjCIvarDecl::Private) { 1808 if (ClassDeclared != IFTy->getDecl() || 1809 ClassOfMethodDecl != ClassDeclared) 1810 Diag(MemberLoc, diag::error_private_ivar_access) << IV->getDeclName(); 1811 } 1812 // @protected 1813 else if (!IFTy->getDecl()->isSuperClassOf(ClassOfMethodDecl)) 1814 Diag(MemberLoc, diag::error_protected_ivar_access) << IV->getDeclName(); 1815 } 1816 1817 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(), 1818 MemberLoc, BaseExpr, 1819 OpKind == tok::arrow); 1820 Context.setFieldDecl(IFTy->getDecl(), IV, MRef); 1821 return Owned(MRef); 1822 } 1823 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar) 1824 << IFTy->getDecl()->getDeclName() << &Member 1825 << BaseExpr->getSourceRange()); 1826 } 1827 1828 // Handle Objective-C property access, which is "Obj.property" where Obj is a 1829 // pointer to a (potentially qualified) interface type. 1830 const PointerType *PTy; 1831 const ObjCInterfaceType *IFTy; 1832 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) && 1833 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) { 1834 ObjCInterfaceDecl *IFace = IFTy->getDecl(); 1835 1836 // Search for a declared property first. 1837 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) { 1838 // Check whether we can reference this property. 1839 if (DiagnoseUseOfDecl(PD, MemberLoc)) 1840 return ExprError(); 1841 1842 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(), 1843 MemberLoc, BaseExpr)); 1844 } 1845 1846 // Check protocols on qualified interfaces. 1847 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(), 1848 E = IFTy->qual_end(); I != E; ++I) 1849 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) { 1850 // Check whether we can reference this property. 1851 if (DiagnoseUseOfDecl(PD, MemberLoc)) 1852 return ExprError(); 1853 1854 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(), 1855 MemberLoc, BaseExpr)); 1856 } 1857 1858 // If that failed, look for an "implicit" property by seeing if the nullary 1859 // selector is implemented. 1860 1861 // FIXME: The logic for looking up nullary and unary selectors should be 1862 // shared with the code in ActOnInstanceMessage. 1863 1864 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member); 1865 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel); 1866 1867 // If this reference is in an @implementation, check for 'private' methods. 1868 if (!Getter) 1869 if (ObjCImplementationDecl *ImpDecl = 1870 ObjCImplementations[IFace->getIdentifier()]) 1871 Getter = ImpDecl->getInstanceMethod(Sel); 1872 1873 // Look through local category implementations associated with the class. 1874 if (!Getter) { 1875 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) { 1876 if (ObjCCategoryImpls[i]->getClassInterface() == IFace) 1877 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel); 1878 } 1879 } 1880 if (Getter) { 1881 // Check if we can reference this property. 1882 if (DiagnoseUseOfDecl(Getter, MemberLoc)) 1883 return ExprError(); 1884 } 1885 // If we found a getter then this may be a valid dot-reference, we 1886 // will look for the matching setter, in case it is needed. 1887 Selector SetterSel = 1888 SelectorTable::constructSetterName(PP.getIdentifierTable(), 1889 PP.getSelectorTable(), &Member); 1890 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel); 1891 if (!Setter) { 1892 // If this reference is in an @implementation, also check for 'private' 1893 // methods. 1894 if (ObjCImplementationDecl *ImpDecl = 1895 ObjCImplementations[IFace->getIdentifier()]) 1896 Setter = ImpDecl->getInstanceMethod(SetterSel); 1897 } 1898 // Look through local category implementations associated with the class. 1899 if (!Setter) { 1900 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) { 1901 if (ObjCCategoryImpls[i]->getClassInterface() == IFace) 1902 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel); 1903 } 1904 } 1905 1906 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc)) 1907 return ExprError(); 1908 1909 if (Getter || Setter) { 1910 QualType PType; 1911 1912 if (Getter) 1913 PType = Getter->getResultType(); 1914 else { 1915 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(), 1916 E = Setter->param_end(); PI != E; ++PI) 1917 PType = (*PI)->getType(); 1918 } 1919 // FIXME: we must check that the setter has property type. 1920 return Owned(new (Context) ObjCKVCRefExpr(Getter, PType, 1921 Setter, MemberLoc, BaseExpr)); 1922 } 1923 return ExprError(Diag(MemberLoc, diag::err_property_not_found) 1924 << &Member << BaseType); 1925 } 1926 // Handle properties on qualified "id" protocols. 1927 const ObjCQualifiedIdType *QIdTy; 1928 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) { 1929 // Check protocols on qualified interfaces. 1930 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(), 1931 E = QIdTy->qual_end(); I != E; ++I) { 1932 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) { 1933 // Check the use of this declaration 1934 if (DiagnoseUseOfDecl(PD, MemberLoc)) 1935 return ExprError(); 1936 1937 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(), 1938 MemberLoc, BaseExpr)); 1939 } 1940 // Also must look for a getter name which uses property syntax. 1941 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member); 1942 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) { 1943 // Check the use of this method. 1944 if (DiagnoseUseOfDecl(OMD, MemberLoc)) 1945 return ExprError(); 1946 1947 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel, 1948 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0)); 1949 } 1950 } 1951 1952 return ExprError(Diag(MemberLoc, diag::err_property_not_found) 1953 << &Member << BaseType); 1954 } 1955 // Handle properties on ObjC 'Class' types. 1956 if (OpKind == tok::period && (BaseType == Context.getObjCClassType())) { 1957 // Also must look for a getter name which uses property syntax. 1958 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member); 1959 if (ObjCMethodDecl *MD = getCurMethodDecl()) { 1960 ObjCInterfaceDecl *IFace = MD->getClassInterface(); 1961 ObjCMethodDecl *Getter; 1962 // FIXME: need to also look locally in the implementation. 1963 if ((Getter = IFace->lookupClassMethod(Sel))) { 1964 // Check the use of this method. 1965 if (DiagnoseUseOfDecl(Getter, MemberLoc)) 1966 return ExprError(); 1967 } 1968 // If we found a getter then this may be a valid dot-reference, we 1969 // will look for the matching setter, in case it is needed. 1970 Selector SetterSel = 1971 SelectorTable::constructSetterName(PP.getIdentifierTable(), 1972 PP.getSelectorTable(), &Member); 1973 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel); 1974 if (!Setter) { 1975 // If this reference is in an @implementation, also check for 'private' 1976 // methods. 1977 if (ObjCImplementationDecl *ImpDecl = 1978 ObjCImplementations[IFace->getIdentifier()]) 1979 Setter = ImpDecl->getInstanceMethod(SetterSel); 1980 } 1981 // Look through local category implementations associated with the class. 1982 if (!Setter) { 1983 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) { 1984 if (ObjCCategoryImpls[i]->getClassInterface() == IFace) 1985 Setter = ObjCCategoryImpls[i]->getClassMethod(SetterSel); 1986 } 1987 } 1988 1989 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc)) 1990 return ExprError(); 1991 1992 if (Getter || Setter) { 1993 QualType PType; 1994 1995 if (Getter) 1996 PType = Getter->getResultType(); 1997 else { 1998 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(), 1999 E = Setter->param_end(); PI != E; ++PI) 2000 PType = (*PI)->getType(); 2001 } 2002 // FIXME: we must check that the setter has property type. 2003 return Owned(new (Context) ObjCKVCRefExpr(Getter, PType, 2004 Setter, MemberLoc, BaseExpr)); 2005 } 2006 return ExprError(Diag(MemberLoc, diag::err_property_not_found) 2007 << &Member << BaseType); 2008 } 2009 } 2010 2011 // Handle 'field access' to vectors, such as 'V.xx'. 2012 if (BaseType->isExtVectorType()) { 2013 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc); 2014 if (ret.isNull()) 2015 return ExprError(); 2016 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member, 2017 MemberLoc)); 2018 } 2019 2020 return ExprError(Diag(MemberLoc, 2021 diag::err_typecheck_member_reference_struct_union) 2022 << BaseType << BaseExpr->getSourceRange()); 2023} 2024 2025/// ConvertArgumentsForCall - Converts the arguments specified in 2026/// Args/NumArgs to the parameter types of the function FDecl with 2027/// function prototype Proto. Call is the call expression itself, and 2028/// Fn is the function expression. For a C++ member function, this 2029/// routine does not attempt to convert the object argument. Returns 2030/// true if the call is ill-formed. 2031bool 2032Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 2033 FunctionDecl *FDecl, 2034 const FunctionProtoType *Proto, 2035 Expr **Args, unsigned NumArgs, 2036 SourceLocation RParenLoc) { 2037 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 2038 // assignment, to the types of the corresponding parameter, ... 2039 unsigned NumArgsInProto = Proto->getNumArgs(); 2040 unsigned NumArgsToCheck = NumArgs; 2041 bool Invalid = false; 2042 2043 // If too few arguments are available (and we don't have default 2044 // arguments for the remaining parameters), don't make the call. 2045 if (NumArgs < NumArgsInProto) { 2046 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments()) 2047 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args) 2048 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange(); 2049 // Use default arguments for missing arguments 2050 NumArgsToCheck = NumArgsInProto; 2051 Call->setNumArgs(Context, NumArgsInProto); 2052 } 2053 2054 // If too many are passed and not variadic, error on the extras and drop 2055 // them. 2056 if (NumArgs > NumArgsInProto) { 2057 if (!Proto->isVariadic()) { 2058 Diag(Args[NumArgsInProto]->getLocStart(), 2059 diag::err_typecheck_call_too_many_args) 2060 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange() 2061 << SourceRange(Args[NumArgsInProto]->getLocStart(), 2062 Args[NumArgs-1]->getLocEnd()); 2063 // This deletes the extra arguments. 2064 Call->setNumArgs(Context, NumArgsInProto); 2065 Invalid = true; 2066 } 2067 NumArgsToCheck = NumArgsInProto; 2068 } 2069 2070 // Continue to check argument types (even if we have too few/many args). 2071 for (unsigned i = 0; i != NumArgsToCheck; i++) { 2072 QualType ProtoArgType = Proto->getArgType(i); 2073 2074 Expr *Arg; 2075 if (i < NumArgs) { 2076 Arg = Args[i]; 2077 2078 // Pass the argument. 2079 if (PerformCopyInitialization(Arg, ProtoArgType, "passing")) 2080 return true; 2081 } else 2082 // We already type-checked the argument, so we know it works. 2083 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i)); 2084 QualType ArgType = Arg->getType(); 2085 2086 Call->setArg(i, Arg); 2087 } 2088 2089 // If this is a variadic call, handle args passed through "...". 2090 if (Proto->isVariadic()) { 2091 VariadicCallType CallType = VariadicFunction; 2092 if (Fn->getType()->isBlockPointerType()) 2093 CallType = VariadicBlock; // Block 2094 else if (isa<MemberExpr>(Fn)) 2095 CallType = VariadicMethod; 2096 2097 // Promote the arguments (C99 6.5.2.2p7). 2098 for (unsigned i = NumArgsInProto; i != NumArgs; i++) { 2099 Expr *Arg = Args[i]; 2100 DefaultVariadicArgumentPromotion(Arg, CallType); 2101 Call->setArg(i, Arg); 2102 } 2103 } 2104 2105 return Invalid; 2106} 2107 2108/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 2109/// This provides the location of the left/right parens and a list of comma 2110/// locations. 2111Action::OwningExprResult 2112Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc, 2113 MultiExprArg args, 2114 SourceLocation *CommaLocs, SourceLocation RParenLoc) { 2115 unsigned NumArgs = args.size(); 2116 Expr *Fn = static_cast<Expr *>(fn.release()); 2117 Expr **Args = reinterpret_cast<Expr**>(args.release()); 2118 assert(Fn && "no function call expression"); 2119 FunctionDecl *FDecl = NULL; 2120 DeclarationName UnqualifiedName; 2121 2122 if (getLangOptions().CPlusPlus) { 2123 // Determine whether this is a dependent call inside a C++ template, 2124 // in which case we won't do any semantic analysis now. 2125 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn. 2126 bool Dependent = false; 2127 if (Fn->isTypeDependent()) 2128 Dependent = true; 2129 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs)) 2130 Dependent = true; 2131 2132 if (Dependent) 2133 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs, 2134 Context.DependentTy, RParenLoc)); 2135 2136 // Determine whether this is a call to an object (C++ [over.call.object]). 2137 if (Fn->getType()->isRecordType()) 2138 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs, 2139 CommaLocs, RParenLoc)); 2140 2141 // Determine whether this is a call to a member function. 2142 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) 2143 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) || 2144 isa<CXXMethodDecl>(MemExpr->getMemberDecl())) 2145 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs, 2146 CommaLocs, RParenLoc)); 2147 } 2148 2149 // If we're directly calling a function, get the appropriate declaration. 2150 DeclRefExpr *DRExpr = NULL; 2151 Expr *FnExpr = Fn; 2152 bool ADL = true; 2153 while (true) { 2154 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr)) 2155 FnExpr = IcExpr->getSubExpr(); 2156 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) { 2157 // Parentheses around a function disable ADL 2158 // (C++0x [basic.lookup.argdep]p1). 2159 ADL = false; 2160 FnExpr = PExpr->getSubExpr(); 2161 } else if (isa<UnaryOperator>(FnExpr) && 2162 cast<UnaryOperator>(FnExpr)->getOpcode() 2163 == UnaryOperator::AddrOf) { 2164 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr(); 2165 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) { 2166 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1). 2167 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr); 2168 break; 2169 } else if (UnresolvedFunctionNameExpr *DepName 2170 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) { 2171 UnqualifiedName = DepName->getName(); 2172 break; 2173 } else { 2174 // Any kind of name that does not refer to a declaration (or 2175 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3). 2176 ADL = false; 2177 break; 2178 } 2179 } 2180 2181 OverloadedFunctionDecl *Ovl = 0; 2182 if (DRExpr) { 2183 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()); 2184 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl()); 2185 } 2186 2187 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) { 2188 // We don't perform ADL for implicit declarations of builtins. 2189 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit()) 2190 ADL = false; 2191 2192 // We don't perform ADL in C. 2193 if (!getLangOptions().CPlusPlus) 2194 ADL = false; 2195 2196 if (Ovl || ADL) { 2197 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0, 2198 UnqualifiedName, LParenLoc, Args, 2199 NumArgs, CommaLocs, RParenLoc, ADL); 2200 if (!FDecl) 2201 return ExprError(); 2202 2203 // Update Fn to refer to the actual function selected. 2204 Expr *NewFn = 0; 2205 if (QualifiedDeclRefExpr *QDRExpr 2206 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr)) 2207 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(), 2208 QDRExpr->getLocation(), 2209 false, false, 2210 QDRExpr->getSourceRange().getBegin()); 2211 else 2212 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(), 2213 Fn->getSourceRange().getBegin()); 2214 Fn->Destroy(Context); 2215 Fn = NewFn; 2216 } 2217 } 2218 2219 // Promote the function operand. 2220 UsualUnaryConversions(Fn); 2221 2222 // Make the call expr early, before semantic checks. This guarantees cleanup 2223 // of arguments and function on error. 2224 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn, 2225 Args, NumArgs, 2226 Context.BoolTy, 2227 RParenLoc)); 2228 2229 const FunctionType *FuncT; 2230 if (!Fn->getType()->isBlockPointerType()) { 2231 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 2232 // have type pointer to function". 2233 const PointerType *PT = Fn->getType()->getAsPointerType(); 2234 if (PT == 0) 2235 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 2236 << Fn->getType() << Fn->getSourceRange()); 2237 FuncT = PT->getPointeeType()->getAsFunctionType(); 2238 } else { // This is a block call. 2239 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()-> 2240 getAsFunctionType(); 2241 } 2242 if (FuncT == 0) 2243 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 2244 << Fn->getType() << Fn->getSourceRange()); 2245 2246 // We know the result type of the call, set it. 2247 TheCall->setType(FuncT->getResultType().getNonReferenceType()); 2248 2249 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) { 2250 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs, 2251 RParenLoc)) 2252 return ExprError(); 2253 } else { 2254 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 2255 2256 // Promote the arguments (C99 6.5.2.2p6). 2257 for (unsigned i = 0; i != NumArgs; i++) { 2258 Expr *Arg = Args[i]; 2259 DefaultArgumentPromotion(Arg); 2260 TheCall->setArg(i, Arg); 2261 } 2262 } 2263 2264 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 2265 if (!Method->isStatic()) 2266 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 2267 << Fn->getSourceRange()); 2268 2269 // Do special checking on direct calls to functions. 2270 if (FDecl) 2271 return CheckFunctionCall(FDecl, TheCall.take()); 2272 2273 return Owned(TheCall.take()); 2274} 2275 2276Action::OwningExprResult 2277Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty, 2278 SourceLocation RParenLoc, ExprArg InitExpr) { 2279 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type"); 2280 QualType literalType = QualType::getFromOpaquePtr(Ty); 2281 // FIXME: put back this assert when initializers are worked out. 2282 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 2283 Expr *literalExpr = static_cast<Expr*>(InitExpr.get()); 2284 2285 if (literalType->isArrayType()) { 2286 if (literalType->isVariableArrayType()) 2287 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 2288 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())); 2289 } else if (RequireCompleteType(LParenLoc, literalType, 2290 diag::err_typecheck_decl_incomplete_type, 2291 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()))) 2292 return ExprError(); 2293 2294 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc, 2295 DeclarationName(), /*FIXME:DirectInit=*/false)) 2296 return ExprError(); 2297 2298 bool isFileScope = getCurFunctionOrMethodDecl() == 0; 2299 if (isFileScope) { // 6.5.2.5p3 2300 if (CheckForConstantInitializer(literalExpr, literalType)) 2301 return ExprError(); 2302 } 2303 InitExpr.release(); 2304 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType, 2305 literalExpr, isFileScope)); 2306} 2307 2308Action::OwningExprResult 2309Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist, 2310 InitListDesignations &Designators, 2311 SourceLocation RBraceLoc) { 2312 unsigned NumInit = initlist.size(); 2313 Expr **InitList = reinterpret_cast<Expr**>(initlist.release()); 2314 2315 // Semantic analysis for initializers is done by ActOnDeclarator() and 2316 // CheckInitializer() - it requires knowledge of the object being intialized. 2317 2318 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit, 2319 RBraceLoc); 2320 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 2321 return Owned(E); 2322} 2323 2324/// CheckCastTypes - Check type constraints for casting between types. 2325bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) { 2326 UsualUnaryConversions(castExpr); 2327 2328 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression 2329 // type needs to be scalar. 2330 if (castType->isVoidType()) { 2331 // Cast to void allows any expr type. 2332 } else if (castType->isDependentType() || castExpr->isTypeDependent()) { 2333 // We can't check any more until template instantiation time. 2334 } else if (!castType->isScalarType() && !castType->isVectorType()) { 2335 if (Context.getCanonicalType(castType).getUnqualifiedType() == 2336 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) && 2337 (castType->isStructureType() || castType->isUnionType())) { 2338 // GCC struct/union extension: allow cast to self. 2339 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar) 2340 << castType << castExpr->getSourceRange(); 2341 } else if (castType->isUnionType()) { 2342 // GCC cast to union extension 2343 RecordDecl *RD = castType->getAsRecordType()->getDecl(); 2344 RecordDecl::field_iterator Field, FieldEnd; 2345 for (Field = RD->field_begin(), FieldEnd = RD->field_end(); 2346 Field != FieldEnd; ++Field) { 2347 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() == 2348 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) { 2349 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union) 2350 << castExpr->getSourceRange(); 2351 break; 2352 } 2353 } 2354 if (Field == FieldEnd) 2355 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type) 2356 << castExpr->getType() << castExpr->getSourceRange(); 2357 } else { 2358 // Reject any other conversions to non-scalar types. 2359 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar) 2360 << castType << castExpr->getSourceRange(); 2361 } 2362 } else if (!castExpr->getType()->isScalarType() && 2363 !castExpr->getType()->isVectorType()) { 2364 return Diag(castExpr->getLocStart(), 2365 diag::err_typecheck_expect_scalar_operand) 2366 << castExpr->getType() << castExpr->getSourceRange(); 2367 } else if (castExpr->getType()->isVectorType()) { 2368 if (CheckVectorCast(TyR, castExpr->getType(), castType)) 2369 return true; 2370 } else if (castType->isVectorType()) { 2371 if (CheckVectorCast(TyR, castType, castExpr->getType())) 2372 return true; 2373 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) { 2374 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR; 2375 } 2376 return false; 2377} 2378 2379bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) { 2380 assert(VectorTy->isVectorType() && "Not a vector type!"); 2381 2382 if (Ty->isVectorType() || Ty->isIntegerType()) { 2383 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty)) 2384 return Diag(R.getBegin(), 2385 Ty->isVectorType() ? 2386 diag::err_invalid_conversion_between_vectors : 2387 diag::err_invalid_conversion_between_vector_and_integer) 2388 << VectorTy << Ty << R; 2389 } else 2390 return Diag(R.getBegin(), 2391 diag::err_invalid_conversion_between_vector_and_scalar) 2392 << VectorTy << Ty << R; 2393 2394 return false; 2395} 2396 2397Action::OwningExprResult 2398Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty, 2399 SourceLocation RParenLoc, ExprArg Op) { 2400 assert((Ty != 0) && (Op.get() != 0) && 2401 "ActOnCastExpr(): missing type or expr"); 2402 2403 Expr *castExpr = static_cast<Expr*>(Op.release()); 2404 QualType castType = QualType::getFromOpaquePtr(Ty); 2405 2406 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr)) 2407 return ExprError(); 2408 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType, 2409 LParenLoc, RParenLoc)); 2410} 2411 2412/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension. 2413/// In that case, lhs = cond. 2414/// C99 6.5.15 2415QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS, 2416 SourceLocation QuestionLoc) { 2417 UsualUnaryConversions(Cond); 2418 UsualUnaryConversions(LHS); 2419 UsualUnaryConversions(RHS); 2420 QualType CondTy = Cond->getType(); 2421 QualType LHSTy = LHS->getType(); 2422 QualType RHSTy = RHS->getType(); 2423 2424 // first, check the condition. 2425 if (!Cond->isTypeDependent()) { 2426 if (!CondTy->isScalarType()) { // C99 6.5.15p2 2427 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) 2428 << CondTy; 2429 return QualType(); 2430 } 2431 } 2432 2433 // Now check the two expressions. 2434 if ((LHS && LHS->isTypeDependent()) || (RHS && RHS->isTypeDependent())) 2435 return Context.DependentTy; 2436 2437 // If both operands have arithmetic type, do the usual arithmetic conversions 2438 // to find a common type: C99 6.5.15p3,5. 2439 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 2440 UsualArithmeticConversions(LHS, RHS); 2441 return LHS->getType(); 2442 } 2443 2444 // If both operands are the same structure or union type, the result is that 2445 // type. 2446 if (const RecordType *LHSRT = LHSTy->getAsRecordType()) { // C99 6.5.15p3 2447 if (const RecordType *RHSRT = RHSTy->getAsRecordType()) 2448 if (LHSRT->getDecl() == RHSRT->getDecl()) 2449 // "If both the operands have structure or union type, the result has 2450 // that type." This implies that CV qualifiers are dropped. 2451 return LHSTy.getUnqualifiedType(); 2452 } 2453 2454 // C99 6.5.15p5: "If both operands have void type, the result has void type." 2455 // The following || allows only one side to be void (a GCC-ism). 2456 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 2457 if (!LHSTy->isVoidType()) 2458 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void) 2459 << RHS->getSourceRange(); 2460 if (!RHSTy->isVoidType()) 2461 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void) 2462 << LHS->getSourceRange(); 2463 ImpCastExprToType(LHS, Context.VoidTy); 2464 ImpCastExprToType(RHS, Context.VoidTy); 2465 return Context.VoidTy; 2466 } 2467 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 2468 // the type of the other operand." 2469 if ((LHSTy->isPointerType() || LHSTy->isBlockPointerType() || 2470 Context.isObjCObjectPointerType(LHSTy)) && 2471 RHS->isNullPointerConstant(Context)) { 2472 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer. 2473 return LHSTy; 2474 } 2475 if ((RHSTy->isPointerType() || RHSTy->isBlockPointerType() || 2476 Context.isObjCObjectPointerType(RHSTy)) && 2477 LHS->isNullPointerConstant(Context)) { 2478 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer. 2479 return RHSTy; 2480 } 2481 2482 // Handle the case where both operands are pointers before we handle null 2483 // pointer constants in case both operands are null pointer constants. 2484 if (const PointerType *LHSPT = LHSTy->getAsPointerType()) { // C99 6.5.15p3,6 2485 if (const PointerType *RHSPT = RHSTy->getAsPointerType()) { 2486 // get the "pointed to" types 2487 QualType lhptee = LHSPT->getPointeeType(); 2488 QualType rhptee = RHSPT->getPointeeType(); 2489 2490 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 2491 if (lhptee->isVoidType() && 2492 rhptee->isIncompleteOrObjectType()) { 2493 // Figure out necessary qualifiers (C99 6.5.15p6) 2494 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers()); 2495 QualType destType = Context.getPointerType(destPointee); 2496 ImpCastExprToType(LHS, destType); // add qualifiers if necessary 2497 ImpCastExprToType(RHS, destType); // promote to void* 2498 return destType; 2499 } 2500 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 2501 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers()); 2502 QualType destType = Context.getPointerType(destPointee); 2503 ImpCastExprToType(LHS, destType); // add qualifiers if necessary 2504 ImpCastExprToType(RHS, destType); // promote to void* 2505 return destType; 2506 } 2507 2508 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 2509 // Two identical pointer types are always compatible. 2510 return LHSTy; 2511 } 2512 2513 QualType compositeType = LHSTy; 2514 2515 // If either type is an Objective-C object type then check 2516 // compatibility according to Objective-C. 2517 if (Context.isObjCObjectPointerType(LHSTy) || 2518 Context.isObjCObjectPointerType(RHSTy)) { 2519 // If both operands are interfaces and either operand can be 2520 // assigned to the other, use that type as the composite 2521 // type. This allows 2522 // xxx ? (A*) a : (B*) b 2523 // where B is a subclass of A. 2524 // 2525 // Additionally, as for assignment, if either type is 'id' 2526 // allow silent coercion. Finally, if the types are 2527 // incompatible then make sure to use 'id' as the composite 2528 // type so the result is acceptable for sending messages to. 2529 2530 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 2531 // It could return the composite type. 2532 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType(); 2533 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType(); 2534 if (LHSIface && RHSIface && 2535 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) { 2536 compositeType = LHSTy; 2537 } else if (LHSIface && RHSIface && 2538 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) { 2539 compositeType = RHSTy; 2540 } else if (Context.isObjCIdStructType(lhptee) || 2541 Context.isObjCIdStructType(rhptee)) { 2542 compositeType = Context.getObjCIdType(); 2543 } else { 2544 Diag(QuestionLoc, diag::ext_typecheck_comparison_of_distinct_pointers) 2545 << LHSTy << RHSTy 2546 << LHS->getSourceRange() << RHS->getSourceRange(); 2547 QualType incompatTy = Context.getObjCIdType(); 2548 ImpCastExprToType(LHS, incompatTy); 2549 ImpCastExprToType(RHS, incompatTy); 2550 return incompatTy; 2551 } 2552 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(), 2553 rhptee.getUnqualifiedType())) { 2554 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers) 2555 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 2556 // In this situation, we assume void* type. No especially good 2557 // reason, but this is what gcc does, and we do have to pick 2558 // to get a consistent AST. 2559 QualType incompatTy = Context.getPointerType(Context.VoidTy); 2560 ImpCastExprToType(LHS, incompatTy); 2561 ImpCastExprToType(RHS, incompatTy); 2562 return incompatTy; 2563 } 2564 // The pointer types are compatible. 2565 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to 2566 // differently qualified versions of compatible types, the result type is 2567 // a pointer to an appropriately qualified version of the *composite* 2568 // type. 2569 // FIXME: Need to calculate the composite type. 2570 // FIXME: Need to add qualifiers 2571 ImpCastExprToType(LHS, compositeType); 2572 ImpCastExprToType(RHS, compositeType); 2573 return compositeType; 2574 } 2575 } 2576 2577 // Selection between block pointer types is ok as long as they are the same. 2578 if (LHSTy->isBlockPointerType() && RHSTy->isBlockPointerType() && 2579 Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) 2580 return LHSTy; 2581 2582 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type 2583 // evaluates to "struct objc_object *" (and is handled above when comparing 2584 // id with statically typed objects). 2585 if (LHSTy->isObjCQualifiedIdType() || RHSTy->isObjCQualifiedIdType()) { 2586 // GCC allows qualified id and any Objective-C type to devolve to 2587 // id. Currently localizing to here until clear this should be 2588 // part of ObjCQualifiedIdTypesAreCompatible. 2589 if (ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true) || 2590 (LHSTy->isObjCQualifiedIdType() && 2591 Context.isObjCObjectPointerType(RHSTy)) || 2592 (RHSTy->isObjCQualifiedIdType() && 2593 Context.isObjCObjectPointerType(LHSTy))) { 2594 // FIXME: This is not the correct composite type. This only 2595 // happens to work because id can more or less be used anywhere, 2596 // however this may change the type of method sends. 2597 // FIXME: gcc adds some type-checking of the arguments and emits 2598 // (confusing) incompatible comparison warnings in some 2599 // cases. Investigate. 2600 QualType compositeType = Context.getObjCIdType(); 2601 ImpCastExprToType(LHS, compositeType); 2602 ImpCastExprToType(RHS, compositeType); 2603 return compositeType; 2604 } 2605 } 2606 2607 // Otherwise, the operands are not compatible. 2608 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 2609 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 2610 return QualType(); 2611} 2612 2613/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 2614/// in the case of a the GNU conditional expr extension. 2615Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 2616 SourceLocation ColonLoc, 2617 ExprArg Cond, ExprArg LHS, 2618 ExprArg RHS) { 2619 Expr *CondExpr = (Expr *) Cond.get(); 2620 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get(); 2621 2622 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 2623 // was the condition. 2624 bool isLHSNull = LHSExpr == 0; 2625 if (isLHSNull) 2626 LHSExpr = CondExpr; 2627 2628 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, 2629 RHSExpr, QuestionLoc); 2630 if (result.isNull()) 2631 return ExprError(); 2632 2633 Cond.release(); 2634 LHS.release(); 2635 RHS.release(); 2636 return Owned(new (Context) ConditionalOperator(CondExpr, 2637 isLHSNull ? 0 : LHSExpr, 2638 RHSExpr, result)); 2639} 2640 2641 2642// CheckPointerTypesForAssignment - This is a very tricky routine (despite 2643// being closely modeled after the C99 spec:-). The odd characteristic of this 2644// routine is it effectively iqnores the qualifiers on the top level pointee. 2645// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 2646// FIXME: add a couple examples in this comment. 2647Sema::AssignConvertType 2648Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) { 2649 QualType lhptee, rhptee; 2650 2651 // get the "pointed to" type (ignoring qualifiers at the top level) 2652 lhptee = lhsType->getAsPointerType()->getPointeeType(); 2653 rhptee = rhsType->getAsPointerType()->getPointeeType(); 2654 2655 // make sure we operate on the canonical type 2656 lhptee = Context.getCanonicalType(lhptee); 2657 rhptee = Context.getCanonicalType(rhptee); 2658 2659 AssignConvertType ConvTy = Compatible; 2660 2661 // C99 6.5.16.1p1: This following citation is common to constraints 2662 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 2663 // qualifiers of the type *pointed to* by the right; 2664 // FIXME: Handle ExtQualType 2665 if (!lhptee.isAtLeastAsQualifiedAs(rhptee)) 2666 ConvTy = CompatiblePointerDiscardsQualifiers; 2667 2668 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 2669 // incomplete type and the other is a pointer to a qualified or unqualified 2670 // version of void... 2671 if (lhptee->isVoidType()) { 2672 if (rhptee->isIncompleteOrObjectType()) 2673 return ConvTy; 2674 2675 // As an extension, we allow cast to/from void* to function pointer. 2676 assert(rhptee->isFunctionType()); 2677 return FunctionVoidPointer; 2678 } 2679 2680 if (rhptee->isVoidType()) { 2681 if (lhptee->isIncompleteOrObjectType()) 2682 return ConvTy; 2683 2684 // As an extension, we allow cast to/from void* to function pointer. 2685 assert(lhptee->isFunctionType()); 2686 return FunctionVoidPointer; 2687 } 2688 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 2689 // unqualified versions of compatible types, ... 2690 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(), 2691 rhptee.getUnqualifiedType())) 2692 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers 2693 return ConvTy; 2694} 2695 2696/// CheckBlockPointerTypesForAssignment - This routine determines whether two 2697/// block pointer types are compatible or whether a block and normal pointer 2698/// are compatible. It is more restrict than comparing two function pointer 2699// types. 2700Sema::AssignConvertType 2701Sema::CheckBlockPointerTypesForAssignment(QualType lhsType, 2702 QualType rhsType) { 2703 QualType lhptee, rhptee; 2704 2705 // get the "pointed to" type (ignoring qualifiers at the top level) 2706 lhptee = lhsType->getAsBlockPointerType()->getPointeeType(); 2707 rhptee = rhsType->getAsBlockPointerType()->getPointeeType(); 2708 2709 // make sure we operate on the canonical type 2710 lhptee = Context.getCanonicalType(lhptee); 2711 rhptee = Context.getCanonicalType(rhptee); 2712 2713 AssignConvertType ConvTy = Compatible; 2714 2715 // For blocks we enforce that qualifiers are identical. 2716 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers()) 2717 ConvTy = CompatiblePointerDiscardsQualifiers; 2718 2719 if (!Context.typesAreBlockCompatible(lhptee, rhptee)) 2720 return IncompatibleBlockPointer; 2721 return ConvTy; 2722} 2723 2724/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 2725/// has code to accommodate several GCC extensions when type checking 2726/// pointers. Here are some objectionable examples that GCC considers warnings: 2727/// 2728/// int a, *pint; 2729/// short *pshort; 2730/// struct foo *pfoo; 2731/// 2732/// pint = pshort; // warning: assignment from incompatible pointer type 2733/// a = pint; // warning: assignment makes integer from pointer without a cast 2734/// pint = a; // warning: assignment makes pointer from integer without a cast 2735/// pint = pfoo; // warning: assignment from incompatible pointer type 2736/// 2737/// As a result, the code for dealing with pointers is more complex than the 2738/// C99 spec dictates. 2739/// 2740Sema::AssignConvertType 2741Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) { 2742 // Get canonical types. We're not formatting these types, just comparing 2743 // them. 2744 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType(); 2745 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType(); 2746 2747 if (lhsType == rhsType) 2748 return Compatible; // Common case: fast path an exact match. 2749 2750 // If the left-hand side is a reference type, then we are in a 2751 // (rare!) case where we've allowed the use of references in C, 2752 // e.g., as a parameter type in a built-in function. In this case, 2753 // just make sure that the type referenced is compatible with the 2754 // right-hand side type. The caller is responsible for adjusting 2755 // lhsType so that the resulting expression does not have reference 2756 // type. 2757 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) { 2758 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) 2759 return Compatible; 2760 return Incompatible; 2761 } 2762 2763 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) { 2764 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false)) 2765 return Compatible; 2766 // Relax integer conversions like we do for pointers below. 2767 if (rhsType->isIntegerType()) 2768 return IntToPointer; 2769 if (lhsType->isIntegerType()) 2770 return PointerToInt; 2771 return IncompatibleObjCQualifiedId; 2772 } 2773 2774 if (lhsType->isVectorType() || rhsType->isVectorType()) { 2775 // For ExtVector, allow vector splats; float -> <n x float> 2776 if (const ExtVectorType *LV = lhsType->getAsExtVectorType()) 2777 if (LV->getElementType() == rhsType) 2778 return Compatible; 2779 2780 // If we are allowing lax vector conversions, and LHS and RHS are both 2781 // vectors, the total size only needs to be the same. This is a bitcast; 2782 // no bits are changed but the result type is different. 2783 if (getLangOptions().LaxVectorConversions && 2784 lhsType->isVectorType() && rhsType->isVectorType()) { 2785 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType)) 2786 return IncompatibleVectors; 2787 } 2788 return Incompatible; 2789 } 2790 2791 if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) 2792 return Compatible; 2793 2794 if (isa<PointerType>(lhsType)) { 2795 if (rhsType->isIntegerType()) 2796 return IntToPointer; 2797 2798 if (isa<PointerType>(rhsType)) 2799 return CheckPointerTypesForAssignment(lhsType, rhsType); 2800 2801 if (rhsType->getAsBlockPointerType()) { 2802 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType()) 2803 return Compatible; 2804 2805 // Treat block pointers as objects. 2806 if (getLangOptions().ObjC1 && 2807 lhsType == Context.getCanonicalType(Context.getObjCIdType())) 2808 return Compatible; 2809 } 2810 return Incompatible; 2811 } 2812 2813 if (isa<BlockPointerType>(lhsType)) { 2814 if (rhsType->isIntegerType()) 2815 return IntToBlockPointer; 2816 2817 // Treat block pointers as objects. 2818 if (getLangOptions().ObjC1 && 2819 rhsType == Context.getCanonicalType(Context.getObjCIdType())) 2820 return Compatible; 2821 2822 if (rhsType->isBlockPointerType()) 2823 return CheckBlockPointerTypesForAssignment(lhsType, rhsType); 2824 2825 if (const PointerType *RHSPT = rhsType->getAsPointerType()) { 2826 if (RHSPT->getPointeeType()->isVoidType()) 2827 return Compatible; 2828 } 2829 return Incompatible; 2830 } 2831 2832 if (isa<PointerType>(rhsType)) { 2833 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer. 2834 if (lhsType == Context.BoolTy) 2835 return Compatible; 2836 2837 if (lhsType->isIntegerType()) 2838 return PointerToInt; 2839 2840 if (isa<PointerType>(lhsType)) 2841 return CheckPointerTypesForAssignment(lhsType, rhsType); 2842 2843 if (isa<BlockPointerType>(lhsType) && 2844 rhsType->getAsPointerType()->getPointeeType()->isVoidType()) 2845 return Compatible; 2846 return Incompatible; 2847 } 2848 2849 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) { 2850 if (Context.typesAreCompatible(lhsType, rhsType)) 2851 return Compatible; 2852 } 2853 return Incompatible; 2854} 2855 2856Sema::AssignConvertType 2857Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) { 2858 if (getLangOptions().CPlusPlus) { 2859 if (!lhsType->isRecordType()) { 2860 // C++ 5.17p3: If the left operand is not of class type, the 2861 // expression is implicitly converted (C++ 4) to the 2862 // cv-unqualified type of the left operand. 2863 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(), 2864 "assigning")) 2865 return Incompatible; 2866 else 2867 return Compatible; 2868 } 2869 2870 // FIXME: Currently, we fall through and treat C++ classes like C 2871 // structures. 2872 } 2873 2874 // C99 6.5.16.1p1: the left operand is a pointer and the right is 2875 // a null pointer constant. 2876 if ((lhsType->isPointerType() || 2877 lhsType->isObjCQualifiedIdType() || 2878 lhsType->isBlockPointerType()) 2879 && rExpr->isNullPointerConstant(Context)) { 2880 ImpCastExprToType(rExpr, lhsType); 2881 return Compatible; 2882 } 2883 2884 // This check seems unnatural, however it is necessary to ensure the proper 2885 // conversion of functions/arrays. If the conversion were done for all 2886 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary 2887 // expressions that surpress this implicit conversion (&, sizeof). 2888 // 2889 // Suppress this for references: C++ 8.5.3p5. 2890 if (!lhsType->isReferenceType()) 2891 DefaultFunctionArrayConversion(rExpr); 2892 2893 Sema::AssignConvertType result = 2894 CheckAssignmentConstraints(lhsType, rExpr->getType()); 2895 2896 // C99 6.5.16.1p2: The value of the right operand is converted to the 2897 // type of the assignment expression. 2898 // CheckAssignmentConstraints allows the left-hand side to be a reference, 2899 // so that we can use references in built-in functions even in C. 2900 // The getNonReferenceType() call makes sure that the resulting expression 2901 // does not have reference type. 2902 if (rExpr->getType() != lhsType) 2903 ImpCastExprToType(rExpr, lhsType.getNonReferenceType()); 2904 return result; 2905} 2906 2907Sema::AssignConvertType 2908Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) { 2909 return CheckAssignmentConstraints(lhsType, rhsType); 2910} 2911 2912QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) { 2913 Diag(Loc, diag::err_typecheck_invalid_operands) 2914 << lex->getType() << rex->getType() 2915 << lex->getSourceRange() << rex->getSourceRange(); 2916 return QualType(); 2917} 2918 2919inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, 2920 Expr *&rex) { 2921 // For conversion purposes, we ignore any qualifiers. 2922 // For example, "const float" and "float" are equivalent. 2923 QualType lhsType = 2924 Context.getCanonicalType(lex->getType()).getUnqualifiedType(); 2925 QualType rhsType = 2926 Context.getCanonicalType(rex->getType()).getUnqualifiedType(); 2927 2928 // If the vector types are identical, return. 2929 if (lhsType == rhsType) 2930 return lhsType; 2931 2932 // Handle the case of a vector & extvector type of the same size and element 2933 // type. It would be nice if we only had one vector type someday. 2934 if (getLangOptions().LaxVectorConversions) { 2935 // FIXME: Should we warn here? 2936 if (const VectorType *LV = lhsType->getAsVectorType()) { 2937 if (const VectorType *RV = rhsType->getAsVectorType()) 2938 if (LV->getElementType() == RV->getElementType() && 2939 LV->getNumElements() == RV->getNumElements()) { 2940 return lhsType->isExtVectorType() ? lhsType : rhsType; 2941 } 2942 } 2943 } 2944 2945 // If the lhs is an extended vector and the rhs is a scalar of the same type 2946 // or a literal, promote the rhs to the vector type. 2947 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) { 2948 QualType eltType = V->getElementType(); 2949 2950 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) || 2951 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) || 2952 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) { 2953 ImpCastExprToType(rex, lhsType); 2954 return lhsType; 2955 } 2956 } 2957 2958 // If the rhs is an extended vector and the lhs is a scalar of the same type, 2959 // promote the lhs to the vector type. 2960 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) { 2961 QualType eltType = V->getElementType(); 2962 2963 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) || 2964 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) || 2965 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) { 2966 ImpCastExprToType(lex, rhsType); 2967 return rhsType; 2968 } 2969 } 2970 2971 // You cannot convert between vector values of different size. 2972 Diag(Loc, diag::err_typecheck_vector_not_convertable) 2973 << lex->getType() << rex->getType() 2974 << lex->getSourceRange() << rex->getSourceRange(); 2975 return QualType(); 2976} 2977 2978inline QualType Sema::CheckMultiplyDivideOperands( 2979 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) 2980{ 2981 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 2982 return CheckVectorOperands(Loc, lex, rex); 2983 2984 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 2985 2986 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 2987 return compType; 2988 return InvalidOperands(Loc, lex, rex); 2989} 2990 2991inline QualType Sema::CheckRemainderOperands( 2992 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) 2993{ 2994 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) { 2995 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType()) 2996 return CheckVectorOperands(Loc, lex, rex); 2997 return InvalidOperands(Loc, lex, rex); 2998 } 2999 3000 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 3001 3002 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType()) 3003 return compType; 3004 return InvalidOperands(Loc, lex, rex); 3005} 3006 3007inline QualType Sema::CheckAdditionOperands( // C99 6.5.6 3008 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) 3009{ 3010 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 3011 return CheckVectorOperands(Loc, lex, rex); 3012 3013 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 3014 3015 // handle the common case first (both operands are arithmetic). 3016 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 3017 return compType; 3018 3019 // Put any potential pointer into PExp 3020 Expr* PExp = lex, *IExp = rex; 3021 if (IExp->getType()->isPointerType()) 3022 std::swap(PExp, IExp); 3023 3024 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) { 3025 if (IExp->getType()->isIntegerType()) { 3026 // Check for arithmetic on pointers to incomplete types 3027 if (!PTy->getPointeeType()->isObjectType()) { 3028 if (PTy->getPointeeType()->isVoidType()) { 3029 if (getLangOptions().CPlusPlus) { 3030 Diag(Loc, diag::err_typecheck_pointer_arith_void_type) 3031 << lex->getSourceRange() << rex->getSourceRange(); 3032 return QualType(); 3033 } 3034 3035 // GNU extension: arithmetic on pointer to void 3036 Diag(Loc, diag::ext_gnu_void_ptr) 3037 << lex->getSourceRange() << rex->getSourceRange(); 3038 } else if (PTy->getPointeeType()->isFunctionType()) { 3039 if (getLangOptions().CPlusPlus) { 3040 Diag(Loc, diag::err_typecheck_pointer_arith_function_type) 3041 << lex->getType() << lex->getSourceRange(); 3042 return QualType(); 3043 } 3044 3045 // GNU extension: arithmetic on pointer to function 3046 Diag(Loc, diag::ext_gnu_ptr_func_arith) 3047 << lex->getType() << lex->getSourceRange(); 3048 } else { 3049 RequireCompleteType(Loc, PTy->getPointeeType(), 3050 diag::err_typecheck_arithmetic_incomplete_type, 3051 lex->getSourceRange(), SourceRange(), 3052 lex->getType()); 3053 return QualType(); 3054 } 3055 } 3056 return PExp->getType(); 3057 } 3058 } 3059 3060 return InvalidOperands(Loc, lex, rex); 3061} 3062 3063// C99 6.5.6 3064QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex, 3065 SourceLocation Loc, bool isCompAssign) { 3066 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 3067 return CheckVectorOperands(Loc, lex, rex); 3068 3069 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 3070 3071 // Enforce type constraints: C99 6.5.6p3. 3072 3073 // Handle the common case first (both operands are arithmetic). 3074 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 3075 return compType; 3076 3077 // Either ptr - int or ptr - ptr. 3078 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) { 3079 QualType lpointee = LHSPTy->getPointeeType(); 3080 3081 // The LHS must be an object type, not incomplete, function, etc. 3082 if (!lpointee->isObjectType()) { 3083 // Handle the GNU void* extension. 3084 if (lpointee->isVoidType()) { 3085 Diag(Loc, diag::ext_gnu_void_ptr) 3086 << lex->getSourceRange() << rex->getSourceRange(); 3087 } else if (lpointee->isFunctionType()) { 3088 if (getLangOptions().CPlusPlus) { 3089 Diag(Loc, diag::err_typecheck_pointer_arith_function_type) 3090 << lex->getType() << lex->getSourceRange(); 3091 return QualType(); 3092 } 3093 3094 // GNU extension: arithmetic on pointer to function 3095 Diag(Loc, diag::ext_gnu_ptr_func_arith) 3096 << lex->getType() << lex->getSourceRange(); 3097 } else { 3098 Diag(Loc, diag::err_typecheck_sub_ptr_object) 3099 << lex->getType() << lex->getSourceRange(); 3100 return QualType(); 3101 } 3102 } 3103 3104 // The result type of a pointer-int computation is the pointer type. 3105 if (rex->getType()->isIntegerType()) 3106 return lex->getType(); 3107 3108 // Handle pointer-pointer subtractions. 3109 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) { 3110 QualType rpointee = RHSPTy->getPointeeType(); 3111 3112 // RHS must be an object type, unless void (GNU). 3113 if (!rpointee->isObjectType()) { 3114 // Handle the GNU void* extension. 3115 if (rpointee->isVoidType()) { 3116 if (!lpointee->isVoidType()) 3117 Diag(Loc, diag::ext_gnu_void_ptr) 3118 << lex->getSourceRange() << rex->getSourceRange(); 3119 } else if (rpointee->isFunctionType()) { 3120 if (getLangOptions().CPlusPlus) { 3121 Diag(Loc, diag::err_typecheck_pointer_arith_function_type) 3122 << rex->getType() << rex->getSourceRange(); 3123 return QualType(); 3124 } 3125 3126 // GNU extension: arithmetic on pointer to function 3127 if (!lpointee->isFunctionType()) 3128 Diag(Loc, diag::ext_gnu_ptr_func_arith) 3129 << lex->getType() << lex->getSourceRange(); 3130 } else { 3131 Diag(Loc, diag::err_typecheck_sub_ptr_object) 3132 << rex->getType() << rex->getSourceRange(); 3133 return QualType(); 3134 } 3135 } 3136 3137 // Pointee types must be compatible. 3138 if (!Context.typesAreCompatible( 3139 Context.getCanonicalType(lpointee).getUnqualifiedType(), 3140 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 3141 Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 3142 << lex->getType() << rex->getType() 3143 << lex->getSourceRange() << rex->getSourceRange(); 3144 return QualType(); 3145 } 3146 3147 return Context.getPointerDiffType(); 3148 } 3149 } 3150 3151 return InvalidOperands(Loc, lex, rex); 3152} 3153 3154// C99 6.5.7 3155QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc, 3156 bool isCompAssign) { 3157 // C99 6.5.7p2: Each of the operands shall have integer type. 3158 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType()) 3159 return InvalidOperands(Loc, lex, rex); 3160 3161 // Shifts don't perform usual arithmetic conversions, they just do integer 3162 // promotions on each operand. C99 6.5.7p3 3163 if (!isCompAssign) 3164 UsualUnaryConversions(lex); 3165 UsualUnaryConversions(rex); 3166 3167 // "The type of the result is that of the promoted left operand." 3168 return lex->getType(); 3169} 3170 3171// C99 6.5.8 3172QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc, 3173 bool isRelational) { 3174 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 3175 return CheckVectorCompareOperands(lex, rex, Loc, isRelational); 3176 3177 // C99 6.5.8p3 / C99 6.5.9p4 3178 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 3179 UsualArithmeticConversions(lex, rex); 3180 else { 3181 UsualUnaryConversions(lex); 3182 UsualUnaryConversions(rex); 3183 } 3184 QualType lType = lex->getType(); 3185 QualType rType = rex->getType(); 3186 3187 if (!lType->isFloatingType()) { 3188 // For non-floating point types, check for self-comparisons of the form 3189 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 3190 // often indicate logic errors in the program. 3191 Expr *LHSStripped = lex->IgnoreParens(); 3192 Expr *RHSStripped = rex->IgnoreParens(); 3193 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) 3194 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) 3195 if (DRL->getDecl() == DRR->getDecl()) 3196 Diag(Loc, diag::warn_selfcomparison); 3197 3198 if (isa<CastExpr>(LHSStripped)) 3199 LHSStripped = LHSStripped->IgnoreParenCasts(); 3200 if (isa<CastExpr>(RHSStripped)) 3201 RHSStripped = RHSStripped->IgnoreParenCasts(); 3202 3203 // Warn about comparisons against a string constant (unless the other 3204 // operand is null), the user probably wants strcmp. 3205 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 3206 !RHSStripped->isNullPointerConstant(Context)) 3207 Diag(Loc, diag::warn_stringcompare) << lex->getSourceRange(); 3208 else if ((isa<StringLiteral>(RHSStripped) || 3209 isa<ObjCEncodeExpr>(RHSStripped)) && 3210 !LHSStripped->isNullPointerConstant(Context)) 3211 Diag(Loc, diag::warn_stringcompare) << rex->getSourceRange(); 3212 } 3213 3214 // The result of comparisons is 'bool' in C++, 'int' in C. 3215 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy; 3216 3217 if (isRelational) { 3218 if (lType->isRealType() && rType->isRealType()) 3219 return ResultTy; 3220 } else { 3221 // Check for comparisons of floating point operands using != and ==. 3222 if (lType->isFloatingType()) { 3223 assert(rType->isFloatingType()); 3224 CheckFloatComparison(Loc,lex,rex); 3225 } 3226 3227 if (lType->isArithmeticType() && rType->isArithmeticType()) 3228 return ResultTy; 3229 } 3230 3231 bool LHSIsNull = lex->isNullPointerConstant(Context); 3232 bool RHSIsNull = rex->isNullPointerConstant(Context); 3233 3234 // All of the following pointer related warnings are GCC extensions, except 3235 // when handling null pointer constants. One day, we can consider making them 3236 // errors (when -pedantic-errors is enabled). 3237 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2 3238 QualType LCanPointeeTy = 3239 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType()); 3240 QualType RCanPointeeTy = 3241 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType()); 3242 3243 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2 3244 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() && 3245 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 3246 RCanPointeeTy.getUnqualifiedType()) && 3247 !Context.areComparableObjCPointerTypes(lType, rType)) { 3248 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers) 3249 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 3250 } 3251 ImpCastExprToType(rex, lType); // promote the pointer to pointer 3252 return ResultTy; 3253 } 3254 // Handle block pointer types. 3255 if (lType->isBlockPointerType() && rType->isBlockPointerType()) { 3256 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType(); 3257 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType(); 3258 3259 if (!LHSIsNull && !RHSIsNull && 3260 !Context.typesAreBlockCompatible(lpointee, rpointee)) { 3261 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 3262 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 3263 } 3264 ImpCastExprToType(rex, lType); // promote the pointer to pointer 3265 return ResultTy; 3266 } 3267 // Allow block pointers to be compared with null pointer constants. 3268 if ((lType->isBlockPointerType() && rType->isPointerType()) || 3269 (lType->isPointerType() && rType->isBlockPointerType())) { 3270 if (!LHSIsNull && !RHSIsNull) { 3271 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 3272 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 3273 } 3274 ImpCastExprToType(rex, lType); // promote the pointer to pointer 3275 return ResultTy; 3276 } 3277 3278 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) { 3279 if (lType->isPointerType() || rType->isPointerType()) { 3280 const PointerType *LPT = lType->getAsPointerType(); 3281 const PointerType *RPT = rType->getAsPointerType(); 3282 bool LPtrToVoid = LPT ? 3283 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false; 3284 bool RPtrToVoid = RPT ? 3285 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false; 3286 3287 if (!LPtrToVoid && !RPtrToVoid && 3288 !Context.typesAreCompatible(lType, rType)) { 3289 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers) 3290 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 3291 ImpCastExprToType(rex, lType); 3292 return ResultTy; 3293 } 3294 ImpCastExprToType(rex, lType); 3295 return ResultTy; 3296 } 3297 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) { 3298 ImpCastExprToType(rex, lType); 3299 return ResultTy; 3300 } else { 3301 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) { 3302 Diag(Loc, diag::warn_incompatible_qualified_id_operands) 3303 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 3304 ImpCastExprToType(rex, lType); 3305 return ResultTy; 3306 } 3307 } 3308 } 3309 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) && 3310 rType->isIntegerType()) { 3311 if (!RHSIsNull) 3312 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer) 3313 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 3314 ImpCastExprToType(rex, lType); // promote the integer to pointer 3315 return ResultTy; 3316 } 3317 if (lType->isIntegerType() && 3318 (rType->isPointerType() || rType->isObjCQualifiedIdType())) { 3319 if (!LHSIsNull) 3320 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer) 3321 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 3322 ImpCastExprToType(lex, rType); // promote the integer to pointer 3323 return ResultTy; 3324 } 3325 // Handle block pointers. 3326 if (lType->isBlockPointerType() && rType->isIntegerType()) { 3327 if (!RHSIsNull) 3328 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer) 3329 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 3330 ImpCastExprToType(rex, lType); // promote the integer to pointer 3331 return ResultTy; 3332 } 3333 if (lType->isIntegerType() && rType->isBlockPointerType()) { 3334 if (!LHSIsNull) 3335 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer) 3336 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 3337 ImpCastExprToType(lex, rType); // promote the integer to pointer 3338 return ResultTy; 3339 } 3340 return InvalidOperands(Loc, lex, rex); 3341} 3342 3343/// CheckVectorCompareOperands - vector comparisons are a clang extension that 3344/// operates on extended vector types. Instead of producing an IntTy result, 3345/// like a scalar comparison, a vector comparison produces a vector of integer 3346/// types. 3347QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex, 3348 SourceLocation Loc, 3349 bool isRelational) { 3350 // Check to make sure we're operating on vectors of the same type and width, 3351 // Allowing one side to be a scalar of element type. 3352 QualType vType = CheckVectorOperands(Loc, lex, rex); 3353 if (vType.isNull()) 3354 return vType; 3355 3356 QualType lType = lex->getType(); 3357 QualType rType = rex->getType(); 3358 3359 // For non-floating point types, check for self-comparisons of the form 3360 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 3361 // often indicate logic errors in the program. 3362 if (!lType->isFloatingType()) { 3363 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens())) 3364 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens())) 3365 if (DRL->getDecl() == DRR->getDecl()) 3366 Diag(Loc, diag::warn_selfcomparison); 3367 } 3368 3369 // Check for comparisons of floating point operands using != and ==. 3370 if (!isRelational && lType->isFloatingType()) { 3371 assert (rType->isFloatingType()); 3372 CheckFloatComparison(Loc,lex,rex); 3373 } 3374 3375 // Return the type for the comparison, which is the same as vector type for 3376 // integer vectors, or an integer type of identical size and number of 3377 // elements for floating point vectors. 3378 if (lType->isIntegerType()) 3379 return lType; 3380 3381 const VectorType *VTy = lType->getAsVectorType(); 3382 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 3383 if (TypeSize == Context.getTypeSize(Context.IntTy)) 3384 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 3385 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 3386 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 3387 3388 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 3389 "Unhandled vector element size in vector compare"); 3390 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 3391} 3392 3393inline QualType Sema::CheckBitwiseOperands( 3394 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) 3395{ 3396 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 3397 return CheckVectorOperands(Loc, lex, rex); 3398 3399 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 3400 3401 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType()) 3402 return compType; 3403 return InvalidOperands(Loc, lex, rex); 3404} 3405 3406inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 3407 Expr *&lex, Expr *&rex, SourceLocation Loc) 3408{ 3409 UsualUnaryConversions(lex); 3410 UsualUnaryConversions(rex); 3411 3412 if (lex->getType()->isScalarType() && rex->getType()->isScalarType()) 3413 return Context.IntTy; 3414 return InvalidOperands(Loc, lex, rex); 3415} 3416 3417/// IsReadonlyProperty - Verify that otherwise a valid l-value expression 3418/// is a read-only property; return true if so. A readonly property expression 3419/// depends on various declarations and thus must be treated specially. 3420/// 3421static bool IsReadonlyProperty(Expr *E, Sema &S) 3422{ 3423 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) { 3424 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E); 3425 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) { 3426 QualType BaseType = PropExpr->getBase()->getType(); 3427 if (const PointerType *PTy = BaseType->getAsPointerType()) 3428 if (const ObjCInterfaceType *IFTy = 3429 PTy->getPointeeType()->getAsObjCInterfaceType()) 3430 if (ObjCInterfaceDecl *IFace = IFTy->getDecl()) 3431 if (S.isPropertyReadonly(PDecl, IFace)) 3432 return true; 3433 } 3434 } 3435 return false; 3436} 3437 3438/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 3439/// emit an error and return true. If so, return false. 3440static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 3441 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context); 3442 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S)) 3443 IsLV = Expr::MLV_ReadonlyProperty; 3444 if (IsLV == Expr::MLV_Valid) 3445 return false; 3446 3447 unsigned Diag = 0; 3448 bool NeedType = false; 3449 switch (IsLV) { // C99 6.5.16p2 3450 default: assert(0 && "Unknown result from isModifiableLvalue!"); 3451 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break; 3452 case Expr::MLV_ArrayType: 3453 Diag = diag::err_typecheck_array_not_modifiable_lvalue; 3454 NeedType = true; 3455 break; 3456 case Expr::MLV_NotObjectType: 3457 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue; 3458 NeedType = true; 3459 break; 3460 case Expr::MLV_LValueCast: 3461 Diag = diag::err_typecheck_lvalue_casts_not_supported; 3462 break; 3463 case Expr::MLV_InvalidExpression: 3464 Diag = diag::err_typecheck_expression_not_modifiable_lvalue; 3465 break; 3466 case Expr::MLV_IncompleteType: 3467 case Expr::MLV_IncompleteVoidType: 3468 return S.RequireCompleteType(Loc, E->getType(), 3469 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, 3470 E->getSourceRange()); 3471 case Expr::MLV_DuplicateVectorComponents: 3472 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 3473 break; 3474 case Expr::MLV_NotBlockQualified: 3475 Diag = diag::err_block_decl_ref_not_modifiable_lvalue; 3476 break; 3477 case Expr::MLV_ReadonlyProperty: 3478 Diag = diag::error_readonly_property_assignment; 3479 break; 3480 case Expr::MLV_NoSetterProperty: 3481 Diag = diag::error_nosetter_property_assignment; 3482 break; 3483 } 3484 3485 if (NeedType) 3486 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange(); 3487 else 3488 S.Diag(Loc, Diag) << E->getSourceRange(); 3489 return true; 3490} 3491 3492 3493 3494// C99 6.5.16.1 3495QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS, 3496 SourceLocation Loc, 3497 QualType CompoundType) { 3498 // Verify that LHS is a modifiable lvalue, and emit error if not. 3499 if (CheckForModifiableLvalue(LHS, Loc, *this)) 3500 return QualType(); 3501 3502 QualType LHSType = LHS->getType(); 3503 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType; 3504 3505 AssignConvertType ConvTy; 3506 if (CompoundType.isNull()) { 3507 // Simple assignment "x = y". 3508 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS); 3509 // Special case of NSObject attributes on c-style pointer types. 3510 if (ConvTy == IncompatiblePointer && 3511 ((Context.isObjCNSObjectType(LHSType) && 3512 Context.isObjCObjectPointerType(RHSType)) || 3513 (Context.isObjCNSObjectType(RHSType) && 3514 Context.isObjCObjectPointerType(LHSType)))) 3515 ConvTy = Compatible; 3516 3517 // If the RHS is a unary plus or minus, check to see if they = and + are 3518 // right next to each other. If so, the user may have typo'd "x =+ 4" 3519 // instead of "x += 4". 3520 Expr *RHSCheck = RHS; 3521 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 3522 RHSCheck = ICE->getSubExpr(); 3523 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 3524 if ((UO->getOpcode() == UnaryOperator::Plus || 3525 UO->getOpcode() == UnaryOperator::Minus) && 3526 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 3527 // Only if the two operators are exactly adjacent. 3528 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() && 3529 // And there is a space or other character before the subexpr of the 3530 // unary +/-. We don't want to warn on "x=-1". 3531 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 3532 UO->getSubExpr()->getLocStart().isFileID()) { 3533 Diag(Loc, diag::warn_not_compound_assign) 3534 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-") 3535 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 3536 } 3537 } 3538 } else { 3539 // Compound assignment "x += y" 3540 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType); 3541 } 3542 3543 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 3544 RHS, "assigning")) 3545 return QualType(); 3546 3547 // C99 6.5.16p3: The type of an assignment expression is the type of the 3548 // left operand unless the left operand has qualified type, in which case 3549 // it is the unqualified version of the type of the left operand. 3550 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 3551 // is converted to the type of the assignment expression (above). 3552 // C++ 5.17p1: the type of the assignment expression is that of its left 3553 // oprdu. 3554 return LHSType.getUnqualifiedType(); 3555} 3556 3557// C99 6.5.17 3558QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) { 3559 // FIXME: what is required for LHS? 3560 3561 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions. 3562 DefaultFunctionArrayConversion(RHS); 3563 return RHS->getType(); 3564} 3565 3566/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 3567/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 3568QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc, 3569 bool isInc) { 3570 if (Op->isTypeDependent()) 3571 return Context.DependentTy; 3572 3573 QualType ResType = Op->getType(); 3574 assert(!ResType.isNull() && "no type for increment/decrement expression"); 3575 3576 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) { 3577 // Decrement of bool is not allowed. 3578 if (!isInc) { 3579 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 3580 return QualType(); 3581 } 3582 // Increment of bool sets it to true, but is deprecated. 3583 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); 3584 } else if (ResType->isRealType()) { 3585 // OK! 3586 } else if (const PointerType *PT = ResType->getAsPointerType()) { 3587 // C99 6.5.2.4p2, 6.5.6p2 3588 if (PT->getPointeeType()->isObjectType()) { 3589 // Pointer to object is ok! 3590 } else if (PT->getPointeeType()->isVoidType()) { 3591 if (getLangOptions().CPlusPlus) { 3592 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type) 3593 << Op->getSourceRange(); 3594 return QualType(); 3595 } 3596 3597 // Pointer to void is a GNU extension in C. 3598 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange(); 3599 } else if (PT->getPointeeType()->isFunctionType()) { 3600 if (getLangOptions().CPlusPlus) { 3601 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type) 3602 << Op->getType() << Op->getSourceRange(); 3603 return QualType(); 3604 } 3605 3606 Diag(OpLoc, diag::ext_gnu_ptr_func_arith) 3607 << ResType << Op->getSourceRange(); 3608 } else { 3609 RequireCompleteType(OpLoc, PT->getPointeeType(), 3610 diag::err_typecheck_arithmetic_incomplete_type, 3611 Op->getSourceRange(), SourceRange(), 3612 ResType); 3613 return QualType(); 3614 } 3615 } else if (ResType->isComplexType()) { 3616 // C99 does not support ++/-- on complex types, we allow as an extension. 3617 Diag(OpLoc, diag::ext_integer_increment_complex) 3618 << ResType << Op->getSourceRange(); 3619 } else { 3620 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 3621 << ResType << Op->getSourceRange(); 3622 return QualType(); 3623 } 3624 // At this point, we know we have a real, complex or pointer type. 3625 // Now make sure the operand is a modifiable lvalue. 3626 if (CheckForModifiableLvalue(Op, OpLoc, *this)) 3627 return QualType(); 3628 return ResType; 3629} 3630 3631/// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 3632/// This routine allows us to typecheck complex/recursive expressions 3633/// where the declaration is needed for type checking. We only need to 3634/// handle cases when the expression references a function designator 3635/// or is an lvalue. Here are some examples: 3636/// - &(x) => x 3637/// - &*****f => f for f a function designator. 3638/// - &s.xx => s 3639/// - &s.zz[1].yy -> s, if zz is an array 3640/// - *(x + 1) -> x, if x is an array 3641/// - &"123"[2] -> 0 3642/// - & __real__ x -> x 3643static NamedDecl *getPrimaryDecl(Expr *E) { 3644 switch (E->getStmtClass()) { 3645 case Stmt::DeclRefExprClass: 3646 case Stmt::QualifiedDeclRefExprClass: 3647 return cast<DeclRefExpr>(E)->getDecl(); 3648 case Stmt::MemberExprClass: 3649 // Fields cannot be declared with a 'register' storage class. 3650 // &X->f is always ok, even if X is declared register. 3651 if (cast<MemberExpr>(E)->isArrow()) 3652 return 0; 3653 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 3654 case Stmt::ArraySubscriptExprClass: { 3655 // &X[4] and &4[X] refers to X if X is not a pointer. 3656 3657 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase()); 3658 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D); 3659 if (!VD || VD->getType()->isPointerType()) 3660 return 0; 3661 else 3662 return VD; 3663 } 3664 case Stmt::UnaryOperatorClass: { 3665 UnaryOperator *UO = cast<UnaryOperator>(E); 3666 3667 switch(UO->getOpcode()) { 3668 case UnaryOperator::Deref: { 3669 // *(X + 1) refers to X if X is not a pointer. 3670 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) { 3671 ValueDecl *VD = dyn_cast<ValueDecl>(D); 3672 if (!VD || VD->getType()->isPointerType()) 3673 return 0; 3674 return VD; 3675 } 3676 return 0; 3677 } 3678 case UnaryOperator::Real: 3679 case UnaryOperator::Imag: 3680 case UnaryOperator::Extension: 3681 return getPrimaryDecl(UO->getSubExpr()); 3682 default: 3683 return 0; 3684 } 3685 } 3686 case Stmt::BinaryOperatorClass: { 3687 BinaryOperator *BO = cast<BinaryOperator>(E); 3688 3689 // Handle cases involving pointer arithmetic. The result of an 3690 // Assign or AddAssign is not an lvalue so they can be ignored. 3691 3692 // (x + n) or (n + x) => x 3693 if (BO->getOpcode() == BinaryOperator::Add) { 3694 if (BO->getLHS()->getType()->isPointerType()) { 3695 return getPrimaryDecl(BO->getLHS()); 3696 } else if (BO->getRHS()->getType()->isPointerType()) { 3697 return getPrimaryDecl(BO->getRHS()); 3698 } 3699 } 3700 3701 return 0; 3702 } 3703 case Stmt::ParenExprClass: 3704 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 3705 case Stmt::ImplicitCastExprClass: 3706 // &X[4] when X is an array, has an implicit cast from array to pointer. 3707 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 3708 default: 3709 return 0; 3710 } 3711} 3712 3713/// CheckAddressOfOperand - The operand of & must be either a function 3714/// designator or an lvalue designating an object. If it is an lvalue, the 3715/// object cannot be declared with storage class register or be a bit field. 3716/// Note: The usual conversions are *not* applied to the operand of the & 3717/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 3718/// In C++, the operand might be an overloaded function name, in which case 3719/// we allow the '&' but retain the overloaded-function type. 3720QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) { 3721 if (op->isTypeDependent()) 3722 return Context.DependentTy; 3723 3724 if (getLangOptions().C99) { 3725 // Implement C99-only parts of addressof rules. 3726 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 3727 if (uOp->getOpcode() == UnaryOperator::Deref) 3728 // Per C99 6.5.3.2, the address of a deref always returns a valid result 3729 // (assuming the deref expression is valid). 3730 return uOp->getSubExpr()->getType(); 3731 } 3732 // Technically, there should be a check for array subscript 3733 // expressions here, but the result of one is always an lvalue anyway. 3734 } 3735 NamedDecl *dcl = getPrimaryDecl(op); 3736 Expr::isLvalueResult lval = op->isLvalue(Context); 3737 3738 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1 3739 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators 3740 // FIXME: emit more specific diag... 3741 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 3742 << op->getSourceRange(); 3743 return QualType(); 3744 } 3745 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1 3746 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) { 3747 if (Field->isBitField()) { 3748 Diag(OpLoc, diag::err_typecheck_address_of) 3749 << "bit-field" << op->getSourceRange(); 3750 return QualType(); 3751 } 3752 } 3753 // Check for Apple extension for accessing vector components. 3754 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) && 3755 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){ 3756 Diag(OpLoc, diag::err_typecheck_address_of) 3757 << "vector element" << op->getSourceRange(); 3758 return QualType(); 3759 } else if (dcl) { // C99 6.5.3.2p1 3760 // We have an lvalue with a decl. Make sure the decl is not declared 3761 // with the register storage-class specifier. 3762 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 3763 if (vd->getStorageClass() == VarDecl::Register) { 3764 Diag(OpLoc, diag::err_typecheck_address_of) 3765 << "register variable" << op->getSourceRange(); 3766 return QualType(); 3767 } 3768 } else if (isa<OverloadedFunctionDecl>(dcl)) { 3769 return Context.OverloadTy; 3770 } else if (isa<FieldDecl>(dcl)) { 3771 // Okay: we can take the address of a field. 3772 // Could be a pointer to member, though, if there is an explicit 3773 // scope qualifier for the class. 3774 if (isa<QualifiedDeclRefExpr>(op)) { 3775 DeclContext *Ctx = dcl->getDeclContext(); 3776 if (Ctx && Ctx->isRecord()) 3777 return Context.getMemberPointerType(op->getType(), 3778 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 3779 } 3780 } else if (isa<FunctionDecl>(dcl)) { 3781 // Okay: we can take the address of a function. 3782 // As above. 3783 if (isa<QualifiedDeclRefExpr>(op)) { 3784 DeclContext *Ctx = dcl->getDeclContext(); 3785 if (Ctx && Ctx->isRecord()) 3786 return Context.getMemberPointerType(op->getType(), 3787 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 3788 } 3789 } 3790 else 3791 assert(0 && "Unknown/unexpected decl type"); 3792 } 3793 3794 // If the operand has type "type", the result has type "pointer to type". 3795 return Context.getPointerType(op->getType()); 3796} 3797 3798QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) { 3799 if (Op->isTypeDependent()) 3800 return Context.DependentTy; 3801 3802 UsualUnaryConversions(Op); 3803 QualType Ty = Op->getType(); 3804 3805 // Note that per both C89 and C99, this is always legal, even if ptype is an 3806 // incomplete type or void. It would be possible to warn about dereferencing 3807 // a void pointer, but it's completely well-defined, and such a warning is 3808 // unlikely to catch any mistakes. 3809 if (const PointerType *PT = Ty->getAsPointerType()) 3810 return PT->getPointeeType(); 3811 3812 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 3813 << Ty << Op->getSourceRange(); 3814 return QualType(); 3815} 3816 3817static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode( 3818 tok::TokenKind Kind) { 3819 BinaryOperator::Opcode Opc; 3820 switch (Kind) { 3821 default: assert(0 && "Unknown binop!"); 3822 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break; 3823 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break; 3824 case tok::star: Opc = BinaryOperator::Mul; break; 3825 case tok::slash: Opc = BinaryOperator::Div; break; 3826 case tok::percent: Opc = BinaryOperator::Rem; break; 3827 case tok::plus: Opc = BinaryOperator::Add; break; 3828 case tok::minus: Opc = BinaryOperator::Sub; break; 3829 case tok::lessless: Opc = BinaryOperator::Shl; break; 3830 case tok::greatergreater: Opc = BinaryOperator::Shr; break; 3831 case tok::lessequal: Opc = BinaryOperator::LE; break; 3832 case tok::less: Opc = BinaryOperator::LT; break; 3833 case tok::greaterequal: Opc = BinaryOperator::GE; break; 3834 case tok::greater: Opc = BinaryOperator::GT; break; 3835 case tok::exclaimequal: Opc = BinaryOperator::NE; break; 3836 case tok::equalequal: Opc = BinaryOperator::EQ; break; 3837 case tok::amp: Opc = BinaryOperator::And; break; 3838 case tok::caret: Opc = BinaryOperator::Xor; break; 3839 case tok::pipe: Opc = BinaryOperator::Or; break; 3840 case tok::ampamp: Opc = BinaryOperator::LAnd; break; 3841 case tok::pipepipe: Opc = BinaryOperator::LOr; break; 3842 case tok::equal: Opc = BinaryOperator::Assign; break; 3843 case tok::starequal: Opc = BinaryOperator::MulAssign; break; 3844 case tok::slashequal: Opc = BinaryOperator::DivAssign; break; 3845 case tok::percentequal: Opc = BinaryOperator::RemAssign; break; 3846 case tok::plusequal: Opc = BinaryOperator::AddAssign; break; 3847 case tok::minusequal: Opc = BinaryOperator::SubAssign; break; 3848 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break; 3849 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break; 3850 case tok::ampequal: Opc = BinaryOperator::AndAssign; break; 3851 case tok::caretequal: Opc = BinaryOperator::XorAssign; break; 3852 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break; 3853 case tok::comma: Opc = BinaryOperator::Comma; break; 3854 } 3855 return Opc; 3856} 3857 3858static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode( 3859 tok::TokenKind Kind) { 3860 UnaryOperator::Opcode Opc; 3861 switch (Kind) { 3862 default: assert(0 && "Unknown unary op!"); 3863 case tok::plusplus: Opc = UnaryOperator::PreInc; break; 3864 case tok::minusminus: Opc = UnaryOperator::PreDec; break; 3865 case tok::amp: Opc = UnaryOperator::AddrOf; break; 3866 case tok::star: Opc = UnaryOperator::Deref; break; 3867 case tok::plus: Opc = UnaryOperator::Plus; break; 3868 case tok::minus: Opc = UnaryOperator::Minus; break; 3869 case tok::tilde: Opc = UnaryOperator::Not; break; 3870 case tok::exclaim: Opc = UnaryOperator::LNot; break; 3871 case tok::kw___real: Opc = UnaryOperator::Real; break; 3872 case tok::kw___imag: Opc = UnaryOperator::Imag; break; 3873 case tok::kw___extension__: Opc = UnaryOperator::Extension; break; 3874 } 3875 return Opc; 3876} 3877 3878/// CreateBuiltinBinOp - Creates a new built-in binary operation with 3879/// operator @p Opc at location @c TokLoc. This routine only supports 3880/// built-in operations; ActOnBinOp handles overloaded operators. 3881Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 3882 unsigned Op, 3883 Expr *lhs, Expr *rhs) { 3884 QualType ResultTy; // Result type of the binary operator. 3885 QualType CompTy; // Computation type for compound assignments (e.g. '+=') 3886 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op; 3887 3888 switch (Opc) { 3889 default: 3890 assert(0 && "Unknown binary expr!"); 3891 case BinaryOperator::Assign: 3892 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType()); 3893 break; 3894 case BinaryOperator::PtrMemD: 3895 case BinaryOperator::PtrMemI: 3896 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc, 3897 Opc == BinaryOperator::PtrMemI); 3898 break; 3899 case BinaryOperator::Mul: 3900 case BinaryOperator::Div: 3901 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc); 3902 break; 3903 case BinaryOperator::Rem: 3904 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc); 3905 break; 3906 case BinaryOperator::Add: 3907 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc); 3908 break; 3909 case BinaryOperator::Sub: 3910 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc); 3911 break; 3912 case BinaryOperator::Shl: 3913 case BinaryOperator::Shr: 3914 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc); 3915 break; 3916 case BinaryOperator::LE: 3917 case BinaryOperator::LT: 3918 case BinaryOperator::GE: 3919 case BinaryOperator::GT: 3920 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true); 3921 break; 3922 case BinaryOperator::EQ: 3923 case BinaryOperator::NE: 3924 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false); 3925 break; 3926 case BinaryOperator::And: 3927 case BinaryOperator::Xor: 3928 case BinaryOperator::Or: 3929 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc); 3930 break; 3931 case BinaryOperator::LAnd: 3932 case BinaryOperator::LOr: 3933 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc); 3934 break; 3935 case BinaryOperator::MulAssign: 3936 case BinaryOperator::DivAssign: 3937 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true); 3938 if (!CompTy.isNull()) 3939 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy); 3940 break; 3941 case BinaryOperator::RemAssign: 3942 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true); 3943 if (!CompTy.isNull()) 3944 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy); 3945 break; 3946 case BinaryOperator::AddAssign: 3947 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true); 3948 if (!CompTy.isNull()) 3949 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy); 3950 break; 3951 case BinaryOperator::SubAssign: 3952 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true); 3953 if (!CompTy.isNull()) 3954 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy); 3955 break; 3956 case BinaryOperator::ShlAssign: 3957 case BinaryOperator::ShrAssign: 3958 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true); 3959 if (!CompTy.isNull()) 3960 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy); 3961 break; 3962 case BinaryOperator::AndAssign: 3963 case BinaryOperator::XorAssign: 3964 case BinaryOperator::OrAssign: 3965 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true); 3966 if (!CompTy.isNull()) 3967 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy); 3968 break; 3969 case BinaryOperator::Comma: 3970 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc); 3971 break; 3972 } 3973 if (ResultTy.isNull()) 3974 return ExprError(); 3975 if (CompTy.isNull()) 3976 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc)); 3977 else 3978 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy, 3979 CompTy, OpLoc)); 3980} 3981 3982// Binary Operators. 'Tok' is the token for the operator. 3983Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 3984 tok::TokenKind Kind, 3985 ExprArg LHS, ExprArg RHS) { 3986 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind); 3987 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release(); 3988 3989 assert((lhs != 0) && "ActOnBinOp(): missing left expression"); 3990 assert((rhs != 0) && "ActOnBinOp(): missing right expression"); 3991 3992 // If either expression is type-dependent, just build the AST. 3993 // FIXME: We'll need to perform some caching of the result of name 3994 // lookup for operator+. 3995 if (lhs->isTypeDependent() || rhs->isTypeDependent()) { 3996 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) 3997 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, 3998 Context.DependentTy, 3999 Context.DependentTy, TokLoc)); 4000 else 4001 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, 4002 Context.DependentTy, TokLoc)); 4003 } 4004 4005 if (getLangOptions().CPlusPlus && Opc != BinaryOperator::PtrMemD && 4006 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() || 4007 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) { 4008 // If this is one of the assignment operators, we only perform 4009 // overload resolution if the left-hand side is a class or 4010 // enumeration type (C++ [expr.ass]p3). 4011 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign && 4012 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) { 4013 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs); 4014 } 4015 4016 // Determine which overloaded operator we're dealing with. 4017 static const OverloadedOperatorKind OverOps[] = { 4018 // Overloading .* is not possible. 4019 static_cast<OverloadedOperatorKind>(0), OO_ArrowStar, 4020 OO_Star, OO_Slash, OO_Percent, 4021 OO_Plus, OO_Minus, 4022 OO_LessLess, OO_GreaterGreater, 4023 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual, 4024 OO_EqualEqual, OO_ExclaimEqual, 4025 OO_Amp, 4026 OO_Caret, 4027 OO_Pipe, 4028 OO_AmpAmp, 4029 OO_PipePipe, 4030 OO_Equal, OO_StarEqual, 4031 OO_SlashEqual, OO_PercentEqual, 4032 OO_PlusEqual, OO_MinusEqual, 4033 OO_LessLessEqual, OO_GreaterGreaterEqual, 4034 OO_AmpEqual, OO_CaretEqual, 4035 OO_PipeEqual, 4036 OO_Comma 4037 }; 4038 OverloadedOperatorKind OverOp = OverOps[Opc]; 4039 4040 // Add the appropriate overloaded operators (C++ [over.match.oper]) 4041 // to the candidate set. 4042 OverloadCandidateSet CandidateSet; 4043 Expr *Args[2] = { lhs, rhs }; 4044 if (AddOperatorCandidates(OverOp, S, TokLoc, Args, 2, CandidateSet)) 4045 return ExprError(); 4046 4047 // Perform overload resolution. 4048 OverloadCandidateSet::iterator Best; 4049 switch (BestViableFunction(CandidateSet, Best)) { 4050 case OR_Success: { 4051 // We found a built-in operator or an overloaded operator. 4052 FunctionDecl *FnDecl = Best->Function; 4053 4054 if (FnDecl) { 4055 // We matched an overloaded operator. Build a call to that 4056 // operator. 4057 4058 // Convert the arguments. 4059 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 4060 if (PerformObjectArgumentInitialization(lhs, Method) || 4061 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(), 4062 "passing")) 4063 return ExprError(); 4064 } else { 4065 // Convert the arguments. 4066 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(), 4067 "passing") || 4068 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(), 4069 "passing")) 4070 return ExprError(); 4071 } 4072 4073 // Determine the result type 4074 QualType ResultTy 4075 = FnDecl->getType()->getAsFunctionType()->getResultType(); 4076 ResultTy = ResultTy.getNonReferenceType(); 4077 4078 // Build the actual expression node. 4079 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(), 4080 SourceLocation()); 4081 UsualUnaryConversions(FnExpr); 4082 4083 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2, 4084 ResultTy, TokLoc)); 4085 } else { 4086 // We matched a built-in operator. Convert the arguments, then 4087 // break out so that we will build the appropriate built-in 4088 // operator node. 4089 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0], 4090 Best->Conversions[0], "passing") || 4091 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1], 4092 Best->Conversions[1], "passing")) 4093 return ExprError(); 4094 4095 break; 4096 } 4097 } 4098 4099 case OR_No_Viable_Function: 4100 // No viable function; fall through to handling this as a 4101 // built-in operator, which will produce an error message for us. 4102 break; 4103 4104 case OR_Ambiguous: 4105 Diag(TokLoc, diag::err_ovl_ambiguous_oper) 4106 << BinaryOperator::getOpcodeStr(Opc) 4107 << lhs->getSourceRange() << rhs->getSourceRange(); 4108 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 4109 return ExprError(); 4110 4111 case OR_Deleted: 4112 Diag(TokLoc, diag::err_ovl_deleted_oper) 4113 << Best->Function->isDeleted() 4114 << BinaryOperator::getOpcodeStr(Opc) 4115 << lhs->getSourceRange() << rhs->getSourceRange(); 4116 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 4117 return ExprError(); 4118 } 4119 4120 // Either we found no viable overloaded operator or we matched a 4121 // built-in operator. In either case, fall through to trying to 4122 // build a built-in operation. 4123 } 4124 4125 // Build a built-in binary operation. 4126 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs); 4127} 4128 4129// Unary Operators. 'Tok' is the token for the operator. 4130Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 4131 tok::TokenKind Op, ExprArg input) { 4132 // FIXME: Input is modified later, but smart pointer not reassigned. 4133 Expr *Input = (Expr*)input.get(); 4134 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op); 4135 4136 if (getLangOptions().CPlusPlus && 4137 (Input->getType()->isRecordType() 4138 || Input->getType()->isEnumeralType())) { 4139 // Determine which overloaded operator we're dealing with. 4140 static const OverloadedOperatorKind OverOps[] = { 4141 OO_None, OO_None, 4142 OO_PlusPlus, OO_MinusMinus, 4143 OO_Amp, OO_Star, 4144 OO_Plus, OO_Minus, 4145 OO_Tilde, OO_Exclaim, 4146 OO_None, OO_None, 4147 OO_None, 4148 OO_None 4149 }; 4150 OverloadedOperatorKind OverOp = OverOps[Opc]; 4151 4152 // Add the appropriate overloaded operators (C++ [over.match.oper]) 4153 // to the candidate set. 4154 OverloadCandidateSet CandidateSet; 4155 if (OverOp != OO_None && 4156 AddOperatorCandidates(OverOp, S, OpLoc, &Input, 1, CandidateSet)) 4157 return ExprError(); 4158 4159 // Perform overload resolution. 4160 OverloadCandidateSet::iterator Best; 4161 switch (BestViableFunction(CandidateSet, Best)) { 4162 case OR_Success: { 4163 // We found a built-in operator or an overloaded operator. 4164 FunctionDecl *FnDecl = Best->Function; 4165 4166 if (FnDecl) { 4167 // We matched an overloaded operator. Build a call to that 4168 // operator. 4169 4170 // Convert the arguments. 4171 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 4172 if (PerformObjectArgumentInitialization(Input, Method)) 4173 return ExprError(); 4174 } else { 4175 // Convert the arguments. 4176 if (PerformCopyInitialization(Input, 4177 FnDecl->getParamDecl(0)->getType(), 4178 "passing")) 4179 return ExprError(); 4180 } 4181 4182 // Determine the result type 4183 QualType ResultTy 4184 = FnDecl->getType()->getAsFunctionType()->getResultType(); 4185 ResultTy = ResultTy.getNonReferenceType(); 4186 4187 // Build the actual expression node. 4188 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(), 4189 SourceLocation()); 4190 UsualUnaryConversions(FnExpr); 4191 4192 input.release(); 4193 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, &Input, 4194 1, ResultTy, OpLoc)); 4195 } else { 4196 // We matched a built-in operator. Convert the arguments, then 4197 // break out so that we will build the appropriate built-in 4198 // operator node. 4199 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 4200 Best->Conversions[0], "passing")) 4201 return ExprError(); 4202 4203 break; 4204 } 4205 } 4206 4207 case OR_No_Viable_Function: 4208 // No viable function; fall through to handling this as a 4209 // built-in operator, which will produce an error message for us. 4210 break; 4211 4212 case OR_Ambiguous: 4213 Diag(OpLoc, diag::err_ovl_ambiguous_oper) 4214 << UnaryOperator::getOpcodeStr(Opc) 4215 << Input->getSourceRange(); 4216 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 4217 return ExprError(); 4218 4219 case OR_Deleted: 4220 Diag(OpLoc, diag::err_ovl_deleted_oper) 4221 << Best->Function->isDeleted() 4222 << UnaryOperator::getOpcodeStr(Opc) 4223 << Input->getSourceRange(); 4224 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 4225 return ExprError(); 4226 } 4227 4228 // Either we found no viable overloaded operator or we matched a 4229 // built-in operator. In either case, fall through to trying to 4230 // build a built-in operation. 4231 } 4232 4233 QualType resultType; 4234 switch (Opc) { 4235 default: 4236 assert(0 && "Unimplemented unary expr!"); 4237 case UnaryOperator::PreInc: 4238 case UnaryOperator::PreDec: 4239 resultType = CheckIncrementDecrementOperand(Input, OpLoc, 4240 Opc == UnaryOperator::PreInc); 4241 break; 4242 case UnaryOperator::AddrOf: 4243 resultType = CheckAddressOfOperand(Input, OpLoc); 4244 break; 4245 case UnaryOperator::Deref: 4246 DefaultFunctionArrayConversion(Input); 4247 resultType = CheckIndirectionOperand(Input, OpLoc); 4248 break; 4249 case UnaryOperator::Plus: 4250 case UnaryOperator::Minus: 4251 UsualUnaryConversions(Input); 4252 resultType = Input->getType(); 4253 if (resultType->isDependentType()) 4254 break; 4255 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 4256 break; 4257 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7 4258 resultType->isEnumeralType()) 4259 break; 4260 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6 4261 Opc == UnaryOperator::Plus && 4262 resultType->isPointerType()) 4263 break; 4264 4265 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 4266 << resultType << Input->getSourceRange()); 4267 case UnaryOperator::Not: // bitwise complement 4268 UsualUnaryConversions(Input); 4269 resultType = Input->getType(); 4270 if (resultType->isDependentType()) 4271 break; 4272 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 4273 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 4274 // C99 does not support '~' for complex conjugation. 4275 Diag(OpLoc, diag::ext_integer_complement_complex) 4276 << resultType << Input->getSourceRange(); 4277 else if (!resultType->isIntegerType()) 4278 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 4279 << resultType << Input->getSourceRange()); 4280 break; 4281 case UnaryOperator::LNot: // logical negation 4282 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 4283 DefaultFunctionArrayConversion(Input); 4284 resultType = Input->getType(); 4285 if (resultType->isDependentType()) 4286 break; 4287 if (!resultType->isScalarType()) // C99 6.5.3.3p1 4288 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 4289 << resultType << Input->getSourceRange()); 4290 // LNot always has type int. C99 6.5.3.3p5. 4291 // In C++, it's bool. C++ 5.3.1p8 4292 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy; 4293 break; 4294 case UnaryOperator::Real: 4295 case UnaryOperator::Imag: 4296 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real); 4297 break; 4298 case UnaryOperator::Extension: 4299 resultType = Input->getType(); 4300 break; 4301 } 4302 if (resultType.isNull()) 4303 return ExprError(); 4304 input.release(); 4305 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc)); 4306} 4307 4308/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 4309Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, 4310 SourceLocation LabLoc, 4311 IdentifierInfo *LabelII) { 4312 // Look up the record for this label identifier. 4313 llvm::DenseMap<IdentifierInfo*, Action::StmtTy*>::iterator I = 4314 ActiveScope->LabelMap.find(LabelII); 4315 4316 LabelStmt *LabelDecl; 4317 4318 // If we haven't seen this label yet, create a forward reference. It 4319 // will be validated and/or cleaned up in ActOnFinishFunctionBody. 4320 if (I == ActiveScope->LabelMap.end()) { 4321 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0); 4322 4323 ActiveScope->LabelMap.insert(std::make_pair(LabelII, LabelDecl)); 4324 } else 4325 LabelDecl = static_cast<LabelStmt *>(I->second); 4326 4327 // Create the AST node. The address of a label always has type 'void*'. 4328 return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl, 4329 Context.getPointerType(Context.VoidTy)); 4330} 4331 4332Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt, 4333 SourceLocation RPLoc) { // "({..})" 4334 Stmt *SubStmt = static_cast<Stmt*>(substmt); 4335 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 4336 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 4337 4338 bool isFileScope = getCurFunctionOrMethodDecl() == 0; 4339 if (isFileScope) { 4340 return Diag(LPLoc, diag::err_stmtexpr_file_scope); 4341 } 4342 4343 // FIXME: there are a variety of strange constraints to enforce here, for 4344 // example, it is not possible to goto into a stmt expression apparently. 4345 // More semantic analysis is needed. 4346 4347 // FIXME: the last statement in the compount stmt has its value used. We 4348 // should not warn about it being unused. 4349 4350 // If there are sub stmts in the compound stmt, take the type of the last one 4351 // as the type of the stmtexpr. 4352 QualType Ty = Context.VoidTy; 4353 4354 if (!Compound->body_empty()) { 4355 Stmt *LastStmt = Compound->body_back(); 4356 // If LastStmt is a label, skip down through into the body. 4357 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) 4358 LastStmt = Label->getSubStmt(); 4359 4360 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) 4361 Ty = LastExpr->getType(); 4362 } 4363 4364 return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 4365} 4366 4367Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 4368 SourceLocation BuiltinLoc, 4369 SourceLocation TypeLoc, 4370 TypeTy *argty, 4371 OffsetOfComponent *CompPtr, 4372 unsigned NumComponents, 4373 SourceLocation RPLoc) { 4374 QualType ArgTy = QualType::getFromOpaquePtr(argty); 4375 assert(!ArgTy.isNull() && "Missing type argument!"); 4376 4377 bool Dependent = ArgTy->isDependentType(); 4378 4379 // We must have at least one component that refers to the type, and the first 4380 // one is known to be a field designator. Verify that the ArgTy represents 4381 // a struct/union/class. 4382 if (!Dependent && !ArgTy->isRecordType()) 4383 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy; 4384 4385 // FIXME: Does the type need to be complete? 4386 4387 // Otherwise, create a null pointer as the base, and iteratively process 4388 // the offsetof designators. 4389 QualType ArgTyPtr = Context.getPointerType(ArgTy); 4390 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr); 4391 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref, 4392 ArgTy, SourceLocation()); 4393 4394 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 4395 // GCC extension, diagnose them. 4396 // FIXME: This diagnostic isn't actually visible because the location is in 4397 // a system header! 4398 if (NumComponents != 1) 4399 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 4400 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); 4401 4402 if (!Dependent) { 4403 // FIXME: Dependent case loses a lot of information here. And probably 4404 // leaks like a sieve. 4405 for (unsigned i = 0; i != NumComponents; ++i) { 4406 const OffsetOfComponent &OC = CompPtr[i]; 4407 if (OC.isBrackets) { 4408 // Offset of an array sub-field. TODO: Should we allow vector elements? 4409 const ArrayType *AT = Context.getAsArrayType(Res->getType()); 4410 if (!AT) { 4411 Res->Destroy(Context); 4412 return Diag(OC.LocEnd, diag::err_offsetof_array_type) 4413 << Res->getType(); 4414 } 4415 4416 // FIXME: C++: Verify that operator[] isn't overloaded. 4417 4418 // Promote the array so it looks more like a normal array subscript 4419 // expression. 4420 DefaultFunctionArrayConversion(Res); 4421 4422 // C99 6.5.2.1p1 4423 Expr *Idx = static_cast<Expr*>(OC.U.E); 4424 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType()) 4425 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript) 4426 << Idx->getSourceRange(); 4427 4428 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(), 4429 OC.LocEnd); 4430 continue; 4431 } 4432 4433 const RecordType *RC = Res->getType()->getAsRecordType(); 4434 if (!RC) { 4435 Res->Destroy(Context); 4436 return Diag(OC.LocEnd, diag::err_offsetof_record_type) 4437 << Res->getType(); 4438 } 4439 4440 // Get the decl corresponding to this. 4441 RecordDecl *RD = RC->getDecl(); 4442 FieldDecl *MemberDecl 4443 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo, 4444 LookupMemberName) 4445 .getAsDecl()); 4446 if (!MemberDecl) 4447 return Diag(BuiltinLoc, diag::err_typecheck_no_member) 4448 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd); 4449 4450 // FIXME: C++: Verify that MemberDecl isn't a static field. 4451 // FIXME: Verify that MemberDecl isn't a bitfield. 4452 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't 4453 // matter here. 4454 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd, 4455 MemberDecl->getType().getNonReferenceType()); 4456 } 4457 } 4458 4459 return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf, 4460 Context.getSizeType(), BuiltinLoc); 4461} 4462 4463 4464Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc, 4465 TypeTy *arg1, TypeTy *arg2, 4466 SourceLocation RPLoc) { 4467 QualType argT1 = QualType::getFromOpaquePtr(arg1); 4468 QualType argT2 = QualType::getFromOpaquePtr(arg2); 4469 4470 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)"); 4471 4472 return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, 4473 argT2, RPLoc); 4474} 4475 4476Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond, 4477 ExprTy *expr1, ExprTy *expr2, 4478 SourceLocation RPLoc) { 4479 Expr *CondExpr = static_cast<Expr*>(cond); 4480 Expr *LHSExpr = static_cast<Expr*>(expr1); 4481 Expr *RHSExpr = static_cast<Expr*>(expr2); 4482 4483 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 4484 4485 QualType resType; 4486 if (CondExpr->isValueDependent()) { 4487 resType = Context.DependentTy; 4488 } else { 4489 // The conditional expression is required to be a constant expression. 4490 llvm::APSInt condEval(32); 4491 SourceLocation ExpLoc; 4492 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc)) 4493 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant) 4494 << CondExpr->getSourceRange(); 4495 4496 // If the condition is > zero, then the AST type is the same as the LSHExpr. 4497 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType(); 4498 } 4499 4500 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 4501 resType, RPLoc); 4502} 4503 4504//===----------------------------------------------------------------------===// 4505// Clang Extensions. 4506//===----------------------------------------------------------------------===// 4507 4508/// ActOnBlockStart - This callback is invoked when a block literal is started. 4509void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) { 4510 // Analyze block parameters. 4511 BlockSemaInfo *BSI = new BlockSemaInfo(); 4512 4513 // Add BSI to CurBlock. 4514 BSI->PrevBlockInfo = CurBlock; 4515 CurBlock = BSI; 4516 ActiveScope = BlockScope; 4517 4518 BSI->ReturnType = 0; 4519 BSI->TheScope = BlockScope; 4520 BSI->hasBlockDeclRefExprs = false; 4521 4522 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc); 4523 PushDeclContext(BlockScope, BSI->TheDecl); 4524} 4525 4526void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) { 4527 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!"); 4528 4529 if (ParamInfo.getNumTypeObjects() == 0 4530 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) { 4531 QualType T = GetTypeForDeclarator(ParamInfo, CurScope); 4532 4533 // The type is entirely optional as well, if none, use DependentTy. 4534 if (T.isNull()) 4535 T = Context.DependentTy; 4536 4537 // The parameter list is optional, if there was none, assume (). 4538 if (!T->isFunctionType()) 4539 T = Context.getFunctionType(T, NULL, 0, 0, 0); 4540 4541 CurBlock->hasPrototype = true; 4542 CurBlock->isVariadic = false; 4543 Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType() 4544 .getTypePtr(); 4545 4546 if (!RetTy->isDependentType()) 4547 CurBlock->ReturnType = RetTy; 4548 return; 4549 } 4550 4551 // Analyze arguments to block. 4552 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function && 4553 "Not a function declarator!"); 4554 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun; 4555 4556 CurBlock->hasPrototype = FTI.hasPrototype; 4557 CurBlock->isVariadic = true; 4558 4559 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes 4560 // no arguments, not a function that takes a single void argument. 4561 if (FTI.hasPrototype && 4562 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 4563 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() && 4564 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) { 4565 // empty arg list, don't push any params. 4566 CurBlock->isVariadic = false; 4567 } else if (FTI.hasPrototype) { 4568 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) 4569 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param); 4570 CurBlock->isVariadic = FTI.isVariadic; 4571 QualType T = GetTypeForDeclarator (ParamInfo, CurScope); 4572 4573 Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType() 4574 .getTypePtr(); 4575 4576 if (!RetTy->isDependentType()) 4577 CurBlock->ReturnType = RetTy; 4578 } 4579 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size()); 4580 4581 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(), 4582 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) 4583 // If this has an identifier, add it to the scope stack. 4584 if ((*AI)->getIdentifier()) 4585 PushOnScopeChains(*AI, CurBlock->TheScope); 4586} 4587 4588/// ActOnBlockError - If there is an error parsing a block, this callback 4589/// is invoked to pop the information about the block from the action impl. 4590void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 4591 // Ensure that CurBlock is deleted. 4592 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock); 4593 4594 // Pop off CurBlock, handle nested blocks. 4595 CurBlock = CurBlock->PrevBlockInfo; 4596 4597 // FIXME: Delete the ParmVarDecl objects as well??? 4598 4599} 4600 4601/// ActOnBlockStmtExpr - This is called when the body of a block statement 4602/// literal was successfully completed. ^(int x){...} 4603Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body, 4604 Scope *CurScope) { 4605 // Ensure that CurBlock is deleted. 4606 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock); 4607 ExprOwningPtr<CompoundStmt> Body(this, static_cast<CompoundStmt*>(body)); 4608 4609 PopDeclContext(); 4610 4611 // Before poping CurBlock, set ActiveScope to this scopes parent. 4612 ActiveScope = CurBlock->TheScope->getParent(); 4613 4614 // Pop off CurBlock, handle nested blocks. 4615 CurBlock = CurBlock->PrevBlockInfo; 4616 4617 QualType RetTy = Context.VoidTy; 4618 if (BSI->ReturnType) 4619 RetTy = QualType(BSI->ReturnType, 0); 4620 4621 llvm::SmallVector<QualType, 8> ArgTypes; 4622 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i) 4623 ArgTypes.push_back(BSI->Params[i]->getType()); 4624 4625 QualType BlockTy; 4626 if (!BSI->hasPrototype) 4627 BlockTy = Context.getFunctionNoProtoType(RetTy); 4628 else 4629 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(), 4630 BSI->isVariadic, 0); 4631 4632 BlockTy = Context.getBlockPointerType(BlockTy); 4633 4634 BSI->TheDecl->setBody(Body.take()); 4635 return new (Context) BlockExpr(BSI->TheDecl, BlockTy, BSI->hasBlockDeclRefExprs); 4636} 4637 4638Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 4639 ExprTy *expr, TypeTy *type, 4640 SourceLocation RPLoc) { 4641 Expr *E = static_cast<Expr*>(expr); 4642 QualType T = QualType::getFromOpaquePtr(type); 4643 4644 InitBuiltinVaListType(); 4645 4646 // Get the va_list type 4647 QualType VaListType = Context.getBuiltinVaListType(); 4648 // Deal with implicit array decay; for example, on x86-64, 4649 // va_list is an array, but it's supposed to decay to 4650 // a pointer for va_arg. 4651 if (VaListType->isArrayType()) 4652 VaListType = Context.getArrayDecayedType(VaListType); 4653 // Make sure the input expression also decays appropriately. 4654 UsualUnaryConversions(E); 4655 4656 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible) 4657 return Diag(E->getLocStart(), 4658 diag::err_first_argument_to_va_arg_not_of_type_va_list) 4659 << E->getType() << E->getSourceRange(); 4660 4661 // FIXME: Warn if a non-POD type is passed in. 4662 4663 return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc); 4664} 4665 4666Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 4667 // The type of __null will be int or long, depending on the size of 4668 // pointers on the target. 4669 QualType Ty; 4670 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth()) 4671 Ty = Context.IntTy; 4672 else 4673 Ty = Context.LongTy; 4674 4675 return new (Context) GNUNullExpr(Ty, TokenLoc); 4676} 4677 4678bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 4679 SourceLocation Loc, 4680 QualType DstType, QualType SrcType, 4681 Expr *SrcExpr, const char *Flavor) { 4682 // Decode the result (notice that AST's are still created for extensions). 4683 bool isInvalid = false; 4684 unsigned DiagKind; 4685 switch (ConvTy) { 4686 default: assert(0 && "Unknown conversion type"); 4687 case Compatible: return false; 4688 case PointerToInt: 4689 DiagKind = diag::ext_typecheck_convert_pointer_int; 4690 break; 4691 case IntToPointer: 4692 DiagKind = diag::ext_typecheck_convert_int_pointer; 4693 break; 4694 case IncompatiblePointer: 4695 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 4696 break; 4697 case FunctionVoidPointer: 4698 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 4699 break; 4700 case CompatiblePointerDiscardsQualifiers: 4701 // If the qualifiers lost were because we were applying the 4702 // (deprecated) C++ conversion from a string literal to a char* 4703 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 4704 // Ideally, this check would be performed in 4705 // CheckPointerTypesForAssignment. However, that would require a 4706 // bit of refactoring (so that the second argument is an 4707 // expression, rather than a type), which should be done as part 4708 // of a larger effort to fix CheckPointerTypesForAssignment for 4709 // C++ semantics. 4710 if (getLangOptions().CPlusPlus && 4711 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 4712 return false; 4713 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 4714 break; 4715 case IntToBlockPointer: 4716 DiagKind = diag::err_int_to_block_pointer; 4717 break; 4718 case IncompatibleBlockPointer: 4719 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer; 4720 break; 4721 case IncompatibleObjCQualifiedId: 4722 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since 4723 // it can give a more specific diagnostic. 4724 DiagKind = diag::warn_incompatible_qualified_id; 4725 break; 4726 case IncompatibleVectors: 4727 DiagKind = diag::warn_incompatible_vectors; 4728 break; 4729 case Incompatible: 4730 DiagKind = diag::err_typecheck_convert_incompatible; 4731 isInvalid = true; 4732 break; 4733 } 4734 4735 Diag(Loc, DiagKind) << DstType << SrcType << Flavor 4736 << SrcExpr->getSourceRange(); 4737 return isInvalid; 4738} 4739 4740bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result) 4741{ 4742 Expr::EvalResult EvalResult; 4743 4744 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() || 4745 EvalResult.HasSideEffects) { 4746 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange(); 4747 4748 if (EvalResult.Diag) { 4749 // We only show the note if it's not the usual "invalid subexpression" 4750 // or if it's actually in a subexpression. 4751 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice || 4752 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens()) 4753 Diag(EvalResult.DiagLoc, EvalResult.Diag); 4754 } 4755 4756 return true; 4757 } 4758 4759 if (EvalResult.Diag) { 4760 Diag(E->getExprLoc(), diag::ext_expr_not_ice) << 4761 E->getSourceRange(); 4762 4763 // Print the reason it's not a constant. 4764 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored) 4765 Diag(EvalResult.DiagLoc, EvalResult.Diag); 4766 } 4767 4768 if (Result) 4769 *Result = EvalResult.Val.getInt(); 4770 return false; 4771} 4772