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