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