SemaExpr.cpp revision dede0c9a8cbcb2a10a2dd72be04fbd754acd8fed
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 (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(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 (ObjCMethodDecl *CurMeth = getCurMethodDecl()) 1870 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) 1871 if (ObjCImplementationDecl *ImpDecl = 1872 ObjCImplementations[ClassDecl->getIdentifier()]) 1873 Getter = ImpDecl->getInstanceMethod(Sel); 1874 1875 // Look through local category implementations associated with the class. 1876 if (!Getter) { 1877 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) { 1878 if (ObjCCategoryImpls[i]->getClassInterface() == IFace) 1879 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel); 1880 } 1881 } 1882 if (Getter) { 1883 // Check if we can reference this property. 1884 if (DiagnoseUseOfDecl(Getter, MemberLoc)) 1885 return ExprError(); 1886 } 1887 // If we found a getter then this may be a valid dot-reference, we 1888 // will look for the matching setter, in case it is needed. 1889 Selector SetterSel = 1890 SelectorTable::constructSetterName(PP.getIdentifierTable(), 1891 PP.getSelectorTable(), &Member); 1892 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel); 1893 if (!Setter) { 1894 // If this reference is in an @implementation, also check for 'private' 1895 // methods. 1896 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) 1897 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) 1898 if (ObjCImplementationDecl *ImpDecl = 1899 ObjCImplementations[ClassDecl->getIdentifier()]) 1900 Setter = ImpDecl->getInstanceMethod(SetterSel); 1901 } 1902 // Look through local category implementations associated with the class. 1903 if (!Setter) { 1904 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) { 1905 if (ObjCCategoryImpls[i]->getClassInterface() == IFace) 1906 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel); 1907 } 1908 } 1909 1910 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc)) 1911 return ExprError(); 1912 1913 if (Getter || Setter) { 1914 QualType PType; 1915 1916 if (Getter) 1917 PType = Getter->getResultType(); 1918 else { 1919 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(), 1920 E = Setter->param_end(); PI != E; ++PI) 1921 PType = (*PI)->getType(); 1922 } 1923 // FIXME: we must check that the setter has property type. 1924 return Owned(new (Context) ObjCKVCRefExpr(Getter, PType, 1925 Setter, MemberLoc, BaseExpr)); 1926 } 1927 return ExprError(Diag(MemberLoc, diag::err_property_not_found) 1928 << &Member << BaseType); 1929 } 1930 // Handle properties on qualified "id" protocols. 1931 const ObjCQualifiedIdType *QIdTy; 1932 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) { 1933 // Check protocols on qualified interfaces. 1934 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(), 1935 E = QIdTy->qual_end(); I != E; ++I) { 1936 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) { 1937 // Check the use of this declaration 1938 if (DiagnoseUseOfDecl(PD, MemberLoc)) 1939 return ExprError(); 1940 1941 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(), 1942 MemberLoc, BaseExpr)); 1943 } 1944 // Also must look for a getter name which uses property syntax. 1945 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member); 1946 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) { 1947 // Check the use of this method. 1948 if (DiagnoseUseOfDecl(OMD, MemberLoc)) 1949 return ExprError(); 1950 1951 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel, 1952 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0)); 1953 } 1954 } 1955 1956 return ExprError(Diag(MemberLoc, diag::err_property_not_found) 1957 << &Member << BaseType); 1958 } 1959 // Handle properties on ObjC 'Class' types. 1960 if (OpKind == tok::period && (BaseType == Context.getObjCClassType())) { 1961 // Also must look for a getter name which uses property syntax. 1962 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member); 1963 if (ObjCMethodDecl *MD = getCurMethodDecl()) { 1964 ObjCMethodDecl *OMD; 1965 // FIXME: need to also look locally in the implementation. 1966 if ((OMD = MD->getClassInterface()->lookupClassMethod(Sel))) { 1967 // Check the use of this method. 1968 if (DiagnoseUseOfDecl(OMD, MemberLoc)) 1969 return ExprError(); 1970 1971 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel, 1972 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0)); 1973 } 1974 } 1975 } 1976 1977 // Handle 'field access' to vectors, such as 'V.xx'. 1978 if (BaseType->isExtVectorType()) { 1979 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc); 1980 if (ret.isNull()) 1981 return ExprError(); 1982 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member, 1983 MemberLoc)); 1984 } 1985 1986 return ExprError(Diag(MemberLoc, 1987 diag::err_typecheck_member_reference_struct_union) 1988 << BaseType << BaseExpr->getSourceRange()); 1989} 1990 1991/// ConvertArgumentsForCall - Converts the arguments specified in 1992/// Args/NumArgs to the parameter types of the function FDecl with 1993/// function prototype Proto. Call is the call expression itself, and 1994/// Fn is the function expression. For a C++ member function, this 1995/// routine does not attempt to convert the object argument. Returns 1996/// true if the call is ill-formed. 1997bool 1998Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 1999 FunctionDecl *FDecl, 2000 const FunctionProtoType *Proto, 2001 Expr **Args, unsigned NumArgs, 2002 SourceLocation RParenLoc) { 2003 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 2004 // assignment, to the types of the corresponding parameter, ... 2005 unsigned NumArgsInProto = Proto->getNumArgs(); 2006 unsigned NumArgsToCheck = NumArgs; 2007 bool Invalid = false; 2008 2009 // If too few arguments are available (and we don't have default 2010 // arguments for the remaining parameters), don't make the call. 2011 if (NumArgs < NumArgsInProto) { 2012 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments()) 2013 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args) 2014 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange(); 2015 // Use default arguments for missing arguments 2016 NumArgsToCheck = NumArgsInProto; 2017 Call->setNumArgs(Context, NumArgsInProto); 2018 } 2019 2020 // If too many are passed and not variadic, error on the extras and drop 2021 // them. 2022 if (NumArgs > NumArgsInProto) { 2023 if (!Proto->isVariadic()) { 2024 Diag(Args[NumArgsInProto]->getLocStart(), 2025 diag::err_typecheck_call_too_many_args) 2026 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange() 2027 << SourceRange(Args[NumArgsInProto]->getLocStart(), 2028 Args[NumArgs-1]->getLocEnd()); 2029 // This deletes the extra arguments. 2030 Call->setNumArgs(Context, NumArgsInProto); 2031 Invalid = true; 2032 } 2033 NumArgsToCheck = NumArgsInProto; 2034 } 2035 2036 // Continue to check argument types (even if we have too few/many args). 2037 for (unsigned i = 0; i != NumArgsToCheck; i++) { 2038 QualType ProtoArgType = Proto->getArgType(i); 2039 2040 Expr *Arg; 2041 if (i < NumArgs) { 2042 Arg = Args[i]; 2043 2044 // Pass the argument. 2045 if (PerformCopyInitialization(Arg, ProtoArgType, "passing")) 2046 return true; 2047 } else 2048 // We already type-checked the argument, so we know it works. 2049 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i)); 2050 QualType ArgType = Arg->getType(); 2051 2052 Call->setArg(i, Arg); 2053 } 2054 2055 // If this is a variadic call, handle args passed through "...". 2056 if (Proto->isVariadic()) { 2057 VariadicCallType CallType = VariadicFunction; 2058 if (Fn->getType()->isBlockPointerType()) 2059 CallType = VariadicBlock; // Block 2060 else if (isa<MemberExpr>(Fn)) 2061 CallType = VariadicMethod; 2062 2063 // Promote the arguments (C99 6.5.2.2p7). 2064 for (unsigned i = NumArgsInProto; i != NumArgs; i++) { 2065 Expr *Arg = Args[i]; 2066 DefaultVariadicArgumentPromotion(Arg, CallType); 2067 Call->setArg(i, Arg); 2068 } 2069 } 2070 2071 return Invalid; 2072} 2073 2074/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 2075/// This provides the location of the left/right parens and a list of comma 2076/// locations. 2077Action::OwningExprResult 2078Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc, 2079 MultiExprArg args, 2080 SourceLocation *CommaLocs, SourceLocation RParenLoc) { 2081 unsigned NumArgs = args.size(); 2082 Expr *Fn = static_cast<Expr *>(fn.release()); 2083 Expr **Args = reinterpret_cast<Expr**>(args.release()); 2084 assert(Fn && "no function call expression"); 2085 FunctionDecl *FDecl = NULL; 2086 DeclarationName UnqualifiedName; 2087 2088 if (getLangOptions().CPlusPlus) { 2089 // Determine whether this is a dependent call inside a C++ template, 2090 // in which case we won't do any semantic analysis now. 2091 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn. 2092 bool Dependent = false; 2093 if (Fn->isTypeDependent()) 2094 Dependent = true; 2095 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs)) 2096 Dependent = true; 2097 2098 if (Dependent) 2099 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs, 2100 Context.DependentTy, RParenLoc)); 2101 2102 // Determine whether this is a call to an object (C++ [over.call.object]). 2103 if (Fn->getType()->isRecordType()) 2104 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs, 2105 CommaLocs, RParenLoc)); 2106 2107 // Determine whether this is a call to a member function. 2108 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) 2109 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) || 2110 isa<CXXMethodDecl>(MemExpr->getMemberDecl())) 2111 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs, 2112 CommaLocs, RParenLoc)); 2113 } 2114 2115 // If we're directly calling a function, get the appropriate declaration. 2116 DeclRefExpr *DRExpr = NULL; 2117 Expr *FnExpr = Fn; 2118 bool ADL = true; 2119 while (true) { 2120 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr)) 2121 FnExpr = IcExpr->getSubExpr(); 2122 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) { 2123 // Parentheses around a function disable ADL 2124 // (C++0x [basic.lookup.argdep]p1). 2125 ADL = false; 2126 FnExpr = PExpr->getSubExpr(); 2127 } else if (isa<UnaryOperator>(FnExpr) && 2128 cast<UnaryOperator>(FnExpr)->getOpcode() 2129 == UnaryOperator::AddrOf) { 2130 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr(); 2131 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) { 2132 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1). 2133 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr); 2134 break; 2135 } else if (UnresolvedFunctionNameExpr *DepName 2136 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) { 2137 UnqualifiedName = DepName->getName(); 2138 break; 2139 } else { 2140 // Any kind of name that does not refer to a declaration (or 2141 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3). 2142 ADL = false; 2143 break; 2144 } 2145 } 2146 2147 OverloadedFunctionDecl *Ovl = 0; 2148 if (DRExpr) { 2149 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()); 2150 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl()); 2151 } 2152 2153 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) { 2154 // We don't perform ADL for implicit declarations of builtins. 2155 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit()) 2156 ADL = false; 2157 2158 // We don't perform ADL in C. 2159 if (!getLangOptions().CPlusPlus) 2160 ADL = false; 2161 2162 if (Ovl || ADL) { 2163 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0, 2164 UnqualifiedName, LParenLoc, Args, 2165 NumArgs, CommaLocs, RParenLoc, ADL); 2166 if (!FDecl) 2167 return ExprError(); 2168 2169 // Update Fn to refer to the actual function selected. 2170 Expr *NewFn = 0; 2171 if (QualifiedDeclRefExpr *QDRExpr 2172 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr)) 2173 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(), 2174 QDRExpr->getLocation(), 2175 false, false, 2176 QDRExpr->getSourceRange().getBegin()); 2177 else 2178 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(), 2179 Fn->getSourceRange().getBegin()); 2180 Fn->Destroy(Context); 2181 Fn = NewFn; 2182 } 2183 } 2184 2185 // Promote the function operand. 2186 UsualUnaryConversions(Fn); 2187 2188 // Make the call expr early, before semantic checks. This guarantees cleanup 2189 // of arguments and function on error. 2190 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn, 2191 Args, NumArgs, 2192 Context.BoolTy, 2193 RParenLoc)); 2194 2195 const FunctionType *FuncT; 2196 if (!Fn->getType()->isBlockPointerType()) { 2197 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 2198 // have type pointer to function". 2199 const PointerType *PT = Fn->getType()->getAsPointerType(); 2200 if (PT == 0) 2201 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 2202 << Fn->getType() << Fn->getSourceRange()); 2203 FuncT = PT->getPointeeType()->getAsFunctionType(); 2204 } else { // This is a block call. 2205 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()-> 2206 getAsFunctionType(); 2207 } 2208 if (FuncT == 0) 2209 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 2210 << Fn->getType() << Fn->getSourceRange()); 2211 2212 // We know the result type of the call, set it. 2213 TheCall->setType(FuncT->getResultType().getNonReferenceType()); 2214 2215 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) { 2216 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs, 2217 RParenLoc)) 2218 return ExprError(); 2219 } else { 2220 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 2221 2222 // Promote the arguments (C99 6.5.2.2p6). 2223 for (unsigned i = 0; i != NumArgs; i++) { 2224 Expr *Arg = Args[i]; 2225 DefaultArgumentPromotion(Arg); 2226 TheCall->setArg(i, Arg); 2227 } 2228 } 2229 2230 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 2231 if (!Method->isStatic()) 2232 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 2233 << Fn->getSourceRange()); 2234 2235 // Do special checking on direct calls to functions. 2236 if (FDecl) 2237 return CheckFunctionCall(FDecl, TheCall.take()); 2238 2239 return Owned(TheCall.take()); 2240} 2241 2242Action::OwningExprResult 2243Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty, 2244 SourceLocation RParenLoc, ExprArg InitExpr) { 2245 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type"); 2246 QualType literalType = QualType::getFromOpaquePtr(Ty); 2247 // FIXME: put back this assert when initializers are worked out. 2248 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 2249 Expr *literalExpr = static_cast<Expr*>(InitExpr.get()); 2250 2251 if (literalType->isArrayType()) { 2252 if (literalType->isVariableArrayType()) 2253 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 2254 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())); 2255 } else if (RequireCompleteType(LParenLoc, literalType, 2256 diag::err_typecheck_decl_incomplete_type, 2257 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()))) 2258 return ExprError(); 2259 2260 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc, 2261 DeclarationName(), /*FIXME:DirectInit=*/false)) 2262 return ExprError(); 2263 2264 bool isFileScope = getCurFunctionOrMethodDecl() == 0; 2265 if (isFileScope) { // 6.5.2.5p3 2266 if (CheckForConstantInitializer(literalExpr, literalType)) 2267 return ExprError(); 2268 } 2269 InitExpr.release(); 2270 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType, 2271 literalExpr, isFileScope)); 2272} 2273 2274Action::OwningExprResult 2275Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist, 2276 InitListDesignations &Designators, 2277 SourceLocation RBraceLoc) { 2278 unsigned NumInit = initlist.size(); 2279 Expr **InitList = reinterpret_cast<Expr**>(initlist.release()); 2280 2281 // Semantic analysis for initializers is done by ActOnDeclarator() and 2282 // CheckInitializer() - it requires knowledge of the object being intialized. 2283 2284 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit, 2285 RBraceLoc); 2286 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 2287 return Owned(E); 2288} 2289 2290/// CheckCastTypes - Check type constraints for casting between types. 2291bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) { 2292 UsualUnaryConversions(castExpr); 2293 2294 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression 2295 // type needs to be scalar. 2296 if (castType->isVoidType()) { 2297 // Cast to void allows any expr type. 2298 } else if (castType->isDependentType() || castExpr->isTypeDependent()) { 2299 // We can't check any more until template instantiation time. 2300 } else if (!castType->isScalarType() && !castType->isVectorType()) { 2301 if (Context.getCanonicalType(castType).getUnqualifiedType() == 2302 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) && 2303 (castType->isStructureType() || castType->isUnionType())) { 2304 // GCC struct/union extension: allow cast to self. 2305 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar) 2306 << castType << castExpr->getSourceRange(); 2307 } else if (castType->isUnionType()) { 2308 // GCC cast to union extension 2309 RecordDecl *RD = castType->getAsRecordType()->getDecl(); 2310 RecordDecl::field_iterator Field, FieldEnd; 2311 for (Field = RD->field_begin(), FieldEnd = RD->field_end(); 2312 Field != FieldEnd; ++Field) { 2313 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() == 2314 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) { 2315 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union) 2316 << castExpr->getSourceRange(); 2317 break; 2318 } 2319 } 2320 if (Field == FieldEnd) 2321 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type) 2322 << castExpr->getType() << castExpr->getSourceRange(); 2323 } else { 2324 // Reject any other conversions to non-scalar types. 2325 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar) 2326 << castType << castExpr->getSourceRange(); 2327 } 2328 } else if (!castExpr->getType()->isScalarType() && 2329 !castExpr->getType()->isVectorType()) { 2330 return Diag(castExpr->getLocStart(), 2331 diag::err_typecheck_expect_scalar_operand) 2332 << castExpr->getType() << castExpr->getSourceRange(); 2333 } else if (castExpr->getType()->isVectorType()) { 2334 if (CheckVectorCast(TyR, castExpr->getType(), castType)) 2335 return true; 2336 } else if (castType->isVectorType()) { 2337 if (CheckVectorCast(TyR, castType, castExpr->getType())) 2338 return true; 2339 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) { 2340 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR; 2341 } 2342 return false; 2343} 2344 2345bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) { 2346 assert(VectorTy->isVectorType() && "Not a vector type!"); 2347 2348 if (Ty->isVectorType() || Ty->isIntegerType()) { 2349 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty)) 2350 return Diag(R.getBegin(), 2351 Ty->isVectorType() ? 2352 diag::err_invalid_conversion_between_vectors : 2353 diag::err_invalid_conversion_between_vector_and_integer) 2354 << VectorTy << Ty << R; 2355 } else 2356 return Diag(R.getBegin(), 2357 diag::err_invalid_conversion_between_vector_and_scalar) 2358 << VectorTy << Ty << R; 2359 2360 return false; 2361} 2362 2363Action::OwningExprResult 2364Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty, 2365 SourceLocation RParenLoc, ExprArg Op) { 2366 assert((Ty != 0) && (Op.get() != 0) && 2367 "ActOnCastExpr(): missing type or expr"); 2368 2369 Expr *castExpr = static_cast<Expr*>(Op.release()); 2370 QualType castType = QualType::getFromOpaquePtr(Ty); 2371 2372 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr)) 2373 return ExprError(); 2374 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType, 2375 LParenLoc, RParenLoc)); 2376} 2377 2378/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension. 2379/// In that case, lhs = cond. 2380/// C99 6.5.15 2381QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS, 2382 SourceLocation QuestionLoc) { 2383 UsualUnaryConversions(Cond); 2384 UsualUnaryConversions(LHS); 2385 UsualUnaryConversions(RHS); 2386 QualType CondTy = Cond->getType(); 2387 QualType LHSTy = LHS->getType(); 2388 QualType RHSTy = RHS->getType(); 2389 2390 // first, check the condition. 2391 if (!Cond->isTypeDependent()) { 2392 if (!CondTy->isScalarType()) { // C99 6.5.15p2 2393 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) 2394 << CondTy; 2395 return QualType(); 2396 } 2397 } 2398 2399 // Now check the two expressions. 2400 if ((LHS && LHS->isTypeDependent()) || (RHS && RHS->isTypeDependent())) 2401 return Context.DependentTy; 2402 2403 // If both operands have arithmetic type, do the usual arithmetic conversions 2404 // to find a common type: C99 6.5.15p3,5. 2405 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 2406 UsualArithmeticConversions(LHS, RHS); 2407 return LHS->getType(); 2408 } 2409 2410 // If both operands are the same structure or union type, the result is that 2411 // type. 2412 if (const RecordType *LHSRT = LHSTy->getAsRecordType()) { // C99 6.5.15p3 2413 if (const RecordType *RHSRT = RHSTy->getAsRecordType()) 2414 if (LHSRT->getDecl() == RHSRT->getDecl()) 2415 // "If both the operands have structure or union type, the result has 2416 // that type." This implies that CV qualifiers are dropped. 2417 return LHSTy.getUnqualifiedType(); 2418 } 2419 2420 // C99 6.5.15p5: "If both operands have void type, the result has void type." 2421 // The following || allows only one side to be void (a GCC-ism). 2422 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 2423 if (!LHSTy->isVoidType()) 2424 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void) 2425 << RHS->getSourceRange(); 2426 if (!RHSTy->isVoidType()) 2427 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void) 2428 << LHS->getSourceRange(); 2429 ImpCastExprToType(LHS, Context.VoidTy); 2430 ImpCastExprToType(RHS, Context.VoidTy); 2431 return Context.VoidTy; 2432 } 2433 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 2434 // the type of the other operand." 2435 if ((LHSTy->isPointerType() || LHSTy->isBlockPointerType() || 2436 Context.isObjCObjectPointerType(LHSTy)) && 2437 RHS->isNullPointerConstant(Context)) { 2438 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer. 2439 return LHSTy; 2440 } 2441 if ((RHSTy->isPointerType() || RHSTy->isBlockPointerType() || 2442 Context.isObjCObjectPointerType(RHSTy)) && 2443 LHS->isNullPointerConstant(Context)) { 2444 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer. 2445 return RHSTy; 2446 } 2447 2448 // Handle the case where both operands are pointers before we handle null 2449 // pointer constants in case both operands are null pointer constants. 2450 if (const PointerType *LHSPT = LHSTy->getAsPointerType()) { // C99 6.5.15p3,6 2451 if (const PointerType *RHSPT = RHSTy->getAsPointerType()) { 2452 // get the "pointed to" types 2453 QualType lhptee = LHSPT->getPointeeType(); 2454 QualType rhptee = RHSPT->getPointeeType(); 2455 2456 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 2457 if (lhptee->isVoidType() && 2458 rhptee->isIncompleteOrObjectType()) { 2459 // Figure out necessary qualifiers (C99 6.5.15p6) 2460 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers()); 2461 QualType destType = Context.getPointerType(destPointee); 2462 ImpCastExprToType(LHS, destType); // add qualifiers if necessary 2463 ImpCastExprToType(RHS, destType); // promote to void* 2464 return destType; 2465 } 2466 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 2467 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers()); 2468 QualType destType = Context.getPointerType(destPointee); 2469 ImpCastExprToType(LHS, destType); // add qualifiers if necessary 2470 ImpCastExprToType(RHS, destType); // promote to void* 2471 return destType; 2472 } 2473 2474 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 2475 // Two identical pointer types are always compatible. 2476 return LHSTy; 2477 } 2478 2479 QualType compositeType = LHSTy; 2480 2481 // If either type is an Objective-C object type then check 2482 // compatibility according to Objective-C. 2483 if (Context.isObjCObjectPointerType(LHSTy) || 2484 Context.isObjCObjectPointerType(RHSTy)) { 2485 // If both operands are interfaces and either operand can be 2486 // assigned to the other, use that type as the composite 2487 // type. This allows 2488 // xxx ? (A*) a : (B*) b 2489 // where B is a subclass of A. 2490 // 2491 // Additionally, as for assignment, if either type is 'id' 2492 // allow silent coercion. Finally, if the types are 2493 // incompatible then make sure to use 'id' as the composite 2494 // type so the result is acceptable for sending messages to. 2495 2496 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 2497 // It could return the composite type. 2498 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType(); 2499 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType(); 2500 if (LHSIface && RHSIface && 2501 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) { 2502 compositeType = LHSTy; 2503 } else if (LHSIface && RHSIface && 2504 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) { 2505 compositeType = RHSTy; 2506 } else if (Context.isObjCIdStructType(lhptee) || 2507 Context.isObjCIdStructType(rhptee)) { 2508 compositeType = Context.getObjCIdType(); 2509 } else { 2510 Diag(QuestionLoc, diag::ext_typecheck_comparison_of_distinct_pointers) 2511 << LHSTy << RHSTy 2512 << LHS->getSourceRange() << RHS->getSourceRange(); 2513 QualType incompatTy = Context.getObjCIdType(); 2514 ImpCastExprToType(LHS, incompatTy); 2515 ImpCastExprToType(RHS, incompatTy); 2516 return incompatTy; 2517 } 2518 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(), 2519 rhptee.getUnqualifiedType())) { 2520 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers) 2521 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 2522 // In this situation, we assume void* type. No especially good 2523 // reason, but this is what gcc does, and we do have to pick 2524 // to get a consistent AST. 2525 QualType incompatTy = Context.getPointerType(Context.VoidTy); 2526 ImpCastExprToType(LHS, incompatTy); 2527 ImpCastExprToType(RHS, incompatTy); 2528 return incompatTy; 2529 } 2530 // The pointer types are compatible. 2531 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to 2532 // differently qualified versions of compatible types, the result type is 2533 // a pointer to an appropriately qualified version of the *composite* 2534 // type. 2535 // FIXME: Need to calculate the composite type. 2536 // FIXME: Need to add qualifiers 2537 ImpCastExprToType(LHS, compositeType); 2538 ImpCastExprToType(RHS, compositeType); 2539 return compositeType; 2540 } 2541 } 2542 2543 // Selection between block pointer types is ok as long as they are the same. 2544 if (LHSTy->isBlockPointerType() && RHSTy->isBlockPointerType() && 2545 Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) 2546 return LHSTy; 2547 2548 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type 2549 // evaluates to "struct objc_object *" (and is handled above when comparing 2550 // id with statically typed objects). 2551 if (LHSTy->isObjCQualifiedIdType() || RHSTy->isObjCQualifiedIdType()) { 2552 // GCC allows qualified id and any Objective-C type to devolve to 2553 // id. Currently localizing to here until clear this should be 2554 // part of ObjCQualifiedIdTypesAreCompatible. 2555 if (ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true) || 2556 (LHSTy->isObjCQualifiedIdType() && 2557 Context.isObjCObjectPointerType(RHSTy)) || 2558 (RHSTy->isObjCQualifiedIdType() && 2559 Context.isObjCObjectPointerType(LHSTy))) { 2560 // FIXME: This is not the correct composite type. This only 2561 // happens to work because id can more or less be used anywhere, 2562 // however this may change the type of method sends. 2563 // FIXME: gcc adds some type-checking of the arguments and emits 2564 // (confusing) incompatible comparison warnings in some 2565 // cases. Investigate. 2566 QualType compositeType = Context.getObjCIdType(); 2567 ImpCastExprToType(LHS, compositeType); 2568 ImpCastExprToType(RHS, compositeType); 2569 return compositeType; 2570 } 2571 } 2572 2573 // Otherwise, the operands are not compatible. 2574 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 2575 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 2576 return QualType(); 2577} 2578 2579/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 2580/// in the case of a the GNU conditional expr extension. 2581Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 2582 SourceLocation ColonLoc, 2583 ExprArg Cond, ExprArg LHS, 2584 ExprArg RHS) { 2585 Expr *CondExpr = (Expr *) Cond.get(); 2586 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get(); 2587 2588 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 2589 // was the condition. 2590 bool isLHSNull = LHSExpr == 0; 2591 if (isLHSNull) 2592 LHSExpr = CondExpr; 2593 2594 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, 2595 RHSExpr, QuestionLoc); 2596 if (result.isNull()) 2597 return ExprError(); 2598 2599 Cond.release(); 2600 LHS.release(); 2601 RHS.release(); 2602 return Owned(new (Context) ConditionalOperator(CondExpr, 2603 isLHSNull ? 0 : LHSExpr, 2604 RHSExpr, result)); 2605} 2606 2607 2608// CheckPointerTypesForAssignment - This is a very tricky routine (despite 2609// being closely modeled after the C99 spec:-). The odd characteristic of this 2610// routine is it effectively iqnores the qualifiers on the top level pointee. 2611// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 2612// FIXME: add a couple examples in this comment. 2613Sema::AssignConvertType 2614Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) { 2615 QualType lhptee, rhptee; 2616 2617 // get the "pointed to" type (ignoring qualifiers at the top level) 2618 lhptee = lhsType->getAsPointerType()->getPointeeType(); 2619 rhptee = rhsType->getAsPointerType()->getPointeeType(); 2620 2621 // make sure we operate on the canonical type 2622 lhptee = Context.getCanonicalType(lhptee); 2623 rhptee = Context.getCanonicalType(rhptee); 2624 2625 AssignConvertType ConvTy = Compatible; 2626 2627 // C99 6.5.16.1p1: This following citation is common to constraints 2628 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 2629 // qualifiers of the type *pointed to* by the right; 2630 // FIXME: Handle ExtQualType 2631 if (!lhptee.isAtLeastAsQualifiedAs(rhptee)) 2632 ConvTy = CompatiblePointerDiscardsQualifiers; 2633 2634 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 2635 // incomplete type and the other is a pointer to a qualified or unqualified 2636 // version of void... 2637 if (lhptee->isVoidType()) { 2638 if (rhptee->isIncompleteOrObjectType()) 2639 return ConvTy; 2640 2641 // As an extension, we allow cast to/from void* to function pointer. 2642 assert(rhptee->isFunctionType()); 2643 return FunctionVoidPointer; 2644 } 2645 2646 if (rhptee->isVoidType()) { 2647 if (lhptee->isIncompleteOrObjectType()) 2648 return ConvTy; 2649 2650 // As an extension, we allow cast to/from void* to function pointer. 2651 assert(lhptee->isFunctionType()); 2652 return FunctionVoidPointer; 2653 } 2654 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 2655 // unqualified versions of compatible types, ... 2656 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(), 2657 rhptee.getUnqualifiedType())) 2658 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers 2659 return ConvTy; 2660} 2661 2662/// CheckBlockPointerTypesForAssignment - This routine determines whether two 2663/// block pointer types are compatible or whether a block and normal pointer 2664/// are compatible. It is more restrict than comparing two function pointer 2665// types. 2666Sema::AssignConvertType 2667Sema::CheckBlockPointerTypesForAssignment(QualType lhsType, 2668 QualType rhsType) { 2669 QualType lhptee, rhptee; 2670 2671 // get the "pointed to" type (ignoring qualifiers at the top level) 2672 lhptee = lhsType->getAsBlockPointerType()->getPointeeType(); 2673 rhptee = rhsType->getAsBlockPointerType()->getPointeeType(); 2674 2675 // make sure we operate on the canonical type 2676 lhptee = Context.getCanonicalType(lhptee); 2677 rhptee = Context.getCanonicalType(rhptee); 2678 2679 AssignConvertType ConvTy = Compatible; 2680 2681 // For blocks we enforce that qualifiers are identical. 2682 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers()) 2683 ConvTy = CompatiblePointerDiscardsQualifiers; 2684 2685 if (!Context.typesAreBlockCompatible(lhptee, rhptee)) 2686 return IncompatibleBlockPointer; 2687 return ConvTy; 2688} 2689 2690/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 2691/// has code to accommodate several GCC extensions when type checking 2692/// pointers. Here are some objectionable examples that GCC considers warnings: 2693/// 2694/// int a, *pint; 2695/// short *pshort; 2696/// struct foo *pfoo; 2697/// 2698/// pint = pshort; // warning: assignment from incompatible pointer type 2699/// a = pint; // warning: assignment makes integer from pointer without a cast 2700/// pint = a; // warning: assignment makes pointer from integer without a cast 2701/// pint = pfoo; // warning: assignment from incompatible pointer type 2702/// 2703/// As a result, the code for dealing with pointers is more complex than the 2704/// C99 spec dictates. 2705/// 2706Sema::AssignConvertType 2707Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) { 2708 // Get canonical types. We're not formatting these types, just comparing 2709 // them. 2710 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType(); 2711 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType(); 2712 2713 if (lhsType == rhsType) 2714 return Compatible; // Common case: fast path an exact match. 2715 2716 // If the left-hand side is a reference type, then we are in a 2717 // (rare!) case where we've allowed the use of references in C, 2718 // e.g., as a parameter type in a built-in function. In this case, 2719 // just make sure that the type referenced is compatible with the 2720 // right-hand side type. The caller is responsible for adjusting 2721 // lhsType so that the resulting expression does not have reference 2722 // type. 2723 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) { 2724 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) 2725 return Compatible; 2726 return Incompatible; 2727 } 2728 2729 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) { 2730 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false)) 2731 return Compatible; 2732 // Relax integer conversions like we do for pointers below. 2733 if (rhsType->isIntegerType()) 2734 return IntToPointer; 2735 if (lhsType->isIntegerType()) 2736 return PointerToInt; 2737 return IncompatibleObjCQualifiedId; 2738 } 2739 2740 if (lhsType->isVectorType() || rhsType->isVectorType()) { 2741 // For ExtVector, allow vector splats; float -> <n x float> 2742 if (const ExtVectorType *LV = lhsType->getAsExtVectorType()) 2743 if (LV->getElementType() == rhsType) 2744 return Compatible; 2745 2746 // If we are allowing lax vector conversions, and LHS and RHS are both 2747 // vectors, the total size only needs to be the same. This is a bitcast; 2748 // no bits are changed but the result type is different. 2749 if (getLangOptions().LaxVectorConversions && 2750 lhsType->isVectorType() && rhsType->isVectorType()) { 2751 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType)) 2752 return IncompatibleVectors; 2753 } 2754 return Incompatible; 2755 } 2756 2757 if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) 2758 return Compatible; 2759 2760 if (isa<PointerType>(lhsType)) { 2761 if (rhsType->isIntegerType()) 2762 return IntToPointer; 2763 2764 if (isa<PointerType>(rhsType)) 2765 return CheckPointerTypesForAssignment(lhsType, rhsType); 2766 2767 if (rhsType->getAsBlockPointerType()) { 2768 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType()) 2769 return Compatible; 2770 2771 // Treat block pointers as objects. 2772 if (getLangOptions().ObjC1 && 2773 lhsType == Context.getCanonicalType(Context.getObjCIdType())) 2774 return Compatible; 2775 } 2776 return Incompatible; 2777 } 2778 2779 if (isa<BlockPointerType>(lhsType)) { 2780 if (rhsType->isIntegerType()) 2781 return IntToBlockPointer; 2782 2783 // Treat block pointers as objects. 2784 if (getLangOptions().ObjC1 && 2785 rhsType == Context.getCanonicalType(Context.getObjCIdType())) 2786 return Compatible; 2787 2788 if (rhsType->isBlockPointerType()) 2789 return CheckBlockPointerTypesForAssignment(lhsType, rhsType); 2790 2791 if (const PointerType *RHSPT = rhsType->getAsPointerType()) { 2792 if (RHSPT->getPointeeType()->isVoidType()) 2793 return Compatible; 2794 } 2795 return Incompatible; 2796 } 2797 2798 if (isa<PointerType>(rhsType)) { 2799 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer. 2800 if (lhsType == Context.BoolTy) 2801 return Compatible; 2802 2803 if (lhsType->isIntegerType()) 2804 return PointerToInt; 2805 2806 if (isa<PointerType>(lhsType)) 2807 return CheckPointerTypesForAssignment(lhsType, rhsType); 2808 2809 if (isa<BlockPointerType>(lhsType) && 2810 rhsType->getAsPointerType()->getPointeeType()->isVoidType()) 2811 return Compatible; 2812 return Incompatible; 2813 } 2814 2815 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) { 2816 if (Context.typesAreCompatible(lhsType, rhsType)) 2817 return Compatible; 2818 } 2819 return Incompatible; 2820} 2821 2822Sema::AssignConvertType 2823Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) { 2824 if (getLangOptions().CPlusPlus) { 2825 if (!lhsType->isRecordType()) { 2826 // C++ 5.17p3: If the left operand is not of class type, the 2827 // expression is implicitly converted (C++ 4) to the 2828 // cv-unqualified type of the left operand. 2829 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(), 2830 "assigning")) 2831 return Incompatible; 2832 else 2833 return Compatible; 2834 } 2835 2836 // FIXME: Currently, we fall through and treat C++ classes like C 2837 // structures. 2838 } 2839 2840 // C99 6.5.16.1p1: the left operand is a pointer and the right is 2841 // a null pointer constant. 2842 if ((lhsType->isPointerType() || 2843 lhsType->isObjCQualifiedIdType() || 2844 lhsType->isBlockPointerType()) 2845 && rExpr->isNullPointerConstant(Context)) { 2846 ImpCastExprToType(rExpr, lhsType); 2847 return Compatible; 2848 } 2849 2850 // This check seems unnatural, however it is necessary to ensure the proper 2851 // conversion of functions/arrays. If the conversion were done for all 2852 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary 2853 // expressions that surpress this implicit conversion (&, sizeof). 2854 // 2855 // Suppress this for references: C++ 8.5.3p5. 2856 if (!lhsType->isReferenceType()) 2857 DefaultFunctionArrayConversion(rExpr); 2858 2859 Sema::AssignConvertType result = 2860 CheckAssignmentConstraints(lhsType, rExpr->getType()); 2861 2862 // C99 6.5.16.1p2: The value of the right operand is converted to the 2863 // type of the assignment expression. 2864 // CheckAssignmentConstraints allows the left-hand side to be a reference, 2865 // so that we can use references in built-in functions even in C. 2866 // The getNonReferenceType() call makes sure that the resulting expression 2867 // does not have reference type. 2868 if (rExpr->getType() != lhsType) 2869 ImpCastExprToType(rExpr, lhsType.getNonReferenceType()); 2870 return result; 2871} 2872 2873Sema::AssignConvertType 2874Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) { 2875 return CheckAssignmentConstraints(lhsType, rhsType); 2876} 2877 2878QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) { 2879 Diag(Loc, diag::err_typecheck_invalid_operands) 2880 << lex->getType() << rex->getType() 2881 << lex->getSourceRange() << rex->getSourceRange(); 2882 return QualType(); 2883} 2884 2885inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, 2886 Expr *&rex) { 2887 // For conversion purposes, we ignore any qualifiers. 2888 // For example, "const float" and "float" are equivalent. 2889 QualType lhsType = 2890 Context.getCanonicalType(lex->getType()).getUnqualifiedType(); 2891 QualType rhsType = 2892 Context.getCanonicalType(rex->getType()).getUnqualifiedType(); 2893 2894 // If the vector types are identical, return. 2895 if (lhsType == rhsType) 2896 return lhsType; 2897 2898 // Handle the case of a vector & extvector type of the same size and element 2899 // type. It would be nice if we only had one vector type someday. 2900 if (getLangOptions().LaxVectorConversions) { 2901 // FIXME: Should we warn here? 2902 if (const VectorType *LV = lhsType->getAsVectorType()) { 2903 if (const VectorType *RV = rhsType->getAsVectorType()) 2904 if (LV->getElementType() == RV->getElementType() && 2905 LV->getNumElements() == RV->getNumElements()) { 2906 return lhsType->isExtVectorType() ? lhsType : rhsType; 2907 } 2908 } 2909 } 2910 2911 // If the lhs is an extended vector and the rhs is a scalar of the same type 2912 // or a literal, promote the rhs to the vector type. 2913 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) { 2914 QualType eltType = V->getElementType(); 2915 2916 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) || 2917 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) || 2918 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) { 2919 ImpCastExprToType(rex, lhsType); 2920 return lhsType; 2921 } 2922 } 2923 2924 // If the rhs is an extended vector and the lhs is a scalar of the same type, 2925 // promote the lhs to the vector type. 2926 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) { 2927 QualType eltType = V->getElementType(); 2928 2929 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) || 2930 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) || 2931 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) { 2932 ImpCastExprToType(lex, rhsType); 2933 return rhsType; 2934 } 2935 } 2936 2937 // You cannot convert between vector values of different size. 2938 Diag(Loc, diag::err_typecheck_vector_not_convertable) 2939 << lex->getType() << rex->getType() 2940 << lex->getSourceRange() << rex->getSourceRange(); 2941 return QualType(); 2942} 2943 2944inline QualType Sema::CheckMultiplyDivideOperands( 2945 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) 2946{ 2947 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 2948 return CheckVectorOperands(Loc, lex, rex); 2949 2950 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 2951 2952 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 2953 return compType; 2954 return InvalidOperands(Loc, lex, rex); 2955} 2956 2957inline QualType Sema::CheckRemainderOperands( 2958 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) 2959{ 2960 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) { 2961 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType()) 2962 return CheckVectorOperands(Loc, lex, rex); 2963 return InvalidOperands(Loc, lex, rex); 2964 } 2965 2966 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 2967 2968 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType()) 2969 return compType; 2970 return InvalidOperands(Loc, lex, rex); 2971} 2972 2973inline QualType Sema::CheckAdditionOperands( // C99 6.5.6 2974 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) 2975{ 2976 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 2977 return CheckVectorOperands(Loc, lex, rex); 2978 2979 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 2980 2981 // handle the common case first (both operands are arithmetic). 2982 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 2983 return compType; 2984 2985 // Put any potential pointer into PExp 2986 Expr* PExp = lex, *IExp = rex; 2987 if (IExp->getType()->isPointerType()) 2988 std::swap(PExp, IExp); 2989 2990 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) { 2991 if (IExp->getType()->isIntegerType()) { 2992 // Check for arithmetic on pointers to incomplete types 2993 if (!PTy->getPointeeType()->isObjectType()) { 2994 if (PTy->getPointeeType()->isVoidType()) { 2995 if (getLangOptions().CPlusPlus) { 2996 Diag(Loc, diag::err_typecheck_pointer_arith_void_type) 2997 << lex->getSourceRange() << rex->getSourceRange(); 2998 return QualType(); 2999 } 3000 3001 // GNU extension: arithmetic on pointer to void 3002 Diag(Loc, diag::ext_gnu_void_ptr) 3003 << lex->getSourceRange() << rex->getSourceRange(); 3004 } else if (PTy->getPointeeType()->isFunctionType()) { 3005 if (getLangOptions().CPlusPlus) { 3006 Diag(Loc, diag::err_typecheck_pointer_arith_function_type) 3007 << lex->getType() << lex->getSourceRange(); 3008 return QualType(); 3009 } 3010 3011 // GNU extension: arithmetic on pointer to function 3012 Diag(Loc, diag::ext_gnu_ptr_func_arith) 3013 << lex->getType() << lex->getSourceRange(); 3014 } else { 3015 RequireCompleteType(Loc, PTy->getPointeeType(), 3016 diag::err_typecheck_arithmetic_incomplete_type, 3017 lex->getSourceRange(), SourceRange(), 3018 lex->getType()); 3019 return QualType(); 3020 } 3021 } 3022 return PExp->getType(); 3023 } 3024 } 3025 3026 return InvalidOperands(Loc, lex, rex); 3027} 3028 3029// C99 6.5.6 3030QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex, 3031 SourceLocation Loc, bool isCompAssign) { 3032 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 3033 return CheckVectorOperands(Loc, lex, rex); 3034 3035 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 3036 3037 // Enforce type constraints: C99 6.5.6p3. 3038 3039 // Handle the common case first (both operands are arithmetic). 3040 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 3041 return compType; 3042 3043 // Either ptr - int or ptr - ptr. 3044 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) { 3045 QualType lpointee = LHSPTy->getPointeeType(); 3046 3047 // The LHS must be an object type, not incomplete, function, etc. 3048 if (!lpointee->isObjectType()) { 3049 // Handle the GNU void* extension. 3050 if (lpointee->isVoidType()) { 3051 Diag(Loc, diag::ext_gnu_void_ptr) 3052 << lex->getSourceRange() << rex->getSourceRange(); 3053 } else if (lpointee->isFunctionType()) { 3054 if (getLangOptions().CPlusPlus) { 3055 Diag(Loc, diag::err_typecheck_pointer_arith_function_type) 3056 << lex->getType() << lex->getSourceRange(); 3057 return QualType(); 3058 } 3059 3060 // GNU extension: arithmetic on pointer to function 3061 Diag(Loc, diag::ext_gnu_ptr_func_arith) 3062 << lex->getType() << lex->getSourceRange(); 3063 } else { 3064 Diag(Loc, diag::err_typecheck_sub_ptr_object) 3065 << lex->getType() << lex->getSourceRange(); 3066 return QualType(); 3067 } 3068 } 3069 3070 // The result type of a pointer-int computation is the pointer type. 3071 if (rex->getType()->isIntegerType()) 3072 return lex->getType(); 3073 3074 // Handle pointer-pointer subtractions. 3075 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) { 3076 QualType rpointee = RHSPTy->getPointeeType(); 3077 3078 // RHS must be an object type, unless void (GNU). 3079 if (!rpointee->isObjectType()) { 3080 // Handle the GNU void* extension. 3081 if (rpointee->isVoidType()) { 3082 if (!lpointee->isVoidType()) 3083 Diag(Loc, diag::ext_gnu_void_ptr) 3084 << lex->getSourceRange() << rex->getSourceRange(); 3085 } else if (rpointee->isFunctionType()) { 3086 if (getLangOptions().CPlusPlus) { 3087 Diag(Loc, diag::err_typecheck_pointer_arith_function_type) 3088 << rex->getType() << rex->getSourceRange(); 3089 return QualType(); 3090 } 3091 3092 // GNU extension: arithmetic on pointer to function 3093 if (!lpointee->isFunctionType()) 3094 Diag(Loc, diag::ext_gnu_ptr_func_arith) 3095 << lex->getType() << lex->getSourceRange(); 3096 } else { 3097 Diag(Loc, diag::err_typecheck_sub_ptr_object) 3098 << rex->getType() << rex->getSourceRange(); 3099 return QualType(); 3100 } 3101 } 3102 3103 // Pointee types must be compatible. 3104 if (!Context.typesAreCompatible( 3105 Context.getCanonicalType(lpointee).getUnqualifiedType(), 3106 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 3107 Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 3108 << lex->getType() << rex->getType() 3109 << lex->getSourceRange() << rex->getSourceRange(); 3110 return QualType(); 3111 } 3112 3113 return Context.getPointerDiffType(); 3114 } 3115 } 3116 3117 return InvalidOperands(Loc, lex, rex); 3118} 3119 3120// C99 6.5.7 3121QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc, 3122 bool isCompAssign) { 3123 // C99 6.5.7p2: Each of the operands shall have integer type. 3124 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType()) 3125 return InvalidOperands(Loc, lex, rex); 3126 3127 // Shifts don't perform usual arithmetic conversions, they just do integer 3128 // promotions on each operand. C99 6.5.7p3 3129 if (!isCompAssign) 3130 UsualUnaryConversions(lex); 3131 UsualUnaryConversions(rex); 3132 3133 // "The type of the result is that of the promoted left operand." 3134 return lex->getType(); 3135} 3136 3137// C99 6.5.8 3138QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc, 3139 bool isRelational) { 3140 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 3141 return CheckVectorCompareOperands(lex, rex, Loc, isRelational); 3142 3143 // C99 6.5.8p3 / C99 6.5.9p4 3144 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 3145 UsualArithmeticConversions(lex, rex); 3146 else { 3147 UsualUnaryConversions(lex); 3148 UsualUnaryConversions(rex); 3149 } 3150 QualType lType = lex->getType(); 3151 QualType rType = rex->getType(); 3152 3153 if (!lType->isFloatingType()) { 3154 // For non-floating point types, check for self-comparisons of the form 3155 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 3156 // often indicate logic errors in the program. 3157 Expr *LHSStripped = lex->IgnoreParens(); 3158 Expr *RHSStripped = rex->IgnoreParens(); 3159 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) 3160 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) 3161 if (DRL->getDecl() == DRR->getDecl()) 3162 Diag(Loc, diag::warn_selfcomparison); 3163 3164 if (isa<CastExpr>(LHSStripped)) 3165 LHSStripped = LHSStripped->IgnoreParenCasts(); 3166 if (isa<CastExpr>(RHSStripped)) 3167 RHSStripped = RHSStripped->IgnoreParenCasts(); 3168 3169 // Warn about comparisons against a string constant (unless the other 3170 // operand is null), the user probably wants strcmp. 3171 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 3172 !RHSStripped->isNullPointerConstant(Context)) 3173 Diag(Loc, diag::warn_stringcompare) << lex->getSourceRange(); 3174 else if ((isa<StringLiteral>(RHSStripped) || 3175 isa<ObjCEncodeExpr>(RHSStripped)) && 3176 !LHSStripped->isNullPointerConstant(Context)) 3177 Diag(Loc, diag::warn_stringcompare) << rex->getSourceRange(); 3178 } 3179 3180 // The result of comparisons is 'bool' in C++, 'int' in C. 3181 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy; 3182 3183 if (isRelational) { 3184 if (lType->isRealType() && rType->isRealType()) 3185 return ResultTy; 3186 } else { 3187 // Check for comparisons of floating point operands using != and ==. 3188 if (lType->isFloatingType()) { 3189 assert(rType->isFloatingType()); 3190 CheckFloatComparison(Loc,lex,rex); 3191 } 3192 3193 if (lType->isArithmeticType() && rType->isArithmeticType()) 3194 return ResultTy; 3195 } 3196 3197 bool LHSIsNull = lex->isNullPointerConstant(Context); 3198 bool RHSIsNull = rex->isNullPointerConstant(Context); 3199 3200 // All of the following pointer related warnings are GCC extensions, except 3201 // when handling null pointer constants. One day, we can consider making them 3202 // errors (when -pedantic-errors is enabled). 3203 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2 3204 QualType LCanPointeeTy = 3205 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType()); 3206 QualType RCanPointeeTy = 3207 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType()); 3208 3209 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2 3210 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() && 3211 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 3212 RCanPointeeTy.getUnqualifiedType()) && 3213 !Context.areComparableObjCPointerTypes(lType, rType)) { 3214 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers) 3215 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 3216 } 3217 ImpCastExprToType(rex, lType); // promote the pointer to pointer 3218 return ResultTy; 3219 } 3220 // Handle block pointer types. 3221 if (lType->isBlockPointerType() && rType->isBlockPointerType()) { 3222 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType(); 3223 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType(); 3224 3225 if (!LHSIsNull && !RHSIsNull && 3226 !Context.typesAreBlockCompatible(lpointee, rpointee)) { 3227 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 3228 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 3229 } 3230 ImpCastExprToType(rex, lType); // promote the pointer to pointer 3231 return ResultTy; 3232 } 3233 // Allow block pointers to be compared with null pointer constants. 3234 if ((lType->isBlockPointerType() && rType->isPointerType()) || 3235 (lType->isPointerType() && rType->isBlockPointerType())) { 3236 if (!LHSIsNull && !RHSIsNull) { 3237 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 3238 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 3239 } 3240 ImpCastExprToType(rex, lType); // promote the pointer to pointer 3241 return ResultTy; 3242 } 3243 3244 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) { 3245 if (lType->isPointerType() || rType->isPointerType()) { 3246 const PointerType *LPT = lType->getAsPointerType(); 3247 const PointerType *RPT = rType->getAsPointerType(); 3248 bool LPtrToVoid = LPT ? 3249 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false; 3250 bool RPtrToVoid = RPT ? 3251 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false; 3252 3253 if (!LPtrToVoid && !RPtrToVoid && 3254 !Context.typesAreCompatible(lType, rType)) { 3255 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers) 3256 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 3257 ImpCastExprToType(rex, lType); 3258 return ResultTy; 3259 } 3260 ImpCastExprToType(rex, lType); 3261 return ResultTy; 3262 } 3263 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) { 3264 ImpCastExprToType(rex, lType); 3265 return ResultTy; 3266 } else { 3267 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) { 3268 Diag(Loc, diag::warn_incompatible_qualified_id_operands) 3269 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 3270 ImpCastExprToType(rex, lType); 3271 return ResultTy; 3272 } 3273 } 3274 } 3275 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) && 3276 rType->isIntegerType()) { 3277 if (!RHSIsNull) 3278 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer) 3279 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 3280 ImpCastExprToType(rex, lType); // promote the integer to pointer 3281 return ResultTy; 3282 } 3283 if (lType->isIntegerType() && 3284 (rType->isPointerType() || rType->isObjCQualifiedIdType())) { 3285 if (!LHSIsNull) 3286 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer) 3287 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 3288 ImpCastExprToType(lex, rType); // promote the integer to pointer 3289 return ResultTy; 3290 } 3291 // Handle block pointers. 3292 if (lType->isBlockPointerType() && rType->isIntegerType()) { 3293 if (!RHSIsNull) 3294 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer) 3295 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 3296 ImpCastExprToType(rex, lType); // promote the integer to pointer 3297 return ResultTy; 3298 } 3299 if (lType->isIntegerType() && rType->isBlockPointerType()) { 3300 if (!LHSIsNull) 3301 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer) 3302 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 3303 ImpCastExprToType(lex, rType); // promote the integer to pointer 3304 return ResultTy; 3305 } 3306 return InvalidOperands(Loc, lex, rex); 3307} 3308 3309/// CheckVectorCompareOperands - vector comparisons are a clang extension that 3310/// operates on extended vector types. Instead of producing an IntTy result, 3311/// like a scalar comparison, a vector comparison produces a vector of integer 3312/// types. 3313QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex, 3314 SourceLocation Loc, 3315 bool isRelational) { 3316 // Check to make sure we're operating on vectors of the same type and width, 3317 // Allowing one side to be a scalar of element type. 3318 QualType vType = CheckVectorOperands(Loc, lex, rex); 3319 if (vType.isNull()) 3320 return vType; 3321 3322 QualType lType = lex->getType(); 3323 QualType rType = rex->getType(); 3324 3325 // For non-floating point types, check for self-comparisons of the form 3326 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 3327 // often indicate logic errors in the program. 3328 if (!lType->isFloatingType()) { 3329 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens())) 3330 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens())) 3331 if (DRL->getDecl() == DRR->getDecl()) 3332 Diag(Loc, diag::warn_selfcomparison); 3333 } 3334 3335 // Check for comparisons of floating point operands using != and ==. 3336 if (!isRelational && lType->isFloatingType()) { 3337 assert (rType->isFloatingType()); 3338 CheckFloatComparison(Loc,lex,rex); 3339 } 3340 3341 // Return the type for the comparison, which is the same as vector type for 3342 // integer vectors, or an integer type of identical size and number of 3343 // elements for floating point vectors. 3344 if (lType->isIntegerType()) 3345 return lType; 3346 3347 const VectorType *VTy = lType->getAsVectorType(); 3348 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 3349 if (TypeSize == Context.getTypeSize(Context.IntTy)) 3350 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 3351 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 3352 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 3353 3354 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 3355 "Unhandled vector element size in vector compare"); 3356 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 3357} 3358 3359inline QualType Sema::CheckBitwiseOperands( 3360 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) 3361{ 3362 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 3363 return CheckVectorOperands(Loc, lex, rex); 3364 3365 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 3366 3367 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType()) 3368 return compType; 3369 return InvalidOperands(Loc, lex, rex); 3370} 3371 3372inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 3373 Expr *&lex, Expr *&rex, SourceLocation Loc) 3374{ 3375 UsualUnaryConversions(lex); 3376 UsualUnaryConversions(rex); 3377 3378 if (lex->getType()->isScalarType() && rex->getType()->isScalarType()) 3379 return Context.IntTy; 3380 return InvalidOperands(Loc, lex, rex); 3381} 3382 3383/// IsReadonlyProperty - Verify that otherwise a valid l-value expression 3384/// is a read-only property; return true if so. A readonly property expression 3385/// depends on various declarations and thus must be treated specially. 3386/// 3387static bool IsReadonlyProperty(Expr *E, Sema &S) 3388{ 3389 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) { 3390 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E); 3391 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) { 3392 QualType BaseType = PropExpr->getBase()->getType(); 3393 if (const PointerType *PTy = BaseType->getAsPointerType()) 3394 if (const ObjCInterfaceType *IFTy = 3395 PTy->getPointeeType()->getAsObjCInterfaceType()) 3396 if (ObjCInterfaceDecl *IFace = IFTy->getDecl()) 3397 if (S.isPropertyReadonly(PDecl, IFace)) 3398 return true; 3399 } 3400 } 3401 return false; 3402} 3403 3404/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 3405/// emit an error and return true. If so, return false. 3406static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 3407 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context); 3408 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S)) 3409 IsLV = Expr::MLV_ReadonlyProperty; 3410 if (IsLV == Expr::MLV_Valid) 3411 return false; 3412 3413 unsigned Diag = 0; 3414 bool NeedType = false; 3415 switch (IsLV) { // C99 6.5.16p2 3416 default: assert(0 && "Unknown result from isModifiableLvalue!"); 3417 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break; 3418 case Expr::MLV_ArrayType: 3419 Diag = diag::err_typecheck_array_not_modifiable_lvalue; 3420 NeedType = true; 3421 break; 3422 case Expr::MLV_NotObjectType: 3423 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue; 3424 NeedType = true; 3425 break; 3426 case Expr::MLV_LValueCast: 3427 Diag = diag::err_typecheck_lvalue_casts_not_supported; 3428 break; 3429 case Expr::MLV_InvalidExpression: 3430 Diag = diag::err_typecheck_expression_not_modifiable_lvalue; 3431 break; 3432 case Expr::MLV_IncompleteType: 3433 case Expr::MLV_IncompleteVoidType: 3434 return S.RequireCompleteType(Loc, E->getType(), 3435 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, 3436 E->getSourceRange()); 3437 case Expr::MLV_DuplicateVectorComponents: 3438 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 3439 break; 3440 case Expr::MLV_NotBlockQualified: 3441 Diag = diag::err_block_decl_ref_not_modifiable_lvalue; 3442 break; 3443 case Expr::MLV_ReadonlyProperty: 3444 Diag = diag::error_readonly_property_assignment; 3445 break; 3446 case Expr::MLV_NoSetterProperty: 3447 Diag = diag::error_nosetter_property_assignment; 3448 break; 3449 } 3450 3451 if (NeedType) 3452 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange(); 3453 else 3454 S.Diag(Loc, Diag) << E->getSourceRange(); 3455 return true; 3456} 3457 3458 3459 3460// C99 6.5.16.1 3461QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS, 3462 SourceLocation Loc, 3463 QualType CompoundType) { 3464 // Verify that LHS is a modifiable lvalue, and emit error if not. 3465 if (CheckForModifiableLvalue(LHS, Loc, *this)) 3466 return QualType(); 3467 3468 QualType LHSType = LHS->getType(); 3469 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType; 3470 3471 AssignConvertType ConvTy; 3472 if (CompoundType.isNull()) { 3473 // Simple assignment "x = y". 3474 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS); 3475 // Special case of NSObject attributes on c-style pointer types. 3476 if (ConvTy == IncompatiblePointer && 3477 ((Context.isObjCNSObjectType(LHSType) && 3478 Context.isObjCObjectPointerType(RHSType)) || 3479 (Context.isObjCNSObjectType(RHSType) && 3480 Context.isObjCObjectPointerType(LHSType)))) 3481 ConvTy = Compatible; 3482 3483 // If the RHS is a unary plus or minus, check to see if they = and + are 3484 // right next to each other. If so, the user may have typo'd "x =+ 4" 3485 // instead of "x += 4". 3486 Expr *RHSCheck = RHS; 3487 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 3488 RHSCheck = ICE->getSubExpr(); 3489 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 3490 if ((UO->getOpcode() == UnaryOperator::Plus || 3491 UO->getOpcode() == UnaryOperator::Minus) && 3492 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 3493 // Only if the two operators are exactly adjacent. 3494 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() && 3495 // And there is a space or other character before the subexpr of the 3496 // unary +/-. We don't want to warn on "x=-1". 3497 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 3498 UO->getSubExpr()->getLocStart().isFileID()) { 3499 Diag(Loc, diag::warn_not_compound_assign) 3500 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-") 3501 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 3502 } 3503 } 3504 } else { 3505 // Compound assignment "x += y" 3506 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType); 3507 } 3508 3509 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 3510 RHS, "assigning")) 3511 return QualType(); 3512 3513 // C99 6.5.16p3: The type of an assignment expression is the type of the 3514 // left operand unless the left operand has qualified type, in which case 3515 // it is the unqualified version of the type of the left operand. 3516 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 3517 // is converted to the type of the assignment expression (above). 3518 // C++ 5.17p1: the type of the assignment expression is that of its left 3519 // oprdu. 3520 return LHSType.getUnqualifiedType(); 3521} 3522 3523// C99 6.5.17 3524QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) { 3525 // FIXME: what is required for LHS? 3526 3527 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions. 3528 DefaultFunctionArrayConversion(RHS); 3529 return RHS->getType(); 3530} 3531 3532/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 3533/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 3534QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc, 3535 bool isInc) { 3536 if (Op->isTypeDependent()) 3537 return Context.DependentTy; 3538 3539 QualType ResType = Op->getType(); 3540 assert(!ResType.isNull() && "no type for increment/decrement expression"); 3541 3542 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) { 3543 // Decrement of bool is not allowed. 3544 if (!isInc) { 3545 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 3546 return QualType(); 3547 } 3548 // Increment of bool sets it to true, but is deprecated. 3549 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); 3550 } else if (ResType->isRealType()) { 3551 // OK! 3552 } else if (const PointerType *PT = ResType->getAsPointerType()) { 3553 // C99 6.5.2.4p2, 6.5.6p2 3554 if (PT->getPointeeType()->isObjectType()) { 3555 // Pointer to object is ok! 3556 } else if (PT->getPointeeType()->isVoidType()) { 3557 if (getLangOptions().CPlusPlus) { 3558 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type) 3559 << Op->getSourceRange(); 3560 return QualType(); 3561 } 3562 3563 // Pointer to void is a GNU extension in C. 3564 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange(); 3565 } else if (PT->getPointeeType()->isFunctionType()) { 3566 if (getLangOptions().CPlusPlus) { 3567 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type) 3568 << Op->getType() << Op->getSourceRange(); 3569 return QualType(); 3570 } 3571 3572 Diag(OpLoc, diag::ext_gnu_ptr_func_arith) 3573 << ResType << Op->getSourceRange(); 3574 } else { 3575 RequireCompleteType(OpLoc, PT->getPointeeType(), 3576 diag::err_typecheck_arithmetic_incomplete_type, 3577 Op->getSourceRange(), SourceRange(), 3578 ResType); 3579 return QualType(); 3580 } 3581 } else if (ResType->isComplexType()) { 3582 // C99 does not support ++/-- on complex types, we allow as an extension. 3583 Diag(OpLoc, diag::ext_integer_increment_complex) 3584 << ResType << Op->getSourceRange(); 3585 } else { 3586 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 3587 << ResType << Op->getSourceRange(); 3588 return QualType(); 3589 } 3590 // At this point, we know we have a real, complex or pointer type. 3591 // Now make sure the operand is a modifiable lvalue. 3592 if (CheckForModifiableLvalue(Op, OpLoc, *this)) 3593 return QualType(); 3594 return ResType; 3595} 3596 3597/// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 3598/// This routine allows us to typecheck complex/recursive expressions 3599/// where the declaration is needed for type checking. We only need to 3600/// handle cases when the expression references a function designator 3601/// or is an lvalue. Here are some examples: 3602/// - &(x) => x 3603/// - &*****f => f for f a function designator. 3604/// - &s.xx => s 3605/// - &s.zz[1].yy -> s, if zz is an array 3606/// - *(x + 1) -> x, if x is an array 3607/// - &"123"[2] -> 0 3608/// - & __real__ x -> x 3609static NamedDecl *getPrimaryDecl(Expr *E) { 3610 switch (E->getStmtClass()) { 3611 case Stmt::DeclRefExprClass: 3612 case Stmt::QualifiedDeclRefExprClass: 3613 return cast<DeclRefExpr>(E)->getDecl(); 3614 case Stmt::MemberExprClass: 3615 // Fields cannot be declared with a 'register' storage class. 3616 // &X->f is always ok, even if X is declared register. 3617 if (cast<MemberExpr>(E)->isArrow()) 3618 return 0; 3619 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 3620 case Stmt::ArraySubscriptExprClass: { 3621 // &X[4] and &4[X] refers to X if X is not a pointer. 3622 3623 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase()); 3624 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D); 3625 if (!VD || VD->getType()->isPointerType()) 3626 return 0; 3627 else 3628 return VD; 3629 } 3630 case Stmt::UnaryOperatorClass: { 3631 UnaryOperator *UO = cast<UnaryOperator>(E); 3632 3633 switch(UO->getOpcode()) { 3634 case UnaryOperator::Deref: { 3635 // *(X + 1) refers to X if X is not a pointer. 3636 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) { 3637 ValueDecl *VD = dyn_cast<ValueDecl>(D); 3638 if (!VD || VD->getType()->isPointerType()) 3639 return 0; 3640 return VD; 3641 } 3642 return 0; 3643 } 3644 case UnaryOperator::Real: 3645 case UnaryOperator::Imag: 3646 case UnaryOperator::Extension: 3647 return getPrimaryDecl(UO->getSubExpr()); 3648 default: 3649 return 0; 3650 } 3651 } 3652 case Stmt::BinaryOperatorClass: { 3653 BinaryOperator *BO = cast<BinaryOperator>(E); 3654 3655 // Handle cases involving pointer arithmetic. The result of an 3656 // Assign or AddAssign is not an lvalue so they can be ignored. 3657 3658 // (x + n) or (n + x) => x 3659 if (BO->getOpcode() == BinaryOperator::Add) { 3660 if (BO->getLHS()->getType()->isPointerType()) { 3661 return getPrimaryDecl(BO->getLHS()); 3662 } else if (BO->getRHS()->getType()->isPointerType()) { 3663 return getPrimaryDecl(BO->getRHS()); 3664 } 3665 } 3666 3667 return 0; 3668 } 3669 case Stmt::ParenExprClass: 3670 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 3671 case Stmt::ImplicitCastExprClass: 3672 // &X[4] when X is an array, has an implicit cast from array to pointer. 3673 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 3674 default: 3675 return 0; 3676 } 3677} 3678 3679/// CheckAddressOfOperand - The operand of & must be either a function 3680/// designator or an lvalue designating an object. If it is an lvalue, the 3681/// object cannot be declared with storage class register or be a bit field. 3682/// Note: The usual conversions are *not* applied to the operand of the & 3683/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 3684/// In C++, the operand might be an overloaded function name, in which case 3685/// we allow the '&' but retain the overloaded-function type. 3686QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) { 3687 if (op->isTypeDependent()) 3688 return Context.DependentTy; 3689 3690 if (getLangOptions().C99) { 3691 // Implement C99-only parts of addressof rules. 3692 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 3693 if (uOp->getOpcode() == UnaryOperator::Deref) 3694 // Per C99 6.5.3.2, the address of a deref always returns a valid result 3695 // (assuming the deref expression is valid). 3696 return uOp->getSubExpr()->getType(); 3697 } 3698 // Technically, there should be a check for array subscript 3699 // expressions here, but the result of one is always an lvalue anyway. 3700 } 3701 NamedDecl *dcl = getPrimaryDecl(op); 3702 Expr::isLvalueResult lval = op->isLvalue(Context); 3703 3704 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1 3705 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators 3706 // FIXME: emit more specific diag... 3707 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 3708 << op->getSourceRange(); 3709 return QualType(); 3710 } 3711 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1 3712 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) { 3713 if (Field->isBitField()) { 3714 Diag(OpLoc, diag::err_typecheck_address_of) 3715 << "bit-field" << op->getSourceRange(); 3716 return QualType(); 3717 } 3718 } 3719 // Check for Apple extension for accessing vector components. 3720 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) && 3721 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){ 3722 Diag(OpLoc, diag::err_typecheck_address_of) 3723 << "vector element" << op->getSourceRange(); 3724 return QualType(); 3725 } else if (dcl) { // C99 6.5.3.2p1 3726 // We have an lvalue with a decl. Make sure the decl is not declared 3727 // with the register storage-class specifier. 3728 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 3729 if (vd->getStorageClass() == VarDecl::Register) { 3730 Diag(OpLoc, diag::err_typecheck_address_of) 3731 << "register variable" << op->getSourceRange(); 3732 return QualType(); 3733 } 3734 } else if (isa<OverloadedFunctionDecl>(dcl)) { 3735 return Context.OverloadTy; 3736 } else if (isa<FieldDecl>(dcl)) { 3737 // Okay: we can take the address of a field. 3738 // Could be a pointer to member, though, if there is an explicit 3739 // scope qualifier for the class. 3740 if (isa<QualifiedDeclRefExpr>(op)) { 3741 DeclContext *Ctx = dcl->getDeclContext(); 3742 if (Ctx && Ctx->isRecord()) 3743 return Context.getMemberPointerType(op->getType(), 3744 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 3745 } 3746 } else if (isa<FunctionDecl>(dcl)) { 3747 // Okay: we can take the address of a function. 3748 // As above. 3749 if (isa<QualifiedDeclRefExpr>(op)) { 3750 DeclContext *Ctx = dcl->getDeclContext(); 3751 if (Ctx && Ctx->isRecord()) 3752 return Context.getMemberPointerType(op->getType(), 3753 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 3754 } 3755 } 3756 else 3757 assert(0 && "Unknown/unexpected decl type"); 3758 } 3759 3760 // If the operand has type "type", the result has type "pointer to type". 3761 return Context.getPointerType(op->getType()); 3762} 3763 3764QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) { 3765 if (Op->isTypeDependent()) 3766 return Context.DependentTy; 3767 3768 UsualUnaryConversions(Op); 3769 QualType Ty = Op->getType(); 3770 3771 // Note that per both C89 and C99, this is always legal, even if ptype is an 3772 // incomplete type or void. It would be possible to warn about dereferencing 3773 // a void pointer, but it's completely well-defined, and such a warning is 3774 // unlikely to catch any mistakes. 3775 if (const PointerType *PT = Ty->getAsPointerType()) 3776 return PT->getPointeeType(); 3777 3778 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 3779 << Ty << Op->getSourceRange(); 3780 return QualType(); 3781} 3782 3783static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode( 3784 tok::TokenKind Kind) { 3785 BinaryOperator::Opcode Opc; 3786 switch (Kind) { 3787 default: assert(0 && "Unknown binop!"); 3788 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break; 3789 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break; 3790 case tok::star: Opc = BinaryOperator::Mul; break; 3791 case tok::slash: Opc = BinaryOperator::Div; break; 3792 case tok::percent: Opc = BinaryOperator::Rem; break; 3793 case tok::plus: Opc = BinaryOperator::Add; break; 3794 case tok::minus: Opc = BinaryOperator::Sub; break; 3795 case tok::lessless: Opc = BinaryOperator::Shl; break; 3796 case tok::greatergreater: Opc = BinaryOperator::Shr; break; 3797 case tok::lessequal: Opc = BinaryOperator::LE; break; 3798 case tok::less: Opc = BinaryOperator::LT; break; 3799 case tok::greaterequal: Opc = BinaryOperator::GE; break; 3800 case tok::greater: Opc = BinaryOperator::GT; break; 3801 case tok::exclaimequal: Opc = BinaryOperator::NE; break; 3802 case tok::equalequal: Opc = BinaryOperator::EQ; break; 3803 case tok::amp: Opc = BinaryOperator::And; break; 3804 case tok::caret: Opc = BinaryOperator::Xor; break; 3805 case tok::pipe: Opc = BinaryOperator::Or; break; 3806 case tok::ampamp: Opc = BinaryOperator::LAnd; break; 3807 case tok::pipepipe: Opc = BinaryOperator::LOr; break; 3808 case tok::equal: Opc = BinaryOperator::Assign; break; 3809 case tok::starequal: Opc = BinaryOperator::MulAssign; break; 3810 case tok::slashequal: Opc = BinaryOperator::DivAssign; break; 3811 case tok::percentequal: Opc = BinaryOperator::RemAssign; break; 3812 case tok::plusequal: Opc = BinaryOperator::AddAssign; break; 3813 case tok::minusequal: Opc = BinaryOperator::SubAssign; break; 3814 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break; 3815 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break; 3816 case tok::ampequal: Opc = BinaryOperator::AndAssign; break; 3817 case tok::caretequal: Opc = BinaryOperator::XorAssign; break; 3818 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break; 3819 case tok::comma: Opc = BinaryOperator::Comma; break; 3820 } 3821 return Opc; 3822} 3823 3824static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode( 3825 tok::TokenKind Kind) { 3826 UnaryOperator::Opcode Opc; 3827 switch (Kind) { 3828 default: assert(0 && "Unknown unary op!"); 3829 case tok::plusplus: Opc = UnaryOperator::PreInc; break; 3830 case tok::minusminus: Opc = UnaryOperator::PreDec; break; 3831 case tok::amp: Opc = UnaryOperator::AddrOf; break; 3832 case tok::star: Opc = UnaryOperator::Deref; break; 3833 case tok::plus: Opc = UnaryOperator::Plus; break; 3834 case tok::minus: Opc = UnaryOperator::Minus; break; 3835 case tok::tilde: Opc = UnaryOperator::Not; break; 3836 case tok::exclaim: Opc = UnaryOperator::LNot; break; 3837 case tok::kw___real: Opc = UnaryOperator::Real; break; 3838 case tok::kw___imag: Opc = UnaryOperator::Imag; break; 3839 case tok::kw___extension__: Opc = UnaryOperator::Extension; break; 3840 } 3841 return Opc; 3842} 3843 3844/// CreateBuiltinBinOp - Creates a new built-in binary operation with 3845/// operator @p Opc at location @c TokLoc. This routine only supports 3846/// built-in operations; ActOnBinOp handles overloaded operators. 3847Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 3848 unsigned Op, 3849 Expr *lhs, Expr *rhs) { 3850 QualType ResultTy; // Result type of the binary operator. 3851 QualType CompTy; // Computation type for compound assignments (e.g. '+=') 3852 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op; 3853 3854 switch (Opc) { 3855 default: 3856 assert(0 && "Unknown binary expr!"); 3857 case BinaryOperator::Assign: 3858 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType()); 3859 break; 3860 case BinaryOperator::PtrMemD: 3861 case BinaryOperator::PtrMemI: 3862 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc, 3863 Opc == BinaryOperator::PtrMemI); 3864 break; 3865 case BinaryOperator::Mul: 3866 case BinaryOperator::Div: 3867 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc); 3868 break; 3869 case BinaryOperator::Rem: 3870 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc); 3871 break; 3872 case BinaryOperator::Add: 3873 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc); 3874 break; 3875 case BinaryOperator::Sub: 3876 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc); 3877 break; 3878 case BinaryOperator::Shl: 3879 case BinaryOperator::Shr: 3880 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc); 3881 break; 3882 case BinaryOperator::LE: 3883 case BinaryOperator::LT: 3884 case BinaryOperator::GE: 3885 case BinaryOperator::GT: 3886 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true); 3887 break; 3888 case BinaryOperator::EQ: 3889 case BinaryOperator::NE: 3890 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false); 3891 break; 3892 case BinaryOperator::And: 3893 case BinaryOperator::Xor: 3894 case BinaryOperator::Or: 3895 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc); 3896 break; 3897 case BinaryOperator::LAnd: 3898 case BinaryOperator::LOr: 3899 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc); 3900 break; 3901 case BinaryOperator::MulAssign: 3902 case BinaryOperator::DivAssign: 3903 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true); 3904 if (!CompTy.isNull()) 3905 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy); 3906 break; 3907 case BinaryOperator::RemAssign: 3908 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true); 3909 if (!CompTy.isNull()) 3910 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy); 3911 break; 3912 case BinaryOperator::AddAssign: 3913 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true); 3914 if (!CompTy.isNull()) 3915 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy); 3916 break; 3917 case BinaryOperator::SubAssign: 3918 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true); 3919 if (!CompTy.isNull()) 3920 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy); 3921 break; 3922 case BinaryOperator::ShlAssign: 3923 case BinaryOperator::ShrAssign: 3924 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true); 3925 if (!CompTy.isNull()) 3926 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy); 3927 break; 3928 case BinaryOperator::AndAssign: 3929 case BinaryOperator::XorAssign: 3930 case BinaryOperator::OrAssign: 3931 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true); 3932 if (!CompTy.isNull()) 3933 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy); 3934 break; 3935 case BinaryOperator::Comma: 3936 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc); 3937 break; 3938 } 3939 if (ResultTy.isNull()) 3940 return ExprError(); 3941 if (CompTy.isNull()) 3942 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc)); 3943 else 3944 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy, 3945 CompTy, OpLoc)); 3946} 3947 3948// Binary Operators. 'Tok' is the token for the operator. 3949Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 3950 tok::TokenKind Kind, 3951 ExprArg LHS, ExprArg RHS) { 3952 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind); 3953 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release(); 3954 3955 assert((lhs != 0) && "ActOnBinOp(): missing left expression"); 3956 assert((rhs != 0) && "ActOnBinOp(): missing right expression"); 3957 3958 // If either expression is type-dependent, just build the AST. 3959 // FIXME: We'll need to perform some caching of the result of name 3960 // lookup for operator+. 3961 if (lhs->isTypeDependent() || rhs->isTypeDependent()) { 3962 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) 3963 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, 3964 Context.DependentTy, 3965 Context.DependentTy, TokLoc)); 3966 else 3967 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, 3968 Context.DependentTy, TokLoc)); 3969 } 3970 3971 if (getLangOptions().CPlusPlus && Opc != BinaryOperator::PtrMemD && 3972 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() || 3973 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) { 3974 // If this is one of the assignment operators, we only perform 3975 // overload resolution if the left-hand side is a class or 3976 // enumeration type (C++ [expr.ass]p3). 3977 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign && 3978 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) { 3979 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs); 3980 } 3981 3982 // Determine which overloaded operator we're dealing with. 3983 static const OverloadedOperatorKind OverOps[] = { 3984 // Overloading .* is not possible. 3985 static_cast<OverloadedOperatorKind>(0), OO_ArrowStar, 3986 OO_Star, OO_Slash, OO_Percent, 3987 OO_Plus, OO_Minus, 3988 OO_LessLess, OO_GreaterGreater, 3989 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual, 3990 OO_EqualEqual, OO_ExclaimEqual, 3991 OO_Amp, 3992 OO_Caret, 3993 OO_Pipe, 3994 OO_AmpAmp, 3995 OO_PipePipe, 3996 OO_Equal, OO_StarEqual, 3997 OO_SlashEqual, OO_PercentEqual, 3998 OO_PlusEqual, OO_MinusEqual, 3999 OO_LessLessEqual, OO_GreaterGreaterEqual, 4000 OO_AmpEqual, OO_CaretEqual, 4001 OO_PipeEqual, 4002 OO_Comma 4003 }; 4004 OverloadedOperatorKind OverOp = OverOps[Opc]; 4005 4006 // Add the appropriate overloaded operators (C++ [over.match.oper]) 4007 // to the candidate set. 4008 OverloadCandidateSet CandidateSet; 4009 Expr *Args[2] = { lhs, rhs }; 4010 if (AddOperatorCandidates(OverOp, S, TokLoc, Args, 2, CandidateSet)) 4011 return ExprError(); 4012 4013 // Perform overload resolution. 4014 OverloadCandidateSet::iterator Best; 4015 switch (BestViableFunction(CandidateSet, Best)) { 4016 case OR_Success: { 4017 // We found a built-in operator or an overloaded operator. 4018 FunctionDecl *FnDecl = Best->Function; 4019 4020 if (FnDecl) { 4021 // We matched an overloaded operator. Build a call to that 4022 // operator. 4023 4024 // Convert the arguments. 4025 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 4026 if (PerformObjectArgumentInitialization(lhs, Method) || 4027 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(), 4028 "passing")) 4029 return ExprError(); 4030 } else { 4031 // Convert the arguments. 4032 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(), 4033 "passing") || 4034 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(), 4035 "passing")) 4036 return ExprError(); 4037 } 4038 4039 // Determine the result type 4040 QualType ResultTy 4041 = FnDecl->getType()->getAsFunctionType()->getResultType(); 4042 ResultTy = ResultTy.getNonReferenceType(); 4043 4044 // Build the actual expression node. 4045 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(), 4046 SourceLocation()); 4047 UsualUnaryConversions(FnExpr); 4048 4049 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2, 4050 ResultTy, TokLoc)); 4051 } else { 4052 // We matched a built-in operator. Convert the arguments, then 4053 // break out so that we will build the appropriate built-in 4054 // operator node. 4055 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0], 4056 Best->Conversions[0], "passing") || 4057 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1], 4058 Best->Conversions[1], "passing")) 4059 return ExprError(); 4060 4061 break; 4062 } 4063 } 4064 4065 case OR_No_Viable_Function: 4066 // No viable function; fall through to handling this as a 4067 // built-in operator, which will produce an error message for us. 4068 break; 4069 4070 case OR_Ambiguous: 4071 Diag(TokLoc, diag::err_ovl_ambiguous_oper) 4072 << BinaryOperator::getOpcodeStr(Opc) 4073 << lhs->getSourceRange() << rhs->getSourceRange(); 4074 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 4075 return ExprError(); 4076 4077 case OR_Deleted: 4078 Diag(TokLoc, diag::err_ovl_deleted_oper) 4079 << Best->Function->isDeleted() 4080 << BinaryOperator::getOpcodeStr(Opc) 4081 << lhs->getSourceRange() << rhs->getSourceRange(); 4082 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 4083 return ExprError(); 4084 } 4085 4086 // Either we found no viable overloaded operator or we matched a 4087 // built-in operator. In either case, fall through to trying to 4088 // build a built-in operation. 4089 } 4090 4091 // Build a built-in binary operation. 4092 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs); 4093} 4094 4095// Unary Operators. 'Tok' is the token for the operator. 4096Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 4097 tok::TokenKind Op, ExprArg input) { 4098 // FIXME: Input is modified later, but smart pointer not reassigned. 4099 Expr *Input = (Expr*)input.get(); 4100 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op); 4101 4102 if (getLangOptions().CPlusPlus && 4103 (Input->getType()->isRecordType() 4104 || Input->getType()->isEnumeralType())) { 4105 // Determine which overloaded operator we're dealing with. 4106 static const OverloadedOperatorKind OverOps[] = { 4107 OO_None, OO_None, 4108 OO_PlusPlus, OO_MinusMinus, 4109 OO_Amp, OO_Star, 4110 OO_Plus, OO_Minus, 4111 OO_Tilde, OO_Exclaim, 4112 OO_None, OO_None, 4113 OO_None, 4114 OO_None 4115 }; 4116 OverloadedOperatorKind OverOp = OverOps[Opc]; 4117 4118 // Add the appropriate overloaded operators (C++ [over.match.oper]) 4119 // to the candidate set. 4120 OverloadCandidateSet CandidateSet; 4121 if (OverOp != OO_None && 4122 AddOperatorCandidates(OverOp, S, OpLoc, &Input, 1, CandidateSet)) 4123 return ExprError(); 4124 4125 // Perform overload resolution. 4126 OverloadCandidateSet::iterator Best; 4127 switch (BestViableFunction(CandidateSet, Best)) { 4128 case OR_Success: { 4129 // We found a built-in operator or an overloaded operator. 4130 FunctionDecl *FnDecl = Best->Function; 4131 4132 if (FnDecl) { 4133 // We matched an overloaded operator. Build a call to that 4134 // operator. 4135 4136 // Convert the arguments. 4137 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 4138 if (PerformObjectArgumentInitialization(Input, Method)) 4139 return ExprError(); 4140 } else { 4141 // Convert the arguments. 4142 if (PerformCopyInitialization(Input, 4143 FnDecl->getParamDecl(0)->getType(), 4144 "passing")) 4145 return ExprError(); 4146 } 4147 4148 // Determine the result type 4149 QualType ResultTy 4150 = FnDecl->getType()->getAsFunctionType()->getResultType(); 4151 ResultTy = ResultTy.getNonReferenceType(); 4152 4153 // Build the actual expression node. 4154 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(), 4155 SourceLocation()); 4156 UsualUnaryConversions(FnExpr); 4157 4158 input.release(); 4159 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, &Input, 4160 1, ResultTy, OpLoc)); 4161 } else { 4162 // We matched a built-in operator. Convert the arguments, then 4163 // break out so that we will build the appropriate built-in 4164 // operator node. 4165 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 4166 Best->Conversions[0], "passing")) 4167 return ExprError(); 4168 4169 break; 4170 } 4171 } 4172 4173 case OR_No_Viable_Function: 4174 // No viable function; fall through to handling this as a 4175 // built-in operator, which will produce an error message for us. 4176 break; 4177 4178 case OR_Ambiguous: 4179 Diag(OpLoc, diag::err_ovl_ambiguous_oper) 4180 << UnaryOperator::getOpcodeStr(Opc) 4181 << Input->getSourceRange(); 4182 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 4183 return ExprError(); 4184 4185 case OR_Deleted: 4186 Diag(OpLoc, diag::err_ovl_deleted_oper) 4187 << Best->Function->isDeleted() 4188 << UnaryOperator::getOpcodeStr(Opc) 4189 << Input->getSourceRange(); 4190 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 4191 return ExprError(); 4192 } 4193 4194 // Either we found no viable overloaded operator or we matched a 4195 // built-in operator. In either case, fall through to trying to 4196 // build a built-in operation. 4197 } 4198 4199 QualType resultType; 4200 switch (Opc) { 4201 default: 4202 assert(0 && "Unimplemented unary expr!"); 4203 case UnaryOperator::PreInc: 4204 case UnaryOperator::PreDec: 4205 resultType = CheckIncrementDecrementOperand(Input, OpLoc, 4206 Opc == UnaryOperator::PreInc); 4207 break; 4208 case UnaryOperator::AddrOf: 4209 resultType = CheckAddressOfOperand(Input, OpLoc); 4210 break; 4211 case UnaryOperator::Deref: 4212 DefaultFunctionArrayConversion(Input); 4213 resultType = CheckIndirectionOperand(Input, OpLoc); 4214 break; 4215 case UnaryOperator::Plus: 4216 case UnaryOperator::Minus: 4217 UsualUnaryConversions(Input); 4218 resultType = Input->getType(); 4219 if (resultType->isDependentType()) 4220 break; 4221 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 4222 break; 4223 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7 4224 resultType->isEnumeralType()) 4225 break; 4226 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6 4227 Opc == UnaryOperator::Plus && 4228 resultType->isPointerType()) 4229 break; 4230 4231 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 4232 << resultType << Input->getSourceRange()); 4233 case UnaryOperator::Not: // bitwise complement 4234 UsualUnaryConversions(Input); 4235 resultType = Input->getType(); 4236 if (resultType->isDependentType()) 4237 break; 4238 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 4239 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 4240 // C99 does not support '~' for complex conjugation. 4241 Diag(OpLoc, diag::ext_integer_complement_complex) 4242 << resultType << Input->getSourceRange(); 4243 else if (!resultType->isIntegerType()) 4244 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 4245 << resultType << Input->getSourceRange()); 4246 break; 4247 case UnaryOperator::LNot: // logical negation 4248 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 4249 DefaultFunctionArrayConversion(Input); 4250 resultType = Input->getType(); 4251 if (resultType->isDependentType()) 4252 break; 4253 if (!resultType->isScalarType()) // C99 6.5.3.3p1 4254 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 4255 << resultType << Input->getSourceRange()); 4256 // LNot always has type int. C99 6.5.3.3p5. 4257 // In C++, it's bool. C++ 5.3.1p8 4258 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy; 4259 break; 4260 case UnaryOperator::Real: 4261 case UnaryOperator::Imag: 4262 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real); 4263 break; 4264 case UnaryOperator::Extension: 4265 resultType = Input->getType(); 4266 break; 4267 } 4268 if (resultType.isNull()) 4269 return ExprError(); 4270 input.release(); 4271 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc)); 4272} 4273 4274/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 4275Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, 4276 SourceLocation LabLoc, 4277 IdentifierInfo *LabelII) { 4278 // Look up the record for this label identifier. 4279 llvm::DenseMap<IdentifierInfo*, Action::StmtTy*>::iterator I = 4280 ActiveScope->LabelMap.find(LabelII); 4281 4282 LabelStmt *LabelDecl; 4283 4284 // If we haven't seen this label yet, create a forward reference. It 4285 // will be validated and/or cleaned up in ActOnFinishFunctionBody. 4286 if (I == ActiveScope->LabelMap.end()) { 4287 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0); 4288 4289 ActiveScope->LabelMap.insert(std::make_pair(LabelII, LabelDecl)); 4290 } else 4291 LabelDecl = static_cast<LabelStmt *>(I->second); 4292 4293 // Create the AST node. The address of a label always has type 'void*'. 4294 return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl, 4295 Context.getPointerType(Context.VoidTy)); 4296} 4297 4298Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt, 4299 SourceLocation RPLoc) { // "({..})" 4300 Stmt *SubStmt = static_cast<Stmt*>(substmt); 4301 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 4302 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 4303 4304 bool isFileScope = getCurFunctionOrMethodDecl() == 0; 4305 if (isFileScope) { 4306 return Diag(LPLoc, diag::err_stmtexpr_file_scope); 4307 } 4308 4309 // FIXME: there are a variety of strange constraints to enforce here, for 4310 // example, it is not possible to goto into a stmt expression apparently. 4311 // More semantic analysis is needed. 4312 4313 // FIXME: the last statement in the compount stmt has its value used. We 4314 // should not warn about it being unused. 4315 4316 // If there are sub stmts in the compound stmt, take the type of the last one 4317 // as the type of the stmtexpr. 4318 QualType Ty = Context.VoidTy; 4319 4320 if (!Compound->body_empty()) { 4321 Stmt *LastStmt = Compound->body_back(); 4322 // If LastStmt is a label, skip down through into the body. 4323 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) 4324 LastStmt = Label->getSubStmt(); 4325 4326 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) 4327 Ty = LastExpr->getType(); 4328 } 4329 4330 return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 4331} 4332 4333Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 4334 SourceLocation BuiltinLoc, 4335 SourceLocation TypeLoc, 4336 TypeTy *argty, 4337 OffsetOfComponent *CompPtr, 4338 unsigned NumComponents, 4339 SourceLocation RPLoc) { 4340 QualType ArgTy = QualType::getFromOpaquePtr(argty); 4341 assert(!ArgTy.isNull() && "Missing type argument!"); 4342 4343 bool Dependent = ArgTy->isDependentType(); 4344 4345 // We must have at least one component that refers to the type, and the first 4346 // one is known to be a field designator. Verify that the ArgTy represents 4347 // a struct/union/class. 4348 if (!Dependent && !ArgTy->isRecordType()) 4349 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy; 4350 4351 // Otherwise, create a null pointer as the base, and iteratively process 4352 // the offsetof designators. 4353 QualType ArgTyPtr = Context.getPointerType(ArgTy); 4354 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr); 4355 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref, 4356 ArgTy, SourceLocation()); 4357 4358 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 4359 // GCC extension, diagnose them. 4360 // FIXME: This diagnostic isn't actually visible because the location is in 4361 // a system header! 4362 if (NumComponents != 1) 4363 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 4364 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); 4365 4366 if (!Dependent) { 4367 // FIXME: Dependent case loses a lot of information here. And probably 4368 // leaks like a sieve. 4369 for (unsigned i = 0; i != NumComponents; ++i) { 4370 const OffsetOfComponent &OC = CompPtr[i]; 4371 if (OC.isBrackets) { 4372 // Offset of an array sub-field. TODO: Should we allow vector elements? 4373 const ArrayType *AT = Context.getAsArrayType(Res->getType()); 4374 if (!AT) { 4375 Res->Destroy(Context); 4376 return Diag(OC.LocEnd, diag::err_offsetof_array_type) 4377 << Res->getType(); 4378 } 4379 4380 // FIXME: C++: Verify that operator[] isn't overloaded. 4381 4382 // Promote the array so it looks more like a normal array subscript 4383 // expression. 4384 DefaultFunctionArrayConversion(Res); 4385 4386 // C99 6.5.2.1p1 4387 Expr *Idx = static_cast<Expr*>(OC.U.E); 4388 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType()) 4389 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript) 4390 << Idx->getSourceRange(); 4391 4392 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(), 4393 OC.LocEnd); 4394 continue; 4395 } 4396 4397 const RecordType *RC = Res->getType()->getAsRecordType(); 4398 if (!RC) { 4399 Res->Destroy(Context); 4400 return Diag(OC.LocEnd, diag::err_offsetof_record_type) 4401 << Res->getType(); 4402 } 4403 4404 // Get the decl corresponding to this. 4405 RecordDecl *RD = RC->getDecl(); 4406 FieldDecl *MemberDecl 4407 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo, 4408 LookupMemberName) 4409 .getAsDecl()); 4410 if (!MemberDecl) 4411 return Diag(BuiltinLoc, diag::err_typecheck_no_member) 4412 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd); 4413 4414 // FIXME: C++: Verify that MemberDecl isn't a static field. 4415 // FIXME: Verify that MemberDecl isn't a bitfield. 4416 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't 4417 // matter here. 4418 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd, 4419 MemberDecl->getType().getNonReferenceType()); 4420 } 4421 } 4422 4423 return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf, 4424 Context.getSizeType(), BuiltinLoc); 4425} 4426 4427 4428Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc, 4429 TypeTy *arg1, TypeTy *arg2, 4430 SourceLocation RPLoc) { 4431 QualType argT1 = QualType::getFromOpaquePtr(arg1); 4432 QualType argT2 = QualType::getFromOpaquePtr(arg2); 4433 4434 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)"); 4435 4436 return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, 4437 argT2, RPLoc); 4438} 4439 4440Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond, 4441 ExprTy *expr1, ExprTy *expr2, 4442 SourceLocation RPLoc) { 4443 Expr *CondExpr = static_cast<Expr*>(cond); 4444 Expr *LHSExpr = static_cast<Expr*>(expr1); 4445 Expr *RHSExpr = static_cast<Expr*>(expr2); 4446 4447 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 4448 4449 QualType resType; 4450 if (CondExpr->isValueDependent()) { 4451 resType = Context.DependentTy; 4452 } else { 4453 // The conditional expression is required to be a constant expression. 4454 llvm::APSInt condEval(32); 4455 SourceLocation ExpLoc; 4456 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc)) 4457 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant) 4458 << CondExpr->getSourceRange(); 4459 4460 // If the condition is > zero, then the AST type is the same as the LSHExpr. 4461 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType(); 4462 } 4463 4464 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 4465 resType, RPLoc); 4466} 4467 4468//===----------------------------------------------------------------------===// 4469// Clang Extensions. 4470//===----------------------------------------------------------------------===// 4471 4472/// ActOnBlockStart - This callback is invoked when a block literal is started. 4473void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) { 4474 // Analyze block parameters. 4475 BlockSemaInfo *BSI = new BlockSemaInfo(); 4476 4477 // Add BSI to CurBlock. 4478 BSI->PrevBlockInfo = CurBlock; 4479 CurBlock = BSI; 4480 ActiveScope = BlockScope; 4481 4482 BSI->ReturnType = 0; 4483 BSI->TheScope = BlockScope; 4484 BSI->hasBlockDeclRefExprs = false; 4485 4486 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc); 4487 PushDeclContext(BlockScope, BSI->TheDecl); 4488} 4489 4490void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) { 4491 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!"); 4492 4493 if (ParamInfo.getNumTypeObjects() == 0 4494 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) { 4495 QualType T = GetTypeForDeclarator(ParamInfo, CurScope); 4496 4497 // The type is entirely optional as well, if none, use DependentTy. 4498 if (T.isNull()) 4499 T = Context.DependentTy; 4500 4501 // The parameter list is optional, if there was none, assume (). 4502 if (!T->isFunctionType()) 4503 T = Context.getFunctionType(T, NULL, 0, 0, 0); 4504 4505 CurBlock->hasPrototype = true; 4506 CurBlock->isVariadic = false; 4507 Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType() 4508 .getTypePtr(); 4509 4510 if (!RetTy->isDependentType()) 4511 CurBlock->ReturnType = RetTy; 4512 return; 4513 } 4514 4515 // Analyze arguments to block. 4516 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function && 4517 "Not a function declarator!"); 4518 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun; 4519 4520 CurBlock->hasPrototype = FTI.hasPrototype; 4521 CurBlock->isVariadic = true; 4522 4523 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes 4524 // no arguments, not a function that takes a single void argument. 4525 if (FTI.hasPrototype && 4526 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 4527 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() && 4528 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) { 4529 // empty arg list, don't push any params. 4530 CurBlock->isVariadic = false; 4531 } else if (FTI.hasPrototype) { 4532 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) 4533 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param); 4534 CurBlock->isVariadic = FTI.isVariadic; 4535 QualType T = GetTypeForDeclarator (ParamInfo, CurScope); 4536 4537 Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType() 4538 .getTypePtr(); 4539 4540 if (!RetTy->isDependentType()) 4541 CurBlock->ReturnType = RetTy; 4542 } 4543 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size()); 4544 4545 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(), 4546 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) 4547 // If this has an identifier, add it to the scope stack. 4548 if ((*AI)->getIdentifier()) 4549 PushOnScopeChains(*AI, CurBlock->TheScope); 4550} 4551 4552/// ActOnBlockError - If there is an error parsing a block, this callback 4553/// is invoked to pop the information about the block from the action impl. 4554void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 4555 // Ensure that CurBlock is deleted. 4556 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock); 4557 4558 // Pop off CurBlock, handle nested blocks. 4559 CurBlock = CurBlock->PrevBlockInfo; 4560 4561 // FIXME: Delete the ParmVarDecl objects as well??? 4562 4563} 4564 4565/// ActOnBlockStmtExpr - This is called when the body of a block statement 4566/// literal was successfully completed. ^(int x){...} 4567Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body, 4568 Scope *CurScope) { 4569 // Ensure that CurBlock is deleted. 4570 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock); 4571 ExprOwningPtr<CompoundStmt> Body(this, static_cast<CompoundStmt*>(body)); 4572 4573 PopDeclContext(); 4574 4575 // Before poping CurBlock, set ActiveScope to this scopes parent. 4576 ActiveScope = CurBlock->TheScope->getParent(); 4577 4578 // Pop off CurBlock, handle nested blocks. 4579 CurBlock = CurBlock->PrevBlockInfo; 4580 4581 QualType RetTy = Context.VoidTy; 4582 if (BSI->ReturnType) 4583 RetTy = QualType(BSI->ReturnType, 0); 4584 4585 llvm::SmallVector<QualType, 8> ArgTypes; 4586 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i) 4587 ArgTypes.push_back(BSI->Params[i]->getType()); 4588 4589 QualType BlockTy; 4590 if (!BSI->hasPrototype) 4591 BlockTy = Context.getFunctionNoProtoType(RetTy); 4592 else 4593 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(), 4594 BSI->isVariadic, 0); 4595 4596 BlockTy = Context.getBlockPointerType(BlockTy); 4597 4598 BSI->TheDecl->setBody(Body.take()); 4599 return new (Context) BlockExpr(BSI->TheDecl, BlockTy, BSI->hasBlockDeclRefExprs); 4600} 4601 4602Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 4603 ExprTy *expr, TypeTy *type, 4604 SourceLocation RPLoc) { 4605 Expr *E = static_cast<Expr*>(expr); 4606 QualType T = QualType::getFromOpaquePtr(type); 4607 4608 InitBuiltinVaListType(); 4609 4610 // Get the va_list type 4611 QualType VaListType = Context.getBuiltinVaListType(); 4612 // Deal with implicit array decay; for example, on x86-64, 4613 // va_list is an array, but it's supposed to decay to 4614 // a pointer for va_arg. 4615 if (VaListType->isArrayType()) 4616 VaListType = Context.getArrayDecayedType(VaListType); 4617 // Make sure the input expression also decays appropriately. 4618 UsualUnaryConversions(E); 4619 4620 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible) 4621 return Diag(E->getLocStart(), 4622 diag::err_first_argument_to_va_arg_not_of_type_va_list) 4623 << E->getType() << E->getSourceRange(); 4624 4625 // FIXME: Warn if a non-POD type is passed in. 4626 4627 return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc); 4628} 4629 4630Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 4631 // The type of __null will be int or long, depending on the size of 4632 // pointers on the target. 4633 QualType Ty; 4634 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth()) 4635 Ty = Context.IntTy; 4636 else 4637 Ty = Context.LongTy; 4638 4639 return new (Context) GNUNullExpr(Ty, TokenLoc); 4640} 4641 4642bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 4643 SourceLocation Loc, 4644 QualType DstType, QualType SrcType, 4645 Expr *SrcExpr, const char *Flavor) { 4646 // Decode the result (notice that AST's are still created for extensions). 4647 bool isInvalid = false; 4648 unsigned DiagKind; 4649 switch (ConvTy) { 4650 default: assert(0 && "Unknown conversion type"); 4651 case Compatible: return false; 4652 case PointerToInt: 4653 DiagKind = diag::ext_typecheck_convert_pointer_int; 4654 break; 4655 case IntToPointer: 4656 DiagKind = diag::ext_typecheck_convert_int_pointer; 4657 break; 4658 case IncompatiblePointer: 4659 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 4660 break; 4661 case FunctionVoidPointer: 4662 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 4663 break; 4664 case CompatiblePointerDiscardsQualifiers: 4665 // If the qualifiers lost were because we were applying the 4666 // (deprecated) C++ conversion from a string literal to a char* 4667 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 4668 // Ideally, this check would be performed in 4669 // CheckPointerTypesForAssignment. However, that would require a 4670 // bit of refactoring (so that the second argument is an 4671 // expression, rather than a type), which should be done as part 4672 // of a larger effort to fix CheckPointerTypesForAssignment for 4673 // C++ semantics. 4674 if (getLangOptions().CPlusPlus && 4675 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 4676 return false; 4677 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 4678 break; 4679 case IntToBlockPointer: 4680 DiagKind = diag::err_int_to_block_pointer; 4681 break; 4682 case IncompatibleBlockPointer: 4683 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer; 4684 break; 4685 case IncompatibleObjCQualifiedId: 4686 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since 4687 // it can give a more specific diagnostic. 4688 DiagKind = diag::warn_incompatible_qualified_id; 4689 break; 4690 case IncompatibleVectors: 4691 DiagKind = diag::warn_incompatible_vectors; 4692 break; 4693 case Incompatible: 4694 DiagKind = diag::err_typecheck_convert_incompatible; 4695 isInvalid = true; 4696 break; 4697 } 4698 4699 Diag(Loc, DiagKind) << DstType << SrcType << Flavor 4700 << SrcExpr->getSourceRange(); 4701 return isInvalid; 4702} 4703 4704bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result) 4705{ 4706 Expr::EvalResult EvalResult; 4707 4708 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() || 4709 EvalResult.HasSideEffects) { 4710 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange(); 4711 4712 if (EvalResult.Diag) { 4713 // We only show the note if it's not the usual "invalid subexpression" 4714 // or if it's actually in a subexpression. 4715 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice || 4716 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens()) 4717 Diag(EvalResult.DiagLoc, EvalResult.Diag); 4718 } 4719 4720 return true; 4721 } 4722 4723 if (EvalResult.Diag) { 4724 Diag(E->getExprLoc(), diag::ext_expr_not_ice) << 4725 E->getSourceRange(); 4726 4727 // Print the reason it's not a constant. 4728 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored) 4729 Diag(EvalResult.DiagLoc, EvalResult.Diag); 4730 } 4731 4732 if (Result) 4733 *Result = EvalResult.Val.getInt(); 4734 return false; 4735} 4736