SemaExpr.cpp revision 28997ec3a493134a8642891944800ffc1c160bee
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/Lex/Preprocessor.h" 20#include "clang/Lex/LiteralSupport.h" 21#include "clang/Basic/Diagnostic.h" 22#include "clang/Basic/SourceManager.h" 23#include "clang/Basic/TargetInfo.h" 24#include "clang/Parse/DeclSpec.h" 25#include "clang/Parse/Scope.h" 26using namespace clang; 27 28//===----------------------------------------------------------------------===// 29// Standard Promotions and Conversions 30//===----------------------------------------------------------------------===// 31 32/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 33void Sema::DefaultFunctionArrayConversion(Expr *&E) { 34 QualType Ty = E->getType(); 35 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 36 37 if (const ReferenceType *ref = Ty->getAsReferenceType()) { 38 ImpCastExprToType(E, ref->getPointeeType()); // C++ [expr] 39 Ty = E->getType(); 40 } 41 if (Ty->isFunctionType()) 42 ImpCastExprToType(E, Context.getPointerType(Ty)); 43 else if (Ty->isArrayType()) { 44 // In C90 mode, arrays only promote to pointers if the array expression is 45 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 46 // type 'array of type' is converted to an expression that has type 'pointer 47 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 48 // that has type 'array of type' ...". The relevant change is "an lvalue" 49 // (C90) to "an expression" (C99). 50 // 51 // C++ 4.2p1: 52 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 53 // T" can be converted to an rvalue of type "pointer to T". 54 // 55 if (getLangOptions().C99 || getLangOptions().CPlusPlus || 56 E->isLvalue(Context) == Expr::LV_Valid) 57 ImpCastExprToType(E, Context.getArrayDecayedType(Ty)); 58 } 59} 60 61/// UsualUnaryConversions - Performs various conversions that are common to most 62/// operators (C99 6.3). The conversions of array and function types are 63/// sometimes surpressed. For example, the array->pointer conversion doesn't 64/// apply if the array is an argument to the sizeof or address (&) operators. 65/// In these instances, this routine should *not* be called. 66Expr *Sema::UsualUnaryConversions(Expr *&Expr) { 67 QualType Ty = Expr->getType(); 68 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 69 70 if (const ReferenceType *Ref = Ty->getAsReferenceType()) { 71 ImpCastExprToType(Expr, Ref->getPointeeType()); // C++ [expr] 72 Ty = Expr->getType(); 73 } 74 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2 75 ImpCastExprToType(Expr, Context.IntTy); 76 else 77 DefaultFunctionArrayConversion(Expr); 78 79 return Expr; 80} 81 82/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 83/// do not have a prototype. Arguments that have type float are promoted to 84/// double. All other argument types are converted by UsualUnaryConversions(). 85void Sema::DefaultArgumentPromotion(Expr *&Expr) { 86 QualType Ty = Expr->getType(); 87 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 88 89 // If this is a 'float' (CVR qualified or typedef) promote to double. 90 if (const BuiltinType *BT = Ty->getAsBuiltinType()) 91 if (BT->getKind() == BuiltinType::Float) 92 return ImpCastExprToType(Expr, Context.DoubleTy); 93 94 UsualUnaryConversions(Expr); 95} 96 97/// UsualArithmeticConversions - Performs various conversions that are common to 98/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 99/// routine returns the first non-arithmetic type found. The client is 100/// responsible for emitting appropriate error diagnostics. 101/// FIXME: verify the conversion rules for "complex int" are consistent with 102/// GCC. 103QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr, 104 bool isCompAssign) { 105 if (!isCompAssign) { 106 UsualUnaryConversions(lhsExpr); 107 UsualUnaryConversions(rhsExpr); 108 } 109 // For conversion purposes, we ignore any qualifiers. 110 // For example, "const float" and "float" are equivalent. 111 QualType lhs = 112 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType(); 113 QualType rhs = 114 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType(); 115 116 // If both types are identical, no conversion is needed. 117 if (lhs == rhs) 118 return lhs; 119 120 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 121 // The caller can deal with this (e.g. pointer + int). 122 if (!lhs->isArithmeticType() || !rhs->isArithmeticType()) 123 return lhs; 124 125 // At this point, we have two different arithmetic types. 126 127 // Handle complex types first (C99 6.3.1.8p1). 128 if (lhs->isComplexType() || rhs->isComplexType()) { 129 // if we have an integer operand, the result is the complex type. 130 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) { 131 // convert the rhs to the lhs complex type. 132 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs); 133 return lhs; 134 } 135 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) { 136 // convert the lhs to the rhs complex type. 137 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); 138 return rhs; 139 } 140 // This handles complex/complex, complex/float, or float/complex. 141 // When both operands are complex, the shorter operand is converted to the 142 // type of the longer, and that is the type of the result. This corresponds 143 // to what is done when combining two real floating-point operands. 144 // The fun begins when size promotion occur across type domains. 145 // From H&S 6.3.4: When one operand is complex and the other is a real 146 // floating-point type, the less precise type is converted, within it's 147 // real or complex domain, to the precision of the other type. For example, 148 // when combining a "long double" with a "double _Complex", the 149 // "double _Complex" is promoted to "long double _Complex". 150 int result = Context.getFloatingTypeOrder(lhs, rhs); 151 152 if (result > 0) { // The left side is bigger, convert rhs. 153 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs); 154 if (!isCompAssign) 155 ImpCastExprToType(rhsExpr, rhs); 156 } else if (result < 0) { // The right side is bigger, convert lhs. 157 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs); 158 if (!isCompAssign) 159 ImpCastExprToType(lhsExpr, lhs); 160 } 161 // At this point, lhs and rhs have the same rank/size. Now, make sure the 162 // domains match. This is a requirement for our implementation, C99 163 // does not require this promotion. 164 if (lhs != rhs) { // Domains don't match, we have complex/float mix. 165 if (lhs->isRealFloatingType()) { // handle "double, _Complex double". 166 if (!isCompAssign) 167 ImpCastExprToType(lhsExpr, rhs); 168 return rhs; 169 } else { // handle "_Complex double, double". 170 if (!isCompAssign) 171 ImpCastExprToType(rhsExpr, lhs); 172 return lhs; 173 } 174 } 175 return lhs; // The domain/size match exactly. 176 } 177 // Now handle "real" floating types (i.e. float, double, long double). 178 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) { 179 // if we have an integer operand, the result is the real floating type. 180 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) { 181 // convert rhs to the lhs floating point type. 182 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs); 183 return lhs; 184 } 185 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) { 186 // convert lhs to the rhs floating point type. 187 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); 188 return rhs; 189 } 190 // We have two real floating types, float/complex combos were handled above. 191 // Convert the smaller operand to the bigger result. 192 int result = Context.getFloatingTypeOrder(lhs, rhs); 193 194 if (result > 0) { // convert the rhs 195 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs); 196 return lhs; 197 } 198 if (result < 0) { // convert the lhs 199 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs 200 return rhs; 201 } 202 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison"); 203 } 204 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) { 205 // Handle GCC complex int extension. 206 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType(); 207 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType(); 208 209 if (lhsComplexInt && rhsComplexInt) { 210 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(), 211 rhsComplexInt->getElementType()) >= 0) { 212 // convert the rhs 213 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs); 214 return lhs; 215 } 216 if (!isCompAssign) 217 ImpCastExprToType(lhsExpr, rhs); // convert the lhs 218 return rhs; 219 } else if (lhsComplexInt && rhs->isIntegerType()) { 220 // convert the rhs to the lhs complex type. 221 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs); 222 return lhs; 223 } else if (rhsComplexInt && lhs->isIntegerType()) { 224 // convert the lhs to the rhs complex type. 225 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); 226 return rhs; 227 } 228 } 229 // Finally, we have two differing integer types. 230 // The rules for this case are in C99 6.3.1.8 231 int compare = Context.getIntegerTypeOrder(lhs, rhs); 232 bool lhsSigned = lhs->isSignedIntegerType(), 233 rhsSigned = rhs->isSignedIntegerType(); 234 QualType destType; 235 if (lhsSigned == rhsSigned) { 236 // Same signedness; use the higher-ranked type 237 destType = compare >= 0 ? lhs : rhs; 238 } else if (compare != (lhsSigned ? 1 : -1)) { 239 // The unsigned type has greater than or equal rank to the 240 // signed type, so use the unsigned type 241 destType = lhsSigned ? rhs : lhs; 242 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) { 243 // The two types are different widths; if we are here, that 244 // means the signed type is larger than the unsigned type, so 245 // use the signed type. 246 destType = lhsSigned ? lhs : rhs; 247 } else { 248 // The signed type is higher-ranked than the unsigned type, 249 // but isn't actually any bigger (like unsigned int and long 250 // on most 32-bit systems). Use the unsigned type corresponding 251 // to the signed type. 252 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs); 253 } 254 if (!isCompAssign) { 255 ImpCastExprToType(lhsExpr, destType); 256 ImpCastExprToType(rhsExpr, destType); 257 } 258 return destType; 259} 260 261//===----------------------------------------------------------------------===// 262// Semantic Analysis for various Expression Types 263//===----------------------------------------------------------------------===// 264 265 266/// ActOnStringLiteral - The specified tokens were lexed as pasted string 267/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 268/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 269/// multiple tokens. However, the common case is that StringToks points to one 270/// string. 271/// 272Action::ExprResult 273Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) { 274 assert(NumStringToks && "Must have at least one string!"); 275 276 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target); 277 if (Literal.hadError) 278 return ExprResult(true); 279 280 llvm::SmallVector<SourceLocation, 4> StringTokLocs; 281 for (unsigned i = 0; i != NumStringToks; ++i) 282 StringTokLocs.push_back(StringToks[i].getLocation()); 283 284 // Verify that pascal strings aren't too large. 285 if (Literal.Pascal && Literal.GetStringLength() > 256) 286 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long, 287 SourceRange(StringToks[0].getLocation(), 288 StringToks[NumStringToks-1].getLocation())); 289 290 QualType StrTy = Context.CharTy; 291 if (Literal.AnyWide) StrTy = Context.getWCharType(); 292 if (Literal.Pascal) StrTy = Context.UnsignedCharTy; 293 294 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 295 if (getLangOptions().CPlusPlus) 296 StrTy.addConst(); 297 298 // Get an array type for the string, according to C99 6.4.5. This includes 299 // the nul terminator character as well as the string length for pascal 300 // strings. 301 StrTy = Context.getConstantArrayType(StrTy, 302 llvm::APInt(32, Literal.GetStringLength()+1), 303 ArrayType::Normal, 0); 304 305 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 306 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(), 307 Literal.AnyWide, StrTy, 308 StringToks[0].getLocation(), 309 StringToks[NumStringToks-1].getLocation()); 310} 311 312/// DeclDefinedWithinScope - Return true if the specified decl is defined at or 313/// within the 'Within' scope. The current Scope is CurScope. 314/// 315/// FIXME: This method is extremely inefficient (linear scan), this should not 316/// be used in common cases. Replace with the more modern DeclContext. We need 317/// to make sure both assignments below produce an error. 318/// 319/// int main(int argc) { 320/// int xx; 321/// ^(int X) { 322/// xx = 4; // error (variable is not assignable) 323/// argc = 3; // no error. 324/// }; 325/// } 326/// 327static bool DeclDefinedWithinScope(ScopedDecl *D, Scope *Within, 328 Scope *CurScope) { 329 while (1) { 330 assert(CurScope && "CurScope not nested within 'Within'?"); 331 332 // Check this scope for the decl. 333 if (CurScope->isDeclScope(D)) return true; 334 335 if (CurScope == Within) return false; 336 CurScope = CurScope->getParent(); 337 } 338} 339 340/// ActOnIdentifierExpr - The parser read an identifier in expression context, 341/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this 342/// identifier is used in a function call context. 343Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc, 344 IdentifierInfo &II, 345 bool HasTrailingLParen) { 346 // Could be enum-constant, value decl, instance variable, etc. 347 Decl *D = LookupDecl(&II, Decl::IDNS_Ordinary, S); 348 349 // If this reference is in an Objective-C method, then ivar lookup happens as 350 // well. 351 if (getCurMethodDecl()) { 352 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D); 353 // There are two cases to handle here. 1) scoped lookup could have failed, 354 // in which case we should look for an ivar. 2) scoped lookup could have 355 // found a decl, but that decl is outside the current method (i.e. a global 356 // variable). In these two cases, we do a lookup for an ivar with this 357 // name, if the lookup suceeds, we replace it our current decl. 358 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) { 359 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface(); 360 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II)) { 361 // FIXME: This should use a new expr for a direct reference, don't turn 362 // this into Self->ivar, just return a BareIVarExpr or something. 363 IdentifierInfo &II = Context.Idents.get("self"); 364 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false); 365 return new ObjCIvarRefExpr(IV, IV->getType(), Loc, 366 static_cast<Expr*>(SelfExpr.Val), true, true); 367 } 368 } 369 // Needed to implement property "super.method" notation. 370 if (SD == 0 && &II == SuperID) { 371 QualType T = Context.getPointerType(Context.getObjCInterfaceType( 372 getCurMethodDecl()->getClassInterface())); 373 return new PredefinedExpr(Loc, T, PredefinedExpr::ObjCSuper); 374 } 375 } 376 // If we are parsing a block, check the block parameter list. 377 if (CurBlock) { 378 BlockSemaInfo *BLK = CurBlock; 379 do { 380 for (unsigned i = 0, e = BLK->Params.size(); i != e && D == 0; ++i) 381 if (BLK->Params[i]->getIdentifier() == &II) 382 D = BLK->Params[i]; 383 if (D) 384 break; // Found! 385 } while ((BLK = BLK->PrevBlockInfo)); // Look through any enclosing blocks. 386 } 387 if (D == 0) { 388 // Otherwise, this could be an implicitly declared function reference (legal 389 // in C90, extension in C99). 390 if (HasTrailingLParen && 391 !getLangOptions().CPlusPlus) // Not in C++. 392 D = ImplicitlyDefineFunction(Loc, II, S); 393 else { 394 // If this name wasn't predeclared and if this is not a function call, 395 // diagnose the problem. 396 return Diag(Loc, diag::err_undeclared_var_use, II.getName()); 397 } 398 } 399 400 if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) { 401 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) { 402 if (MD->isStatic()) 403 // "invalid use of member 'x' in static member function" 404 return Diag(Loc, diag::err_invalid_member_use_in_static_method, 405 FD->getName()); 406 if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent()) 407 // "invalid use of nonstatic data member 'x'" 408 return Diag(Loc, diag::err_invalid_non_static_member_use, 409 FD->getName()); 410 411 if (FD->isInvalidDecl()) 412 return true; 413 414 // FIXME: Use DeclRefExpr or a new Expr for a direct CXXField reference. 415 ExprResult ThisExpr = ActOnCXXThis(SourceLocation()); 416 return new MemberExpr(static_cast<Expr*>(ThisExpr.Val), 417 true, FD, Loc, FD->getType()); 418 } 419 420 return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName()); 421 } 422 if (isa<TypedefDecl>(D)) 423 return Diag(Loc, diag::err_unexpected_typedef, II.getName()); 424 if (isa<ObjCInterfaceDecl>(D)) 425 return Diag(Loc, diag::err_unexpected_interface, II.getName()); 426 if (isa<NamespaceDecl>(D)) 427 return Diag(Loc, diag::err_unexpected_namespace, II.getName()); 428 429 // Make the DeclRefExpr or BlockDeclRefExpr for the decl. 430 ValueDecl *VD = cast<ValueDecl>(D); 431 432 // check if referencing an identifier with __attribute__((deprecated)). 433 if (VD->getAttr<DeprecatedAttr>()) 434 Diag(Loc, diag::warn_deprecated, VD->getName()); 435 436 // Only create DeclRefExpr's for valid Decl's. 437 if (VD->isInvalidDecl()) 438 return true; 439 440 // If this reference is not in a block or if the referenced variable is 441 // within the block, create a normal DeclRefExpr. 442 // 443 // FIXME: This will create BlockDeclRefExprs for global variables, 444 // function references, etc which is suboptimal :) and breaks 445 // things like "integer constant expression" tests. 446 // 447 if (!CurBlock || DeclDefinedWithinScope(VD, CurBlock->TheScope, S) || 448 isa<EnumConstantDecl>(VD) || isa<ParmVarDecl>(VD)) 449 return new DeclRefExpr(VD, VD->getType(), Loc); 450 451 // If we are in a block and the variable is outside the current block, 452 // bind the variable reference with a BlockDeclRefExpr. 453 454 // The BlocksAttr indicates the variable is bound by-reference. 455 if (VD->getAttr<BlocksAttr>()) 456 return new BlockDeclRefExpr(VD, VD->getType(), Loc, true); 457 458 // Variable will be bound by-copy, make it const within the closure. 459 VD->getType().addConst(); 460 return new BlockDeclRefExpr(VD, VD->getType(), Loc, false); 461} 462 463Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, 464 tok::TokenKind Kind) { 465 PredefinedExpr::IdentType IT; 466 467 switch (Kind) { 468 default: assert(0 && "Unknown simple primary expr!"); 469 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 470 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 471 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 472 } 473 474 // Verify that this is in a function context. 475 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0) 476 return Diag(Loc, diag::err_predef_outside_function); 477 478 // Pre-defined identifiers are of type char[x], where x is the length of the 479 // string. 480 unsigned Length; 481 if (getCurFunctionDecl()) 482 Length = getCurFunctionDecl()->getIdentifier()->getLength(); 483 else 484 Length = getCurMethodDecl()->getSynthesizedMethodSize(); 485 486 llvm::APInt LengthI(32, Length + 1); 487 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const); 488 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); 489 return new PredefinedExpr(Loc, ResTy, IT); 490} 491 492Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) { 493 llvm::SmallString<16> CharBuffer; 494 CharBuffer.resize(Tok.getLength()); 495 const char *ThisTokBegin = &CharBuffer[0]; 496 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin); 497 498 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength, 499 Tok.getLocation(), PP); 500 if (Literal.hadError()) 501 return ExprResult(true); 502 503 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy; 504 505 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type, 506 Tok.getLocation()); 507} 508 509Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) { 510 // fast path for a single digit (which is quite common). A single digit 511 // cannot have a trigraph, escaped newline, radix prefix, or type suffix. 512 if (Tok.getLength() == 1) { 513 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation()); 514 515 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy)); 516 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'), 517 Context.IntTy, 518 Tok.getLocation())); 519 } 520 llvm::SmallString<512> IntegerBuffer; 521 IntegerBuffer.resize(Tok.getLength()); 522 const char *ThisTokBegin = &IntegerBuffer[0]; 523 524 // Get the spelling of the token, which eliminates trigraphs, etc. 525 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin); 526 527 // Add padding so that NumericLiteralParser can overread by one character. 528 if (!IntegerBuffer.empty()) { 529 IntegerBuffer.push_back(' '); 530 ThisTokBegin = &IntegerBuffer[0]; 531 } 532 533 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength, 534 Tok.getLocation(), PP); 535 if (Literal.hadError) 536 return ExprResult(true); 537 538 Expr *Res; 539 540 if (Literal.isFloatingLiteral()) { 541 QualType Ty; 542 if (Literal.isFloat) 543 Ty = Context.FloatTy; 544 else if (!Literal.isLong) 545 Ty = Context.DoubleTy; 546 else 547 Ty = Context.LongDoubleTy; 548 549 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty); 550 551 // isExact will be set by GetFloatValue(). 552 bool isExact = false; 553 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact, 554 Ty, Tok.getLocation()); 555 556 } else if (!Literal.isIntegerLiteral()) { 557 return ExprResult(true); 558 } else { 559 QualType Ty; 560 561 // long long is a C99 feature. 562 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x && 563 Literal.isLongLong) 564 Diag(Tok.getLocation(), diag::ext_longlong); 565 566 // Get the value in the widest-possible width. 567 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0); 568 569 if (Literal.GetIntegerValue(ResultVal)) { 570 // If this value didn't fit into uintmax_t, warn and force to ull. 571 Diag(Tok.getLocation(), diag::warn_integer_too_large); 572 Ty = Context.UnsignedLongLongTy; 573 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 574 "long long is not intmax_t?"); 575 } else { 576 // If this value fits into a ULL, try to figure out what else it fits into 577 // according to the rules of C99 6.4.4.1p5. 578 579 // Octal, Hexadecimal, and integers with a U suffix are allowed to 580 // be an unsigned int. 581 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 582 583 // Check from smallest to largest, picking the smallest type we can. 584 unsigned Width = 0; 585 if (!Literal.isLong && !Literal.isLongLong) { 586 // Are int/unsigned possibilities? 587 unsigned IntSize = Context.Target.getIntWidth(); 588 589 // Does it fit in a unsigned int? 590 if (ResultVal.isIntN(IntSize)) { 591 // Does it fit in a signed int? 592 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 593 Ty = Context.IntTy; 594 else if (AllowUnsigned) 595 Ty = Context.UnsignedIntTy; 596 Width = IntSize; 597 } 598 } 599 600 // Are long/unsigned long possibilities? 601 if (Ty.isNull() && !Literal.isLongLong) { 602 unsigned LongSize = Context.Target.getLongWidth(); 603 604 // Does it fit in a unsigned long? 605 if (ResultVal.isIntN(LongSize)) { 606 // Does it fit in a signed long? 607 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 608 Ty = Context.LongTy; 609 else if (AllowUnsigned) 610 Ty = Context.UnsignedLongTy; 611 Width = LongSize; 612 } 613 } 614 615 // Finally, check long long if needed. 616 if (Ty.isNull()) { 617 unsigned LongLongSize = Context.Target.getLongLongWidth(); 618 619 // Does it fit in a unsigned long long? 620 if (ResultVal.isIntN(LongLongSize)) { 621 // Does it fit in a signed long long? 622 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0) 623 Ty = Context.LongLongTy; 624 else if (AllowUnsigned) 625 Ty = Context.UnsignedLongLongTy; 626 Width = LongLongSize; 627 } 628 } 629 630 // If we still couldn't decide a type, we probably have something that 631 // does not fit in a signed long long, but has no U suffix. 632 if (Ty.isNull()) { 633 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed); 634 Ty = Context.UnsignedLongLongTy; 635 Width = Context.Target.getLongLongWidth(); 636 } 637 638 if (ResultVal.getBitWidth() != Width) 639 ResultVal.trunc(Width); 640 } 641 642 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation()); 643 } 644 645 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 646 if (Literal.isImaginary) 647 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType())); 648 649 return Res; 650} 651 652Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, 653 ExprTy *Val) { 654 Expr *E = (Expr *)Val; 655 assert((E != 0) && "ActOnParenExpr() missing expr"); 656 return new ParenExpr(L, R, E); 657} 658 659/// The UsualUnaryConversions() function is *not* called by this routine. 660/// See C99 6.3.2.1p[2-4] for more details. 661QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType, 662 SourceLocation OpLoc, 663 const SourceRange &ExprRange, 664 bool isSizeof) { 665 // C99 6.5.3.4p1: 666 if (isa<FunctionType>(exprType) && isSizeof) 667 // alignof(function) is allowed. 668 Diag(OpLoc, diag::ext_sizeof_function_type, ExprRange); 669 else if (exprType->isVoidType()) 670 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof", 671 ExprRange); 672 else if (exprType->isIncompleteType()) { 673 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type : 674 diag::err_alignof_incomplete_type, 675 exprType.getAsString(), ExprRange); 676 return QualType(); // error 677 } 678 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 679 return Context.getSizeType(); 680} 681 682Action::ExprResult Sema:: 683ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof, 684 SourceLocation LPLoc, TypeTy *Ty, 685 SourceLocation RPLoc) { 686 // If error parsing type, ignore. 687 if (Ty == 0) return true; 688 689 // Verify that this is a valid expression. 690 QualType ArgTy = QualType::getFromOpaquePtr(Ty); 691 692 QualType resultType = 693 CheckSizeOfAlignOfOperand(ArgTy, OpLoc, SourceRange(LPLoc, RPLoc),isSizeof); 694 695 if (resultType.isNull()) 696 return true; 697 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc); 698} 699 700QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) { 701 DefaultFunctionArrayConversion(V); 702 703 // These operators return the element type of a complex type. 704 if (const ComplexType *CT = V->getType()->getAsComplexType()) 705 return CT->getElementType(); 706 707 // Otherwise they pass through real integer and floating point types here. 708 if (V->getType()->isArithmeticType()) 709 return V->getType(); 710 711 // Reject anything else. 712 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString()); 713 return QualType(); 714} 715 716 717 718Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc, 719 tok::TokenKind Kind, 720 ExprTy *Input) { 721 UnaryOperator::Opcode Opc; 722 switch (Kind) { 723 default: assert(0 && "Unknown unary op!"); 724 case tok::plusplus: Opc = UnaryOperator::PostInc; break; 725 case tok::minusminus: Opc = UnaryOperator::PostDec; break; 726 } 727 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc); 728 if (result.isNull()) 729 return true; 730 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc); 731} 732 733Action::ExprResult Sema:: 734ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc, 735 ExprTy *Idx, SourceLocation RLoc) { 736 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx); 737 738 // Perform default conversions. 739 DefaultFunctionArrayConversion(LHSExp); 740 DefaultFunctionArrayConversion(RHSExp); 741 742 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 743 744 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 745 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 746 // in the subscript position. As a result, we need to derive the array base 747 // and index from the expression types. 748 Expr *BaseExpr, *IndexExpr; 749 QualType ResultType; 750 if (const PointerType *PTy = LHSTy->getAsPointerType()) { 751 BaseExpr = LHSExp; 752 IndexExpr = RHSExp; 753 // FIXME: need to deal with const... 754 ResultType = PTy->getPointeeType(); 755 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) { 756 // Handle the uncommon case of "123[Ptr]". 757 BaseExpr = RHSExp; 758 IndexExpr = LHSExp; 759 // FIXME: need to deal with const... 760 ResultType = PTy->getPointeeType(); 761 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) { 762 BaseExpr = LHSExp; // vectors: V[123] 763 IndexExpr = RHSExp; 764 765 // Component access limited to variables (reject vec4.rg[1]). 766 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) && 767 !isa<ExtVectorElementExpr>(BaseExpr)) 768 return Diag(LLoc, diag::err_ext_vector_component_access, 769 SourceRange(LLoc, RLoc)); 770 // FIXME: need to deal with const... 771 ResultType = VTy->getElementType(); 772 } else { 773 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value, 774 RHSExp->getSourceRange()); 775 } 776 // C99 6.5.2.1p1 777 if (!IndexExpr->getType()->isIntegerType()) 778 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript, 779 IndexExpr->getSourceRange()); 780 781 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice, 782 // the following check catches trying to index a pointer to a function (e.g. 783 // void (*)(int)) and pointers to incomplete types. Functions are not 784 // objects in C99. 785 if (!ResultType->isObjectType()) 786 return Diag(BaseExpr->getLocStart(), 787 diag::err_typecheck_subscript_not_object, 788 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange()); 789 790 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc); 791} 792 793QualType Sema:: 794CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc, 795 IdentifierInfo &CompName, SourceLocation CompLoc) { 796 const ExtVectorType *vecType = baseType->getAsExtVectorType(); 797 798 // This flag determines whether or not the component is to be treated as a 799 // special name, or a regular GLSL-style component access. 800 bool SpecialComponent = false; 801 802 // The vector accessor can't exceed the number of elements. 803 const char *compStr = CompName.getName(); 804 if (strlen(compStr) > vecType->getNumElements()) { 805 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length, 806 baseType.getAsString(), SourceRange(CompLoc)); 807 return QualType(); 808 } 809 810 // Check that we've found one of the special components, or that the component 811 // names must come from the same set. 812 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") || 813 !strcmp(compStr, "e") || !strcmp(compStr, "o")) { 814 SpecialComponent = true; 815 } else if (vecType->getPointAccessorIdx(*compStr) != -1) { 816 do 817 compStr++; 818 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1); 819 } else if (vecType->getColorAccessorIdx(*compStr) != -1) { 820 do 821 compStr++; 822 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1); 823 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) { 824 do 825 compStr++; 826 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1); 827 } 828 829 if (!SpecialComponent && *compStr) { 830 // We didn't get to the end of the string. This means the component names 831 // didn't come from the same set *or* we encountered an illegal name. 832 Diag(OpLoc, diag::err_ext_vector_component_name_illegal, 833 std::string(compStr,compStr+1), SourceRange(CompLoc)); 834 return QualType(); 835 } 836 // Each component accessor can't exceed the vector type. 837 compStr = CompName.getName(); 838 while (*compStr) { 839 if (vecType->isAccessorWithinNumElements(*compStr)) 840 compStr++; 841 else 842 break; 843 } 844 if (!SpecialComponent && *compStr) { 845 // We didn't get to the end of the string. This means a component accessor 846 // exceeds the number of elements in the vector. 847 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length, 848 baseType.getAsString(), SourceRange(CompLoc)); 849 return QualType(); 850 } 851 852 // If we have a special component name, verify that the current vector length 853 // is an even number, since all special component names return exactly half 854 // the elements. 855 if (SpecialComponent && (vecType->getNumElements() & 1U)) { 856 Diag(OpLoc, diag::err_ext_vector_component_requires_even, 857 baseType.getAsString(), SourceRange(CompLoc)); 858 return QualType(); 859 } 860 861 // The component accessor looks fine - now we need to compute the actual type. 862 // The vector type is implied by the component accessor. For example, 863 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc. 864 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2. 865 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2 866 : strlen(CompName.getName()); 867 if (CompSize == 1) 868 return vecType->getElementType(); 869 870 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize); 871 // Now look up the TypeDefDecl from the vector type. Without this, 872 // diagostics look bad. We want extended vector types to appear built-in. 873 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) { 874 if (ExtVectorDecls[i]->getUnderlyingType() == VT) 875 return Context.getTypedefType(ExtVectorDecls[i]); 876 } 877 return VT; // should never get here (a typedef type should always be found). 878} 879 880/// constructSetterName - Return the setter name for the given 881/// identifier, i.e. "set" + Name where the initial character of Name 882/// has been capitalized. 883// FIXME: Merge with same routine in Parser. But where should this 884// live? 885static IdentifierInfo *constructSetterName(IdentifierTable &Idents, 886 const IdentifierInfo *Name) { 887 unsigned N = Name->getLength(); 888 char *SelectorName = new char[3 + N]; 889 memcpy(SelectorName, "set", 3); 890 memcpy(&SelectorName[3], Name->getName(), N); 891 SelectorName[3] = toupper(SelectorName[3]); 892 893 IdentifierInfo *Setter = 894 &Idents.get(SelectorName, &SelectorName[3 + N]); 895 delete[] SelectorName; 896 return Setter; 897} 898 899Action::ExprResult Sema:: 900ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc, 901 tok::TokenKind OpKind, SourceLocation MemberLoc, 902 IdentifierInfo &Member) { 903 Expr *BaseExpr = static_cast<Expr *>(Base); 904 assert(BaseExpr && "no record expression"); 905 906 // Perform default conversions. 907 DefaultFunctionArrayConversion(BaseExpr); 908 909 QualType BaseType = BaseExpr->getType(); 910 assert(!BaseType.isNull() && "no type for member expression"); 911 912 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr 913 // must have pointer type, and the accessed type is the pointee. 914 if (OpKind == tok::arrow) { 915 if (const PointerType *PT = BaseType->getAsPointerType()) 916 BaseType = PT->getPointeeType(); 917 else 918 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow, 919 BaseType.getAsString(), BaseExpr->getSourceRange()); 920 } 921 922 // Handle field access to simple records. This also handles access to fields 923 // of the ObjC 'id' struct. 924 if (const RecordType *RTy = BaseType->getAsRecordType()) { 925 RecordDecl *RDecl = RTy->getDecl(); 926 if (RTy->isIncompleteType()) 927 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(), 928 BaseExpr->getSourceRange()); 929 // The record definition is complete, now make sure the member is valid. 930 FieldDecl *MemberDecl = RDecl->getMember(&Member); 931 if (!MemberDecl) 932 return Diag(MemberLoc, diag::err_typecheck_no_member, Member.getName(), 933 BaseExpr->getSourceRange()); 934 935 // Figure out the type of the member; see C99 6.5.2.3p3 936 // FIXME: Handle address space modifiers 937 QualType MemberType = MemberDecl->getType(); 938 unsigned combinedQualifiers = 939 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers(); 940 MemberType = MemberType.getQualifiedType(combinedQualifiers); 941 942 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl, 943 MemberLoc, MemberType); 944 } 945 946 // Handle access to Objective-C instance variables, such as "Obj->ivar" and 947 // (*Obj).ivar. 948 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) { 949 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) 950 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr, 951 OpKind == tok::arrow); 952 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar, 953 IFTy->getDecl()->getName(), Member.getName(), 954 BaseExpr->getSourceRange()); 955 } 956 957 // Handle Objective-C property access, which is "Obj.property" where Obj is a 958 // pointer to a (potentially qualified) interface type. 959 const PointerType *PTy; 960 const ObjCInterfaceType *IFTy; 961 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) && 962 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) { 963 ObjCInterfaceDecl *IFace = IFTy->getDecl(); 964 965 // Search for a declared property first. 966 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) 967 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr); 968 969 // Check protocols on qualified interfaces. 970 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(), 971 E = IFTy->qual_end(); I != E; ++I) 972 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) 973 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr); 974 975 // If that failed, look for an "implicit" property by seeing if the nullary 976 // selector is implemented. 977 978 // FIXME: The logic for looking up nullary and unary selectors should be 979 // shared with the code in ActOnInstanceMessage. 980 981 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member); 982 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel); 983 984 // If this reference is in an @implementation, check for 'private' methods. 985 if (!Getter) 986 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) 987 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) 988 if (ObjCImplementationDecl *ImpDecl = 989 ObjCImplementations[ClassDecl->getIdentifier()]) 990 Getter = ImpDecl->getInstanceMethod(Sel); 991 992 if (Getter) { 993 // If we found a getter then this may be a valid dot-reference, we 994 // need to also look for the matching setter. 995 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(), 996 &Member); 997 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName); 998 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel); 999 1000 if (!Setter) { 1001 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) 1002 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) 1003 if (ObjCImplementationDecl *ImpDecl = 1004 ObjCImplementations[ClassDecl->getIdentifier()]) 1005 Setter = ImpDecl->getInstanceMethod(SetterSel); 1006 } 1007 1008 // FIXME: There are some issues here. First, we are not 1009 // diagnosing accesses to read-only properties because we do not 1010 // know if this is a getter or setter yet. Second, we are 1011 // checking that the type of the setter matches the type we 1012 // expect. 1013 return new ObjCPropertyRefExpr(Getter, Setter, Getter->getResultType(), 1014 MemberLoc, BaseExpr); 1015 } 1016 } 1017 1018 // Handle 'field access' to vectors, such as 'V.xx'. 1019 if (BaseType->isExtVectorType() && OpKind == tok::period) { 1020 // Component access limited to variables (reject vec4.rg.g). 1021 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) && 1022 !isa<ExtVectorElementExpr>(BaseExpr)) 1023 return Diag(MemberLoc, diag::err_ext_vector_component_access, 1024 BaseExpr->getSourceRange()); 1025 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc); 1026 if (ret.isNull()) 1027 return true; 1028 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc); 1029 } 1030 1031 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union, 1032 BaseType.getAsString(), BaseExpr->getSourceRange()); 1033} 1034 1035/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 1036/// This provides the location of the left/right parens and a list of comma 1037/// locations. 1038Action::ExprResult Sema:: 1039ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc, 1040 ExprTy **args, unsigned NumArgs, 1041 SourceLocation *CommaLocs, SourceLocation RParenLoc) { 1042 Expr *Fn = static_cast<Expr *>(fn); 1043 Expr **Args = reinterpret_cast<Expr**>(args); 1044 assert(Fn && "no function call expression"); 1045 FunctionDecl *FDecl = NULL; 1046 1047 // Promote the function operand. 1048 UsualUnaryConversions(Fn); 1049 1050 // If we're directly calling a function, get the declaration for 1051 // that function. 1052 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn)) 1053 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr())) 1054 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()); 1055 1056 // Make the call expr early, before semantic checks. This guarantees cleanup 1057 // of arguments and function on error. 1058 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs, 1059 Context.BoolTy, RParenLoc)); 1060 const FunctionType *FuncT; 1061 if (!Fn->getType()->isBlockPointerType()) { 1062 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 1063 // have type pointer to function". 1064 const PointerType *PT = Fn->getType()->getAsPointerType(); 1065 if (PT == 0) 1066 return Diag(LParenLoc, diag::err_typecheck_call_not_function, 1067 Fn->getSourceRange()); 1068 FuncT = PT->getPointeeType()->getAsFunctionType(); 1069 } else { // This is a block call. 1070 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()-> 1071 getAsFunctionType(); 1072 } 1073 if (FuncT == 0) 1074 return Diag(LParenLoc, diag::err_typecheck_call_not_function, 1075 Fn->getSourceRange()); 1076 1077 // We know the result type of the call, set it. 1078 TheCall->setType(FuncT->getResultType()); 1079 1080 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) { 1081 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 1082 // assignment, to the types of the corresponding parameter, ... 1083 unsigned NumArgsInProto = Proto->getNumArgs(); 1084 unsigned NumArgsToCheck = NumArgs; 1085 1086 // If too few arguments are available (and we don't have default 1087 // arguments for the remaining parameters), don't make the call. 1088 if (NumArgs < NumArgsInProto) { 1089 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) { 1090 // Use default arguments for missing arguments 1091 NumArgsToCheck = NumArgsInProto; 1092 TheCall->setNumArgs(NumArgsInProto); 1093 } else 1094 return Diag(RParenLoc, 1095 !Fn->getType()->isBlockPointerType() 1096 ? diag::err_typecheck_call_too_few_args 1097 : diag::err_typecheck_block_too_few_args, 1098 Fn->getSourceRange()); 1099 } 1100 1101 // If too many are passed and not variadic, error on the extras and drop 1102 // them. 1103 if (NumArgs > NumArgsInProto) { 1104 if (!Proto->isVariadic()) { 1105 Diag(Args[NumArgsInProto]->getLocStart(), 1106 !Fn->getType()->isBlockPointerType() 1107 ? diag::err_typecheck_call_too_many_args 1108 : diag::err_typecheck_block_too_many_args, 1109 Fn->getSourceRange(), 1110 SourceRange(Args[NumArgsInProto]->getLocStart(), 1111 Args[NumArgs-1]->getLocEnd())); 1112 // This deletes the extra arguments. 1113 TheCall->setNumArgs(NumArgsInProto); 1114 } 1115 NumArgsToCheck = NumArgsInProto; 1116 } 1117 1118 // Continue to check argument types (even if we have too few/many args). 1119 for (unsigned i = 0; i != NumArgsToCheck; i++) { 1120 QualType ProtoArgType = Proto->getArgType(i); 1121 1122 Expr *Arg; 1123 if (i < NumArgs) 1124 Arg = Args[i]; 1125 else 1126 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i)); 1127 QualType ArgType = Arg->getType(); 1128 1129 // Compute implicit casts from the operand to the formal argument type. 1130 AssignConvertType ConvTy = 1131 CheckSingleAssignmentConstraints(ProtoArgType, Arg); 1132 TheCall->setArg(i, Arg); 1133 1134 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType, 1135 ArgType, Arg, "passing")) 1136 return true; 1137 } 1138 1139 // If this is a variadic call, handle args passed through "...". 1140 if (Proto->isVariadic()) { 1141 // Promote the arguments (C99 6.5.2.2p7). 1142 for (unsigned i = NumArgsInProto; i != NumArgs; i++) { 1143 Expr *Arg = Args[i]; 1144 DefaultArgumentPromotion(Arg); 1145 TheCall->setArg(i, Arg); 1146 } 1147 } 1148 } else { 1149 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!"); 1150 1151 // Promote the arguments (C99 6.5.2.2p6). 1152 for (unsigned i = 0; i != NumArgs; i++) { 1153 Expr *Arg = Args[i]; 1154 DefaultArgumentPromotion(Arg); 1155 TheCall->setArg(i, Arg); 1156 } 1157 } 1158 1159 // Do special checking on direct calls to functions. 1160 if (FDecl) 1161 return CheckFunctionCall(FDecl, TheCall.take()); 1162 1163 return TheCall.take(); 1164} 1165 1166Action::ExprResult Sema:: 1167ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty, 1168 SourceLocation RParenLoc, ExprTy *InitExpr) { 1169 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type"); 1170 QualType literalType = QualType::getFromOpaquePtr(Ty); 1171 // FIXME: put back this assert when initializers are worked out. 1172 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 1173 Expr *literalExpr = static_cast<Expr*>(InitExpr); 1174 1175 if (literalType->isArrayType()) { 1176 if (literalType->isVariableArrayType()) 1177 return Diag(LParenLoc, 1178 diag::err_variable_object_no_init, 1179 SourceRange(LParenLoc, 1180 literalExpr->getSourceRange().getEnd())); 1181 } else if (literalType->isIncompleteType()) { 1182 return Diag(LParenLoc, 1183 diag::err_typecheck_decl_incomplete_type, 1184 literalType.getAsString(), 1185 SourceRange(LParenLoc, 1186 literalExpr->getSourceRange().getEnd())); 1187 } 1188 1189 if (CheckInitializerTypes(literalExpr, literalType)) 1190 return true; 1191 1192 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl(); 1193 if (isFileScope) { // 6.5.2.5p3 1194 if (CheckForConstantInitializer(literalExpr, literalType)) 1195 return true; 1196 } 1197 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope); 1198} 1199 1200Action::ExprResult Sema:: 1201ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit, 1202 SourceLocation RBraceLoc) { 1203 Expr **InitList = reinterpret_cast<Expr**>(initlist); 1204 1205 // Semantic analysis for initializers is done by ActOnDeclarator() and 1206 // CheckInitializer() - it requires knowledge of the object being intialized. 1207 1208 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc); 1209 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 1210 return E; 1211} 1212 1213/// CheckCastTypes - Check type constraints for casting between types. 1214bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) { 1215 UsualUnaryConversions(castExpr); 1216 1217 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression 1218 // type needs to be scalar. 1219 if (castType->isVoidType()) { 1220 // Cast to void allows any expr type. 1221 } else if (!castType->isScalarType() && !castType->isVectorType()) { 1222 // GCC struct/union extension: allow cast to self. 1223 if (Context.getCanonicalType(castType) != 1224 Context.getCanonicalType(castExpr->getType()) || 1225 (!castType->isStructureType() && !castType->isUnionType())) { 1226 // Reject any other conversions to non-scalar types. 1227 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar, 1228 castType.getAsString(), castExpr->getSourceRange()); 1229 } 1230 1231 // accept this, but emit an ext-warn. 1232 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar, 1233 castType.getAsString(), castExpr->getSourceRange()); 1234 } else if (!castExpr->getType()->isScalarType() && 1235 !castExpr->getType()->isVectorType()) { 1236 return Diag(castExpr->getLocStart(), 1237 diag::err_typecheck_expect_scalar_operand, 1238 castExpr->getType().getAsString(),castExpr->getSourceRange()); 1239 } else if (castExpr->getType()->isVectorType()) { 1240 if (CheckVectorCast(TyR, castExpr->getType(), castType)) 1241 return true; 1242 } else if (castType->isVectorType()) { 1243 if (CheckVectorCast(TyR, castType, castExpr->getType())) 1244 return true; 1245 } 1246 return false; 1247} 1248 1249bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) { 1250 assert(VectorTy->isVectorType() && "Not a vector type!"); 1251 1252 if (Ty->isVectorType() || Ty->isIntegerType()) { 1253 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty)) 1254 return Diag(R.getBegin(), 1255 Ty->isVectorType() ? 1256 diag::err_invalid_conversion_between_vectors : 1257 diag::err_invalid_conversion_between_vector_and_integer, 1258 VectorTy.getAsString().c_str(), 1259 Ty.getAsString().c_str(), R); 1260 } else 1261 return Diag(R.getBegin(), 1262 diag::err_invalid_conversion_between_vector_and_scalar, 1263 VectorTy.getAsString().c_str(), 1264 Ty.getAsString().c_str(), R); 1265 1266 return false; 1267} 1268 1269Action::ExprResult Sema:: 1270ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty, 1271 SourceLocation RParenLoc, ExprTy *Op) { 1272 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr"); 1273 1274 Expr *castExpr = static_cast<Expr*>(Op); 1275 QualType castType = QualType::getFromOpaquePtr(Ty); 1276 1277 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr)) 1278 return true; 1279 return new ExplicitCastExpr(castType, castExpr, LParenLoc); 1280} 1281 1282/// Note that lex is not null here, even if this is the gnu "x ?: y" extension. 1283/// In that case, lex = cond. 1284inline QualType Sema::CheckConditionalOperands( // C99 6.5.15 1285 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) { 1286 UsualUnaryConversions(cond); 1287 UsualUnaryConversions(lex); 1288 UsualUnaryConversions(rex); 1289 QualType condT = cond->getType(); 1290 QualType lexT = lex->getType(); 1291 QualType rexT = rex->getType(); 1292 1293 // first, check the condition. 1294 if (!condT->isScalarType()) { // C99 6.5.15p2 1295 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar, 1296 condT.getAsString()); 1297 return QualType(); 1298 } 1299 1300 // Now check the two expressions. 1301 1302 // If both operands have arithmetic type, do the usual arithmetic conversions 1303 // to find a common type: C99 6.5.15p3,5. 1304 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { 1305 UsualArithmeticConversions(lex, rex); 1306 return lex->getType(); 1307 } 1308 1309 // If both operands are the same structure or union type, the result is that 1310 // type. 1311 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3 1312 if (const RecordType *RHSRT = rexT->getAsRecordType()) 1313 if (LHSRT->getDecl() == RHSRT->getDecl()) 1314 // "If both the operands have structure or union type, the result has 1315 // that type." This implies that CV qualifiers are dropped. 1316 return lexT.getUnqualifiedType(); 1317 } 1318 1319 // C99 6.5.15p5: "If both operands have void type, the result has void type." 1320 // The following || allows only one side to be void (a GCC-ism). 1321 if (lexT->isVoidType() || rexT->isVoidType()) { 1322 if (!lexT->isVoidType()) 1323 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void, 1324 rex->getSourceRange()); 1325 if (!rexT->isVoidType()) 1326 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void, 1327 lex->getSourceRange()); 1328 ImpCastExprToType(lex, Context.VoidTy); 1329 ImpCastExprToType(rex, Context.VoidTy); 1330 return Context.VoidTy; 1331 } 1332 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 1333 // the type of the other operand." 1334 if ((lexT->isPointerType() || lexT->isBlockPointerType() || 1335 Context.isObjCObjectPointerType(lexT)) && 1336 rex->isNullPointerConstant(Context)) { 1337 ImpCastExprToType(rex, lexT); // promote the null to a pointer. 1338 return lexT; 1339 } 1340 if ((rexT->isPointerType() || rexT->isBlockPointerType() || 1341 Context.isObjCObjectPointerType(rexT)) && 1342 lex->isNullPointerConstant(Context)) { 1343 ImpCastExprToType(lex, rexT); // promote the null to a pointer. 1344 return rexT; 1345 } 1346 // Handle the case where both operands are pointers before we handle null 1347 // pointer constants in case both operands are null pointer constants. 1348 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6 1349 if (const PointerType *RHSPT = rexT->getAsPointerType()) { 1350 // get the "pointed to" types 1351 QualType lhptee = LHSPT->getPointeeType(); 1352 QualType rhptee = RHSPT->getPointeeType(); 1353 1354 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 1355 if (lhptee->isVoidType() && 1356 rhptee->isIncompleteOrObjectType()) { 1357 // Figure out necessary qualifiers (C99 6.5.15p6) 1358 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers()); 1359 QualType destType = Context.getPointerType(destPointee); 1360 ImpCastExprToType(lex, destType); // add qualifiers if necessary 1361 ImpCastExprToType(rex, destType); // promote to void* 1362 return destType; 1363 } 1364 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 1365 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers()); 1366 QualType destType = Context.getPointerType(destPointee); 1367 ImpCastExprToType(lex, destType); // add qualifiers if necessary 1368 ImpCastExprToType(rex, destType); // promote to void* 1369 return destType; 1370 } 1371 1372 QualType compositeType = lexT; 1373 1374 // If either type is an Objective-C object type then check 1375 // compatibility according to Objective-C. 1376 if (Context.isObjCObjectPointerType(lexT) || 1377 Context.isObjCObjectPointerType(rexT)) { 1378 // If both operands are interfaces and either operand can be 1379 // assigned to the other, use that type as the composite 1380 // type. This allows 1381 // xxx ? (A*) a : (B*) b 1382 // where B is a subclass of A. 1383 // 1384 // Additionally, as for assignment, if either type is 'id' 1385 // allow silent coercion. Finally, if the types are 1386 // incompatible then make sure to use 'id' as the composite 1387 // type so the result is acceptable for sending messages to. 1388 1389 // FIXME: This code should not be localized to here. Also this 1390 // should use a compatible check instead of abusing the 1391 // canAssignObjCInterfaces code. 1392 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType(); 1393 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType(); 1394 if (LHSIface && RHSIface && 1395 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) { 1396 compositeType = lexT; 1397 } else if (LHSIface && RHSIface && 1398 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) { 1399 compositeType = rexT; 1400 } else if (Context.isObjCIdType(lhptee) || 1401 Context.isObjCIdType(rhptee)) { 1402 // FIXME: This code looks wrong, because isObjCIdType checks 1403 // the struct but getObjCIdType returns the pointer to 1404 // struct. This is horrible and should be fixed. 1405 compositeType = Context.getObjCIdType(); 1406 } else { 1407 QualType incompatTy = Context.getObjCIdType(); 1408 ImpCastExprToType(lex, incompatTy); 1409 ImpCastExprToType(rex, incompatTy); 1410 return incompatTy; 1411 } 1412 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(), 1413 rhptee.getUnqualifiedType())) { 1414 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers, 1415 lexT.getAsString(), rexT.getAsString(), 1416 lex->getSourceRange(), rex->getSourceRange()); 1417 // In this situation, we assume void* type. No especially good 1418 // reason, but this is what gcc does, and we do have to pick 1419 // to get a consistent AST. 1420 QualType incompatTy = Context.getPointerType(Context.VoidTy); 1421 ImpCastExprToType(lex, incompatTy); 1422 ImpCastExprToType(rex, incompatTy); 1423 return incompatTy; 1424 } 1425 // The pointer types are compatible. 1426 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to 1427 // differently qualified versions of compatible types, the result type is 1428 // a pointer to an appropriately qualified version of the *composite* 1429 // type. 1430 // FIXME: Need to calculate the composite type. 1431 // FIXME: Need to add qualifiers 1432 ImpCastExprToType(lex, compositeType); 1433 ImpCastExprToType(rex, compositeType); 1434 return compositeType; 1435 } 1436 } 1437 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type 1438 // evaluates to "struct objc_object *" (and is handled above when comparing 1439 // id with statically typed objects). 1440 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) { 1441 // GCC allows qualified id and any Objective-C type to devolve to 1442 // id. Currently localizing to here until clear this should be 1443 // part of ObjCQualifiedIdTypesAreCompatible. 1444 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) || 1445 (lexT->isObjCQualifiedIdType() && 1446 Context.isObjCObjectPointerType(rexT)) || 1447 (rexT->isObjCQualifiedIdType() && 1448 Context.isObjCObjectPointerType(lexT))) { 1449 // FIXME: This is not the correct composite type. This only 1450 // happens to work because id can more or less be used anywhere, 1451 // however this may change the type of method sends. 1452 // FIXME: gcc adds some type-checking of the arguments and emits 1453 // (confusing) incompatible comparison warnings in some 1454 // cases. Investigate. 1455 QualType compositeType = Context.getObjCIdType(); 1456 ImpCastExprToType(lex, compositeType); 1457 ImpCastExprToType(rex, compositeType); 1458 return compositeType; 1459 } 1460 } 1461 1462 // Selection between block pointer types is ok as long as they are the same. 1463 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() && 1464 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT)) 1465 return lexT; 1466 1467 // Otherwise, the operands are not compatible. 1468 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands, 1469 lexT.getAsString(), rexT.getAsString(), 1470 lex->getSourceRange(), rex->getSourceRange()); 1471 return QualType(); 1472} 1473 1474/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 1475/// in the case of a the GNU conditional expr extension. 1476Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 1477 SourceLocation ColonLoc, 1478 ExprTy *Cond, ExprTy *LHS, 1479 ExprTy *RHS) { 1480 Expr *CondExpr = (Expr *) Cond; 1481 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS; 1482 1483 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 1484 // was the condition. 1485 bool isLHSNull = LHSExpr == 0; 1486 if (isLHSNull) 1487 LHSExpr = CondExpr; 1488 1489 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, 1490 RHSExpr, QuestionLoc); 1491 if (result.isNull()) 1492 return true; 1493 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr, 1494 RHSExpr, result); 1495} 1496 1497 1498// CheckPointerTypesForAssignment - This is a very tricky routine (despite 1499// being closely modeled after the C99 spec:-). The odd characteristic of this 1500// routine is it effectively iqnores the qualifiers on the top level pointee. 1501// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 1502// FIXME: add a couple examples in this comment. 1503Sema::AssignConvertType 1504Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) { 1505 QualType lhptee, rhptee; 1506 1507 // get the "pointed to" type (ignoring qualifiers at the top level) 1508 lhptee = lhsType->getAsPointerType()->getPointeeType(); 1509 rhptee = rhsType->getAsPointerType()->getPointeeType(); 1510 1511 // make sure we operate on the canonical type 1512 lhptee = Context.getCanonicalType(lhptee); 1513 rhptee = Context.getCanonicalType(rhptee); 1514 1515 AssignConvertType ConvTy = Compatible; 1516 1517 // C99 6.5.16.1p1: This following citation is common to constraints 1518 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 1519 // qualifiers of the type *pointed to* by the right; 1520 // FIXME: Handle ASQualType 1521 if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) != 1522 rhptee.getCVRQualifiers()) 1523 ConvTy = CompatiblePointerDiscardsQualifiers; 1524 1525 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 1526 // incomplete type and the other is a pointer to a qualified or unqualified 1527 // version of void... 1528 if (lhptee->isVoidType()) { 1529 if (rhptee->isIncompleteOrObjectType()) 1530 return ConvTy; 1531 1532 // As an extension, we allow cast to/from void* to function pointer. 1533 assert(rhptee->isFunctionType()); 1534 return FunctionVoidPointer; 1535 } 1536 1537 if (rhptee->isVoidType()) { 1538 if (lhptee->isIncompleteOrObjectType()) 1539 return ConvTy; 1540 1541 // As an extension, we allow cast to/from void* to function pointer. 1542 assert(lhptee->isFunctionType()); 1543 return FunctionVoidPointer; 1544 } 1545 1546 // Check for ObjC interfaces 1547 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType(); 1548 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType(); 1549 if (LHSIface && RHSIface && 1550 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) 1551 return ConvTy; 1552 1553 // ID acts sort of like void* for ObjC interfaces 1554 if (LHSIface && Context.isObjCIdType(rhptee)) 1555 return ConvTy; 1556 if (RHSIface && Context.isObjCIdType(lhptee)) 1557 return ConvTy; 1558 1559 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 1560 // unqualified versions of compatible types, ... 1561 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(), 1562 rhptee.getUnqualifiedType())) 1563 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers 1564 return ConvTy; 1565} 1566 1567/// CheckBlockPointerTypesForAssignment - This routine determines whether two 1568/// block pointer types are compatible or whether a block and normal pointer 1569/// are compatible. It is more restrict than comparing two function pointer 1570// types. 1571Sema::AssignConvertType 1572Sema::CheckBlockPointerTypesForAssignment(QualType lhsType, 1573 QualType rhsType) { 1574 QualType lhptee, rhptee; 1575 1576 // get the "pointed to" type (ignoring qualifiers at the top level) 1577 lhptee = lhsType->getAsBlockPointerType()->getPointeeType(); 1578 rhptee = rhsType->getAsBlockPointerType()->getPointeeType(); 1579 1580 // make sure we operate on the canonical type 1581 lhptee = Context.getCanonicalType(lhptee); 1582 rhptee = Context.getCanonicalType(rhptee); 1583 1584 AssignConvertType ConvTy = Compatible; 1585 1586 // For blocks we enforce that qualifiers are identical. 1587 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers()) 1588 ConvTy = CompatiblePointerDiscardsQualifiers; 1589 1590 if (!Context.typesAreBlockCompatible(lhptee, rhptee)) 1591 return IncompatibleBlockPointer; 1592 return ConvTy; 1593} 1594 1595/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 1596/// has code to accommodate several GCC extensions when type checking 1597/// pointers. Here are some objectionable examples that GCC considers warnings: 1598/// 1599/// int a, *pint; 1600/// short *pshort; 1601/// struct foo *pfoo; 1602/// 1603/// pint = pshort; // warning: assignment from incompatible pointer type 1604/// a = pint; // warning: assignment makes integer from pointer without a cast 1605/// pint = a; // warning: assignment makes pointer from integer without a cast 1606/// pint = pfoo; // warning: assignment from incompatible pointer type 1607/// 1608/// As a result, the code for dealing with pointers is more complex than the 1609/// C99 spec dictates. 1610/// 1611Sema::AssignConvertType 1612Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) { 1613 // Get canonical types. We're not formatting these types, just comparing 1614 // them. 1615 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType(); 1616 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType(); 1617 1618 if (lhsType == rhsType) 1619 return Compatible; // Common case: fast path an exact match. 1620 1621 if (lhsType->isReferenceType() || rhsType->isReferenceType()) { 1622 if (Context.typesAreCompatible(lhsType, rhsType)) 1623 return Compatible; 1624 return Incompatible; 1625 } 1626 1627 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) { 1628 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false)) 1629 return Compatible; 1630 // Relax integer conversions like we do for pointers below. 1631 if (rhsType->isIntegerType()) 1632 return IntToPointer; 1633 if (lhsType->isIntegerType()) 1634 return PointerToInt; 1635 return Incompatible; 1636 } 1637 1638 if (lhsType->isVectorType() || rhsType->isVectorType()) { 1639 // For ExtVector, allow vector splats; float -> <n x float> 1640 if (const ExtVectorType *LV = lhsType->getAsExtVectorType()) 1641 if (LV->getElementType() == rhsType) 1642 return Compatible; 1643 1644 // If we are allowing lax vector conversions, and LHS and RHS are both 1645 // vectors, the total size only needs to be the same. This is a bitcast; 1646 // no bits are changed but the result type is different. 1647 if (getLangOptions().LaxVectorConversions && 1648 lhsType->isVectorType() && rhsType->isVectorType()) { 1649 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType)) 1650 return Compatible; 1651 } 1652 return Incompatible; 1653 } 1654 1655 if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) 1656 return Compatible; 1657 1658 if (isa<PointerType>(lhsType)) { 1659 if (rhsType->isIntegerType()) 1660 return IntToPointer; 1661 1662 if (isa<PointerType>(rhsType)) 1663 return CheckPointerTypesForAssignment(lhsType, rhsType); 1664 1665 if (rhsType->getAsBlockPointerType()) { 1666 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType()) 1667 return BlockVoidPointer; 1668 1669 // Treat block pointers as objects. 1670 if (getLangOptions().ObjC1 && 1671 lhsType == Context.getCanonicalType(Context.getObjCIdType())) 1672 return Compatible; 1673 } 1674 return Incompatible; 1675 } 1676 1677 if (isa<BlockPointerType>(lhsType)) { 1678 if (rhsType->isIntegerType()) 1679 return IntToPointer; 1680 1681 // Treat block pointers as objects. 1682 if (getLangOptions().ObjC1 && 1683 rhsType == Context.getCanonicalType(Context.getObjCIdType())) 1684 return Compatible; 1685 1686 if (rhsType->isBlockPointerType()) 1687 return CheckBlockPointerTypesForAssignment(lhsType, rhsType); 1688 1689 if (const PointerType *RHSPT = rhsType->getAsPointerType()) { 1690 if (RHSPT->getPointeeType()->isVoidType()) 1691 return BlockVoidPointer; 1692 } 1693 return Incompatible; 1694 } 1695 1696 if (isa<PointerType>(rhsType)) { 1697 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer. 1698 if (lhsType == Context.BoolTy) 1699 return Compatible; 1700 1701 if (lhsType->isIntegerType()) 1702 return PointerToInt; 1703 1704 if (isa<PointerType>(lhsType)) 1705 return CheckPointerTypesForAssignment(lhsType, rhsType); 1706 1707 if (isa<BlockPointerType>(lhsType) && 1708 rhsType->getAsPointerType()->getPointeeType()->isVoidType()) 1709 return BlockVoidPointer; 1710 return Incompatible; 1711 } 1712 1713 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) { 1714 if (Context.typesAreCompatible(lhsType, rhsType)) 1715 return Compatible; 1716 } 1717 return Incompatible; 1718} 1719 1720Sema::AssignConvertType 1721Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) { 1722 // C99 6.5.16.1p1: the left operand is a pointer and the right is 1723 // a null pointer constant. 1724 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() || 1725 lhsType->isBlockPointerType()) 1726 && rExpr->isNullPointerConstant(Context)) { 1727 ImpCastExprToType(rExpr, lhsType); 1728 return Compatible; 1729 } 1730 1731 // We don't allow conversion of non-null-pointer constants to integers. 1732 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType()) 1733 return IntToBlockPointer; 1734 1735 // This check seems unnatural, however it is necessary to ensure the proper 1736 // conversion of functions/arrays. If the conversion were done for all 1737 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary 1738 // expressions that surpress this implicit conversion (&, sizeof). 1739 // 1740 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references 1741 // are better understood. 1742 if (!lhsType->isReferenceType()) 1743 DefaultFunctionArrayConversion(rExpr); 1744 1745 Sema::AssignConvertType result = 1746 CheckAssignmentConstraints(lhsType, rExpr->getType()); 1747 1748 // C99 6.5.16.1p2: The value of the right operand is converted to the 1749 // type of the assignment expression. 1750 if (rExpr->getType() != lhsType) 1751 ImpCastExprToType(rExpr, lhsType); 1752 return result; 1753} 1754 1755Sema::AssignConvertType 1756Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) { 1757 return CheckAssignmentConstraints(lhsType, rhsType); 1758} 1759 1760QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) { 1761 Diag(loc, diag::err_typecheck_invalid_operands, 1762 lex->getType().getAsString(), rex->getType().getAsString(), 1763 lex->getSourceRange(), rex->getSourceRange()); 1764 return QualType(); 1765} 1766 1767inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex, 1768 Expr *&rex) { 1769 // For conversion purposes, we ignore any qualifiers. 1770 // For example, "const float" and "float" are equivalent. 1771 QualType lhsType = 1772 Context.getCanonicalType(lex->getType()).getUnqualifiedType(); 1773 QualType rhsType = 1774 Context.getCanonicalType(rex->getType()).getUnqualifiedType(); 1775 1776 // If the vector types are identical, return. 1777 if (lhsType == rhsType) 1778 return lhsType; 1779 1780 // Handle the case of a vector & extvector type of the same size and element 1781 // type. It would be nice if we only had one vector type someday. 1782 if (getLangOptions().LaxVectorConversions) 1783 if (const VectorType *LV = lhsType->getAsVectorType()) 1784 if (const VectorType *RV = rhsType->getAsVectorType()) 1785 if (LV->getElementType() == RV->getElementType() && 1786 LV->getNumElements() == RV->getNumElements()) 1787 return lhsType->isExtVectorType() ? lhsType : rhsType; 1788 1789 // If the lhs is an extended vector and the rhs is a scalar of the same type 1790 // or a literal, promote the rhs to the vector type. 1791 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) { 1792 QualType eltType = V->getElementType(); 1793 1794 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) || 1795 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) || 1796 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) { 1797 ImpCastExprToType(rex, lhsType); 1798 return lhsType; 1799 } 1800 } 1801 1802 // If the rhs is an extended vector and the lhs is a scalar of the same type, 1803 // promote the lhs to the vector type. 1804 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) { 1805 QualType eltType = V->getElementType(); 1806 1807 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) || 1808 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) || 1809 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) { 1810 ImpCastExprToType(lex, rhsType); 1811 return rhsType; 1812 } 1813 } 1814 1815 // You cannot convert between vector values of different size. 1816 Diag(loc, diag::err_typecheck_vector_not_convertable, 1817 lex->getType().getAsString(), rex->getType().getAsString(), 1818 lex->getSourceRange(), rex->getSourceRange()); 1819 return QualType(); 1820} 1821 1822inline QualType Sema::CheckMultiplyDivideOperands( 1823 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) 1824{ 1825 QualType lhsType = lex->getType(), rhsType = rex->getType(); 1826 1827 if (lhsType->isVectorType() || rhsType->isVectorType()) 1828 return CheckVectorOperands(loc, lex, rex); 1829 1830 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 1831 1832 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 1833 return compType; 1834 return InvalidOperands(loc, lex, rex); 1835} 1836 1837inline QualType Sema::CheckRemainderOperands( 1838 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) 1839{ 1840 QualType lhsType = lex->getType(), rhsType = rex->getType(); 1841 1842 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 1843 1844 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType()) 1845 return compType; 1846 return InvalidOperands(loc, lex, rex); 1847} 1848 1849inline QualType Sema::CheckAdditionOperands( // C99 6.5.6 1850 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) 1851{ 1852 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 1853 return CheckVectorOperands(loc, lex, rex); 1854 1855 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 1856 1857 // handle the common case first (both operands are arithmetic). 1858 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 1859 return compType; 1860 1861 // Put any potential pointer into PExp 1862 Expr* PExp = lex, *IExp = rex; 1863 if (IExp->getType()->isPointerType()) 1864 std::swap(PExp, IExp); 1865 1866 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) { 1867 if (IExp->getType()->isIntegerType()) { 1868 // Check for arithmetic on pointers to incomplete types 1869 if (!PTy->getPointeeType()->isObjectType()) { 1870 if (PTy->getPointeeType()->isVoidType()) { 1871 Diag(loc, diag::ext_gnu_void_ptr, 1872 lex->getSourceRange(), rex->getSourceRange()); 1873 } else { 1874 Diag(loc, diag::err_typecheck_arithmetic_incomplete_type, 1875 lex->getType().getAsString(), lex->getSourceRange()); 1876 return QualType(); 1877 } 1878 } 1879 return PExp->getType(); 1880 } 1881 } 1882 1883 return InvalidOperands(loc, lex, rex); 1884} 1885 1886// C99 6.5.6 1887QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex, 1888 SourceLocation loc, bool isCompAssign) { 1889 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 1890 return CheckVectorOperands(loc, lex, rex); 1891 1892 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 1893 1894 // Enforce type constraints: C99 6.5.6p3. 1895 1896 // Handle the common case first (both operands are arithmetic). 1897 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 1898 return compType; 1899 1900 // Either ptr - int or ptr - ptr. 1901 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) { 1902 QualType lpointee = LHSPTy->getPointeeType(); 1903 1904 // The LHS must be an object type, not incomplete, function, etc. 1905 if (!lpointee->isObjectType()) { 1906 // Handle the GNU void* extension. 1907 if (lpointee->isVoidType()) { 1908 Diag(loc, diag::ext_gnu_void_ptr, 1909 lex->getSourceRange(), rex->getSourceRange()); 1910 } else { 1911 Diag(loc, diag::err_typecheck_sub_ptr_object, 1912 lex->getType().getAsString(), lex->getSourceRange()); 1913 return QualType(); 1914 } 1915 } 1916 1917 // The result type of a pointer-int computation is the pointer type. 1918 if (rex->getType()->isIntegerType()) 1919 return lex->getType(); 1920 1921 // Handle pointer-pointer subtractions. 1922 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) { 1923 QualType rpointee = RHSPTy->getPointeeType(); 1924 1925 // RHS must be an object type, unless void (GNU). 1926 if (!rpointee->isObjectType()) { 1927 // Handle the GNU void* extension. 1928 if (rpointee->isVoidType()) { 1929 if (!lpointee->isVoidType()) 1930 Diag(loc, diag::ext_gnu_void_ptr, 1931 lex->getSourceRange(), rex->getSourceRange()); 1932 } else { 1933 Diag(loc, diag::err_typecheck_sub_ptr_object, 1934 rex->getType().getAsString(), rex->getSourceRange()); 1935 return QualType(); 1936 } 1937 } 1938 1939 // Pointee types must be compatible. 1940 if (!Context.typesAreCompatible( 1941 Context.getCanonicalType(lpointee).getUnqualifiedType(), 1942 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 1943 Diag(loc, diag::err_typecheck_sub_ptr_compatible, 1944 lex->getType().getAsString(), rex->getType().getAsString(), 1945 lex->getSourceRange(), rex->getSourceRange()); 1946 return QualType(); 1947 } 1948 1949 return Context.getPointerDiffType(); 1950 } 1951 } 1952 1953 return InvalidOperands(loc, lex, rex); 1954} 1955 1956// C99 6.5.7 1957QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc, 1958 bool isCompAssign) { 1959 // C99 6.5.7p2: Each of the operands shall have integer type. 1960 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType()) 1961 return InvalidOperands(loc, lex, rex); 1962 1963 // Shifts don't perform usual arithmetic conversions, they just do integer 1964 // promotions on each operand. C99 6.5.7p3 1965 if (!isCompAssign) 1966 UsualUnaryConversions(lex); 1967 UsualUnaryConversions(rex); 1968 1969 // "The type of the result is that of the promoted left operand." 1970 return lex->getType(); 1971} 1972 1973static bool areComparableObjCInterfaces(QualType LHS, QualType RHS, 1974 ASTContext& Context) { 1975 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType(); 1976 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType(); 1977 // ID acts sort of like void* for ObjC interfaces 1978 if (LHSIface && Context.isObjCIdType(RHS)) 1979 return true; 1980 if (RHSIface && Context.isObjCIdType(LHS)) 1981 return true; 1982 if (!LHSIface || !RHSIface) 1983 return false; 1984 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) || 1985 Context.canAssignObjCInterfaces(RHSIface, LHSIface); 1986} 1987 1988// C99 6.5.8 1989QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc, 1990 bool isRelational) { 1991 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 1992 return CheckVectorCompareOperands(lex, rex, loc, isRelational); 1993 1994 // C99 6.5.8p3 / C99 6.5.9p4 1995 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 1996 UsualArithmeticConversions(lex, rex); 1997 else { 1998 UsualUnaryConversions(lex); 1999 UsualUnaryConversions(rex); 2000 } 2001 QualType lType = lex->getType(); 2002 QualType rType = rex->getType(); 2003 2004 // For non-floating point types, check for self-comparisons of the form 2005 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 2006 // often indicate logic errors in the program. 2007 if (!lType->isFloatingType()) { 2008 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens())) 2009 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens())) 2010 if (DRL->getDecl() == DRR->getDecl()) 2011 Diag(loc, diag::warn_selfcomparison); 2012 } 2013 2014 if (isRelational) { 2015 if (lType->isRealType() && rType->isRealType()) 2016 return Context.IntTy; 2017 } else { 2018 // Check for comparisons of floating point operands using != and ==. 2019 if (lType->isFloatingType()) { 2020 assert (rType->isFloatingType()); 2021 CheckFloatComparison(loc,lex,rex); 2022 } 2023 2024 if (lType->isArithmeticType() && rType->isArithmeticType()) 2025 return Context.IntTy; 2026 } 2027 2028 bool LHSIsNull = lex->isNullPointerConstant(Context); 2029 bool RHSIsNull = rex->isNullPointerConstant(Context); 2030 2031 // All of the following pointer related warnings are GCC extensions, except 2032 // when handling null pointer constants. One day, we can consider making them 2033 // errors (when -pedantic-errors is enabled). 2034 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2 2035 QualType LCanPointeeTy = 2036 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType()); 2037 QualType RCanPointeeTy = 2038 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType()); 2039 2040 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2 2041 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() && 2042 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 2043 RCanPointeeTy.getUnqualifiedType()) && 2044 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) { 2045 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers, 2046 lType.getAsString(), rType.getAsString(), 2047 lex->getSourceRange(), rex->getSourceRange()); 2048 } 2049 ImpCastExprToType(rex, lType); // promote the pointer to pointer 2050 return Context.IntTy; 2051 } 2052 // Handle block pointer types. 2053 if (lType->isBlockPointerType() && rType->isBlockPointerType()) { 2054 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType(); 2055 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType(); 2056 2057 if (!LHSIsNull && !RHSIsNull && 2058 !Context.typesAreBlockCompatible(lpointee, rpointee)) { 2059 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks, 2060 lType.getAsString(), rType.getAsString(), 2061 lex->getSourceRange(), rex->getSourceRange()); 2062 } 2063 ImpCastExprToType(rex, lType); // promote the pointer to pointer 2064 return Context.IntTy; 2065 } 2066 // Allow block pointers to be compared with null pointer constants. 2067 if ((lType->isBlockPointerType() && rType->isPointerType()) || 2068 (lType->isPointerType() && rType->isBlockPointerType())) { 2069 if (!LHSIsNull && !RHSIsNull) { 2070 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks, 2071 lType.getAsString(), rType.getAsString(), 2072 lex->getSourceRange(), rex->getSourceRange()); 2073 } 2074 ImpCastExprToType(rex, lType); // promote the pointer to pointer 2075 return Context.IntTy; 2076 } 2077 2078 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) { 2079 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) { 2080 ImpCastExprToType(rex, lType); 2081 return Context.IntTy; 2082 } 2083 } 2084 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) && 2085 rType->isIntegerType()) { 2086 if (!RHSIsNull) 2087 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer, 2088 lType.getAsString(), rType.getAsString(), 2089 lex->getSourceRange(), rex->getSourceRange()); 2090 ImpCastExprToType(rex, lType); // promote the integer to pointer 2091 return Context.IntTy; 2092 } 2093 if (lType->isIntegerType() && 2094 (rType->isPointerType() || rType->isObjCQualifiedIdType())) { 2095 if (!LHSIsNull) 2096 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer, 2097 lType.getAsString(), rType.getAsString(), 2098 lex->getSourceRange(), rex->getSourceRange()); 2099 ImpCastExprToType(lex, rType); // promote the integer to pointer 2100 return Context.IntTy; 2101 } 2102 // Handle block pointers. 2103 if (lType->isBlockPointerType() && rType->isIntegerType()) { 2104 if (!RHSIsNull) 2105 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer, 2106 lType.getAsString(), rType.getAsString(), 2107 lex->getSourceRange(), rex->getSourceRange()); 2108 ImpCastExprToType(rex, lType); // promote the integer to pointer 2109 return Context.IntTy; 2110 } 2111 if (lType->isIntegerType() && rType->isBlockPointerType()) { 2112 if (!LHSIsNull) 2113 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer, 2114 lType.getAsString(), rType.getAsString(), 2115 lex->getSourceRange(), rex->getSourceRange()); 2116 ImpCastExprToType(lex, rType); // promote the integer to pointer 2117 return Context.IntTy; 2118 } 2119 return InvalidOperands(loc, lex, rex); 2120} 2121 2122/// CheckVectorCompareOperands - vector comparisons are a clang extension that 2123/// operates on extended vector types. Instead of producing an IntTy result, 2124/// like a scalar comparison, a vector comparison produces a vector of integer 2125/// types. 2126QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex, 2127 SourceLocation loc, 2128 bool isRelational) { 2129 // Check to make sure we're operating on vectors of the same type and width, 2130 // Allowing one side to be a scalar of element type. 2131 QualType vType = CheckVectorOperands(loc, lex, rex); 2132 if (vType.isNull()) 2133 return vType; 2134 2135 QualType lType = lex->getType(); 2136 QualType rType = rex->getType(); 2137 2138 // For non-floating point types, check for self-comparisons of the form 2139 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 2140 // often indicate logic errors in the program. 2141 if (!lType->isFloatingType()) { 2142 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens())) 2143 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens())) 2144 if (DRL->getDecl() == DRR->getDecl()) 2145 Diag(loc, diag::warn_selfcomparison); 2146 } 2147 2148 // Check for comparisons of floating point operands using != and ==. 2149 if (!isRelational && lType->isFloatingType()) { 2150 assert (rType->isFloatingType()); 2151 CheckFloatComparison(loc,lex,rex); 2152 } 2153 2154 // Return the type for the comparison, which is the same as vector type for 2155 // integer vectors, or an integer type of identical size and number of 2156 // elements for floating point vectors. 2157 if (lType->isIntegerType()) 2158 return lType; 2159 2160 const VectorType *VTy = lType->getAsVectorType(); 2161 2162 // FIXME: need to deal with non-32b int / non-64b long long 2163 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 2164 if (TypeSize == 32) { 2165 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 2166 } 2167 assert(TypeSize == 64 && "Unhandled vector element size in vector compare"); 2168 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 2169} 2170 2171inline QualType Sema::CheckBitwiseOperands( 2172 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) 2173{ 2174 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 2175 return CheckVectorOperands(loc, lex, rex); 2176 2177 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 2178 2179 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType()) 2180 return compType; 2181 return InvalidOperands(loc, lex, rex); 2182} 2183 2184inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 2185 Expr *&lex, Expr *&rex, SourceLocation loc) 2186{ 2187 UsualUnaryConversions(lex); 2188 UsualUnaryConversions(rex); 2189 2190 if (lex->getType()->isScalarType() && rex->getType()->isScalarType()) 2191 return Context.IntTy; 2192 return InvalidOperands(loc, lex, rex); 2193} 2194 2195inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1 2196 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType) 2197{ 2198 QualType lhsType = lex->getType(); 2199 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType; 2200 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue(Context); 2201 2202 switch (mlval) { // C99 6.5.16p2 2203 case Expr::MLV_Valid: 2204 break; 2205 case Expr::MLV_ConstQualified: 2206 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange()); 2207 return QualType(); 2208 case Expr::MLV_ArrayType: 2209 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue, 2210 lhsType.getAsString(), lex->getSourceRange()); 2211 return QualType(); 2212 case Expr::MLV_NotObjectType: 2213 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue, 2214 lhsType.getAsString(), lex->getSourceRange()); 2215 return QualType(); 2216 case Expr::MLV_InvalidExpression: 2217 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue, 2218 lex->getSourceRange()); 2219 return QualType(); 2220 case Expr::MLV_IncompleteType: 2221 case Expr::MLV_IncompleteVoidType: 2222 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue, 2223 lhsType.getAsString(), lex->getSourceRange()); 2224 return QualType(); 2225 case Expr::MLV_DuplicateVectorComponents: 2226 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue, 2227 lex->getSourceRange()); 2228 return QualType(); 2229 case Expr::MLV_NotBlockQualified: 2230 Diag(loc, diag::err_block_decl_ref_not_modifiable_lvalue, 2231 lex->getSourceRange()); 2232 return QualType(); 2233 } 2234 2235 AssignConvertType ConvTy; 2236 if (compoundType.isNull()) { 2237 // Simple assignment "x = y". 2238 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex); 2239 2240 // If the RHS is a unary plus or minus, check to see if they = and + are 2241 // right next to each other. If so, the user may have typo'd "x =+ 4" 2242 // instead of "x += 4". 2243 Expr *RHSCheck = rex; 2244 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 2245 RHSCheck = ICE->getSubExpr(); 2246 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 2247 if ((UO->getOpcode() == UnaryOperator::Plus || 2248 UO->getOpcode() == UnaryOperator::Minus) && 2249 loc.isFileID() && UO->getOperatorLoc().isFileID() && 2250 // Only if the two operators are exactly adjacent. 2251 loc.getFileLocWithOffset(1) == UO->getOperatorLoc()) 2252 Diag(loc, diag::warn_not_compound_assign, 2253 UO->getOpcode() == UnaryOperator::Plus ? "+" : "-", 2254 SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc())); 2255 } 2256 } else { 2257 // Compound assignment "x += y" 2258 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType); 2259 } 2260 2261 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType, 2262 rex, "assigning")) 2263 return QualType(); 2264 2265 // C99 6.5.16p3: The type of an assignment expression is the type of the 2266 // left operand unless the left operand has qualified type, in which case 2267 // it is the unqualified version of the type of the left operand. 2268 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 2269 // is converted to the type of the assignment expression (above). 2270 // C++ 5.17p1: the type of the assignment expression is that of its left 2271 // oprdu. 2272 return lhsType.getUnqualifiedType(); 2273} 2274 2275inline QualType Sema::CheckCommaOperands( // C99 6.5.17 2276 Expr *&lex, Expr *&rex, SourceLocation loc) { 2277 2278 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions. 2279 DefaultFunctionArrayConversion(rex); 2280 return rex->getType(); 2281} 2282 2283/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 2284/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 2285QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) { 2286 QualType resType = op->getType(); 2287 assert(!resType.isNull() && "no type for increment/decrement expression"); 2288 2289 // C99 6.5.2.4p1: We allow complex as a GCC extension. 2290 if (const PointerType *pt = resType->getAsPointerType()) { 2291 if (pt->getPointeeType()->isVoidType()) { 2292 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange()); 2293 } else if (!pt->getPointeeType()->isObjectType()) { 2294 // C99 6.5.2.4p2, 6.5.6p2 2295 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type, 2296 resType.getAsString(), op->getSourceRange()); 2297 return QualType(); 2298 } 2299 } else if (!resType->isRealType()) { 2300 if (resType->isComplexType()) 2301 // C99 does not support ++/-- on complex types. 2302 Diag(OpLoc, diag::ext_integer_increment_complex, 2303 resType.getAsString(), op->getSourceRange()); 2304 else { 2305 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement, 2306 resType.getAsString(), op->getSourceRange()); 2307 return QualType(); 2308 } 2309 } 2310 // At this point, we know we have a real, complex or pointer type. 2311 // Now make sure the operand is a modifiable lvalue. 2312 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue(Context); 2313 if (mlval != Expr::MLV_Valid) { 2314 // FIXME: emit a more precise diagnostic... 2315 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr, 2316 op->getSourceRange()); 2317 return QualType(); 2318 } 2319 return resType; 2320} 2321 2322/// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 2323/// This routine allows us to typecheck complex/recursive expressions 2324/// where the declaration is needed for type checking. We only need to 2325/// handle cases when the expression references a function designator 2326/// or is an lvalue. Here are some examples: 2327/// - &(x) => x 2328/// - &*****f => f for f a function designator. 2329/// - &s.xx => s 2330/// - &s.zz[1].yy -> s, if zz is an array 2331/// - *(x + 1) -> x, if x is an array 2332/// - &"123"[2] -> 0 2333/// - & __real__ x -> x 2334static ValueDecl *getPrimaryDecl(Expr *E) { 2335 switch (E->getStmtClass()) { 2336 case Stmt::DeclRefExprClass: 2337 return cast<DeclRefExpr>(E)->getDecl(); 2338 case Stmt::MemberExprClass: 2339 // Fields cannot be declared with a 'register' storage class. 2340 // &X->f is always ok, even if X is declared register. 2341 if (cast<MemberExpr>(E)->isArrow()) 2342 return 0; 2343 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 2344 case Stmt::ArraySubscriptExprClass: { 2345 // &X[4] and &4[X] refers to X if X is not a pointer. 2346 2347 ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase()); 2348 if (!VD || VD->getType()->isPointerType()) 2349 return 0; 2350 else 2351 return VD; 2352 } 2353 case Stmt::UnaryOperatorClass: { 2354 UnaryOperator *UO = cast<UnaryOperator>(E); 2355 2356 switch(UO->getOpcode()) { 2357 case UnaryOperator::Deref: { 2358 // *(X + 1) refers to X if X is not a pointer. 2359 ValueDecl *VD = getPrimaryDecl(UO->getSubExpr()); 2360 if (!VD || VD->getType()->isPointerType()) 2361 return 0; 2362 return VD; 2363 } 2364 case UnaryOperator::Real: 2365 case UnaryOperator::Imag: 2366 case UnaryOperator::Extension: 2367 return getPrimaryDecl(UO->getSubExpr()); 2368 default: 2369 return 0; 2370 } 2371 } 2372 case Stmt::BinaryOperatorClass: { 2373 BinaryOperator *BO = cast<BinaryOperator>(E); 2374 2375 // Handle cases involving pointer arithmetic. The result of an 2376 // Assign or AddAssign is not an lvalue so they can be ignored. 2377 2378 // (x + n) or (n + x) => x 2379 if (BO->getOpcode() == BinaryOperator::Add) { 2380 if (BO->getLHS()->getType()->isPointerType()) { 2381 return getPrimaryDecl(BO->getLHS()); 2382 } else if (BO->getRHS()->getType()->isPointerType()) { 2383 return getPrimaryDecl(BO->getRHS()); 2384 } 2385 } 2386 2387 return 0; 2388 } 2389 case Stmt::ParenExprClass: 2390 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 2391 case Stmt::ImplicitCastExprClass: 2392 // &X[4] when X is an array, has an implicit cast from array to pointer. 2393 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 2394 default: 2395 return 0; 2396 } 2397} 2398 2399/// CheckAddressOfOperand - The operand of & must be either a function 2400/// designator or an lvalue designating an object. If it is an lvalue, the 2401/// object cannot be declared with storage class register or be a bit field. 2402/// Note: The usual conversions are *not* applied to the operand of the & 2403/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 2404QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) { 2405 if (getLangOptions().C99) { 2406 // Implement C99-only parts of addressof rules. 2407 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 2408 if (uOp->getOpcode() == UnaryOperator::Deref) 2409 // Per C99 6.5.3.2, the address of a deref always returns a valid result 2410 // (assuming the deref expression is valid). 2411 return uOp->getSubExpr()->getType(); 2412 } 2413 // Technically, there should be a check for array subscript 2414 // expressions here, but the result of one is always an lvalue anyway. 2415 } 2416 ValueDecl *dcl = getPrimaryDecl(op); 2417 Expr::isLvalueResult lval = op->isLvalue(Context); 2418 2419 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1 2420 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators 2421 // FIXME: emit more specific diag... 2422 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof, 2423 op->getSourceRange()); 2424 return QualType(); 2425 } 2426 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1 2427 if (MemExpr->getMemberDecl()->isBitField()) { 2428 Diag(OpLoc, diag::err_typecheck_address_of, 2429 std::string("bit-field"), op->getSourceRange()); 2430 return QualType(); 2431 } 2432 // Check for Apple extension for accessing vector components. 2433 } else if (isa<ArraySubscriptExpr>(op) && 2434 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) { 2435 Diag(OpLoc, diag::err_typecheck_address_of, 2436 std::string("vector"), op->getSourceRange()); 2437 return QualType(); 2438 } else if (dcl) { // C99 6.5.3.2p1 2439 // We have an lvalue with a decl. Make sure the decl is not declared 2440 // with the register storage-class specifier. 2441 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 2442 if (vd->getStorageClass() == VarDecl::Register) { 2443 Diag(OpLoc, diag::err_typecheck_address_of, 2444 std::string("register variable"), op->getSourceRange()); 2445 return QualType(); 2446 } 2447 } else 2448 assert(0 && "Unknown/unexpected decl type"); 2449 } 2450 2451 // If the operand has type "type", the result has type "pointer to type". 2452 return Context.getPointerType(op->getType()); 2453} 2454 2455QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) { 2456 UsualUnaryConversions(op); 2457 QualType qType = op->getType(); 2458 2459 if (const PointerType *PT = qType->getAsPointerType()) { 2460 // Note that per both C89 and C99, this is always legal, even 2461 // if ptype is an incomplete type or void. 2462 // It would be possible to warn about dereferencing a 2463 // void pointer, but it's completely well-defined, 2464 // and such a warning is unlikely to catch any mistakes. 2465 return PT->getPointeeType(); 2466 } 2467 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer, 2468 qType.getAsString(), op->getSourceRange()); 2469 return QualType(); 2470} 2471 2472static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode( 2473 tok::TokenKind Kind) { 2474 BinaryOperator::Opcode Opc; 2475 switch (Kind) { 2476 default: assert(0 && "Unknown binop!"); 2477 case tok::star: Opc = BinaryOperator::Mul; break; 2478 case tok::slash: Opc = BinaryOperator::Div; break; 2479 case tok::percent: Opc = BinaryOperator::Rem; break; 2480 case tok::plus: Opc = BinaryOperator::Add; break; 2481 case tok::minus: Opc = BinaryOperator::Sub; break; 2482 case tok::lessless: Opc = BinaryOperator::Shl; break; 2483 case tok::greatergreater: Opc = BinaryOperator::Shr; break; 2484 case tok::lessequal: Opc = BinaryOperator::LE; break; 2485 case tok::less: Opc = BinaryOperator::LT; break; 2486 case tok::greaterequal: Opc = BinaryOperator::GE; break; 2487 case tok::greater: Opc = BinaryOperator::GT; break; 2488 case tok::exclaimequal: Opc = BinaryOperator::NE; break; 2489 case tok::equalequal: Opc = BinaryOperator::EQ; break; 2490 case tok::amp: Opc = BinaryOperator::And; break; 2491 case tok::caret: Opc = BinaryOperator::Xor; break; 2492 case tok::pipe: Opc = BinaryOperator::Or; break; 2493 case tok::ampamp: Opc = BinaryOperator::LAnd; break; 2494 case tok::pipepipe: Opc = BinaryOperator::LOr; break; 2495 case tok::equal: Opc = BinaryOperator::Assign; break; 2496 case tok::starequal: Opc = BinaryOperator::MulAssign; break; 2497 case tok::slashequal: Opc = BinaryOperator::DivAssign; break; 2498 case tok::percentequal: Opc = BinaryOperator::RemAssign; break; 2499 case tok::plusequal: Opc = BinaryOperator::AddAssign; break; 2500 case tok::minusequal: Opc = BinaryOperator::SubAssign; break; 2501 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break; 2502 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break; 2503 case tok::ampequal: Opc = BinaryOperator::AndAssign; break; 2504 case tok::caretequal: Opc = BinaryOperator::XorAssign; break; 2505 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break; 2506 case tok::comma: Opc = BinaryOperator::Comma; break; 2507 } 2508 return Opc; 2509} 2510 2511static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode( 2512 tok::TokenKind Kind) { 2513 UnaryOperator::Opcode Opc; 2514 switch (Kind) { 2515 default: assert(0 && "Unknown unary op!"); 2516 case tok::plusplus: Opc = UnaryOperator::PreInc; break; 2517 case tok::minusminus: Opc = UnaryOperator::PreDec; break; 2518 case tok::amp: Opc = UnaryOperator::AddrOf; break; 2519 case tok::star: Opc = UnaryOperator::Deref; break; 2520 case tok::plus: Opc = UnaryOperator::Plus; break; 2521 case tok::minus: Opc = UnaryOperator::Minus; break; 2522 case tok::tilde: Opc = UnaryOperator::Not; break; 2523 case tok::exclaim: Opc = UnaryOperator::LNot; break; 2524 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break; 2525 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break; 2526 case tok::kw___real: Opc = UnaryOperator::Real; break; 2527 case tok::kw___imag: Opc = UnaryOperator::Imag; break; 2528 case tok::kw___extension__: Opc = UnaryOperator::Extension; break; 2529 } 2530 return Opc; 2531} 2532 2533// Binary Operators. 'Tok' is the token for the operator. 2534Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind, 2535 ExprTy *LHS, ExprTy *RHS) { 2536 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind); 2537 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS; 2538 2539 assert((lhs != 0) && "ActOnBinOp(): missing left expression"); 2540 assert((rhs != 0) && "ActOnBinOp(): missing right expression"); 2541 2542 QualType ResultTy; // Result type of the binary operator. 2543 QualType CompTy; // Computation type for compound assignments (e.g. '+=') 2544 2545 switch (Opc) { 2546 default: 2547 assert(0 && "Unknown binary expr!"); 2548 case BinaryOperator::Assign: 2549 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType()); 2550 break; 2551 case BinaryOperator::Mul: 2552 case BinaryOperator::Div: 2553 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc); 2554 break; 2555 case BinaryOperator::Rem: 2556 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc); 2557 break; 2558 case BinaryOperator::Add: 2559 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc); 2560 break; 2561 case BinaryOperator::Sub: 2562 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc); 2563 break; 2564 case BinaryOperator::Shl: 2565 case BinaryOperator::Shr: 2566 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc); 2567 break; 2568 case BinaryOperator::LE: 2569 case BinaryOperator::LT: 2570 case BinaryOperator::GE: 2571 case BinaryOperator::GT: 2572 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true); 2573 break; 2574 case BinaryOperator::EQ: 2575 case BinaryOperator::NE: 2576 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false); 2577 break; 2578 case BinaryOperator::And: 2579 case BinaryOperator::Xor: 2580 case BinaryOperator::Or: 2581 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc); 2582 break; 2583 case BinaryOperator::LAnd: 2584 case BinaryOperator::LOr: 2585 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc); 2586 break; 2587 case BinaryOperator::MulAssign: 2588 case BinaryOperator::DivAssign: 2589 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true); 2590 if (!CompTy.isNull()) 2591 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy); 2592 break; 2593 case BinaryOperator::RemAssign: 2594 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true); 2595 if (!CompTy.isNull()) 2596 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy); 2597 break; 2598 case BinaryOperator::AddAssign: 2599 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true); 2600 if (!CompTy.isNull()) 2601 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy); 2602 break; 2603 case BinaryOperator::SubAssign: 2604 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true); 2605 if (!CompTy.isNull()) 2606 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy); 2607 break; 2608 case BinaryOperator::ShlAssign: 2609 case BinaryOperator::ShrAssign: 2610 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true); 2611 if (!CompTy.isNull()) 2612 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy); 2613 break; 2614 case BinaryOperator::AndAssign: 2615 case BinaryOperator::XorAssign: 2616 case BinaryOperator::OrAssign: 2617 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true); 2618 if (!CompTy.isNull()) 2619 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy); 2620 break; 2621 case BinaryOperator::Comma: 2622 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc); 2623 break; 2624 } 2625 if (ResultTy.isNull()) 2626 return true; 2627 if (CompTy.isNull()) 2628 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc); 2629 else 2630 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc); 2631} 2632 2633// Unary Operators. 'Tok' is the token for the operator. 2634Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op, 2635 ExprTy *input) { 2636 Expr *Input = (Expr*)input; 2637 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op); 2638 QualType resultType; 2639 switch (Opc) { 2640 default: 2641 assert(0 && "Unimplemented unary expr!"); 2642 case UnaryOperator::PreInc: 2643 case UnaryOperator::PreDec: 2644 resultType = CheckIncrementDecrementOperand(Input, OpLoc); 2645 break; 2646 case UnaryOperator::AddrOf: 2647 resultType = CheckAddressOfOperand(Input, OpLoc); 2648 break; 2649 case UnaryOperator::Deref: 2650 DefaultFunctionArrayConversion(Input); 2651 resultType = CheckIndirectionOperand(Input, OpLoc); 2652 break; 2653 case UnaryOperator::Plus: 2654 case UnaryOperator::Minus: 2655 UsualUnaryConversions(Input); 2656 resultType = Input->getType(); 2657 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1 2658 return Diag(OpLoc, diag::err_typecheck_unary_expr, 2659 resultType.getAsString()); 2660 break; 2661 case UnaryOperator::Not: // bitwise complement 2662 UsualUnaryConversions(Input); 2663 resultType = Input->getType(); 2664 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 2665 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 2666 // C99 does not support '~' for complex conjugation. 2667 Diag(OpLoc, diag::ext_integer_complement_complex, 2668 resultType.getAsString(), Input->getSourceRange()); 2669 else if (!resultType->isIntegerType()) 2670 return Diag(OpLoc, diag::err_typecheck_unary_expr, 2671 resultType.getAsString(), Input->getSourceRange()); 2672 break; 2673 case UnaryOperator::LNot: // logical negation 2674 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 2675 DefaultFunctionArrayConversion(Input); 2676 resultType = Input->getType(); 2677 if (!resultType->isScalarType()) // C99 6.5.3.3p1 2678 return Diag(OpLoc, diag::err_typecheck_unary_expr, 2679 resultType.getAsString()); 2680 // LNot always has type int. C99 6.5.3.3p5. 2681 resultType = Context.IntTy; 2682 break; 2683 case UnaryOperator::SizeOf: 2684 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, 2685 Input->getSourceRange(), true); 2686 break; 2687 case UnaryOperator::AlignOf: 2688 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, 2689 Input->getSourceRange(), false); 2690 break; 2691 case UnaryOperator::Real: 2692 case UnaryOperator::Imag: 2693 resultType = CheckRealImagOperand(Input, OpLoc); 2694 break; 2695 case UnaryOperator::Extension: 2696 resultType = Input->getType(); 2697 break; 2698 } 2699 if (resultType.isNull()) 2700 return true; 2701 return new UnaryOperator(Input, Opc, resultType, OpLoc); 2702} 2703 2704/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 2705Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, 2706 SourceLocation LabLoc, 2707 IdentifierInfo *LabelII) { 2708 // Look up the record for this label identifier. 2709 LabelStmt *&LabelDecl = LabelMap[LabelII]; 2710 2711 // If we haven't seen this label yet, create a forward reference. It 2712 // will be validated and/or cleaned up in ActOnFinishFunctionBody. 2713 if (LabelDecl == 0) 2714 LabelDecl = new LabelStmt(LabLoc, LabelII, 0); 2715 2716 // Create the AST node. The address of a label always has type 'void*'. 2717 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl, 2718 Context.getPointerType(Context.VoidTy)); 2719} 2720 2721Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt, 2722 SourceLocation RPLoc) { // "({..})" 2723 Stmt *SubStmt = static_cast<Stmt*>(substmt); 2724 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 2725 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 2726 2727 // FIXME: there are a variety of strange constraints to enforce here, for 2728 // example, it is not possible to goto into a stmt expression apparently. 2729 // More semantic analysis is needed. 2730 2731 // FIXME: the last statement in the compount stmt has its value used. We 2732 // should not warn about it being unused. 2733 2734 // If there are sub stmts in the compound stmt, take the type of the last one 2735 // as the type of the stmtexpr. 2736 QualType Ty = Context.VoidTy; 2737 2738 if (!Compound->body_empty()) { 2739 Stmt *LastStmt = Compound->body_back(); 2740 // If LastStmt is a label, skip down through into the body. 2741 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) 2742 LastStmt = Label->getSubStmt(); 2743 2744 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) 2745 Ty = LastExpr->getType(); 2746 } 2747 2748 return new StmtExpr(Compound, Ty, LPLoc, RPLoc); 2749} 2750 2751Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc, 2752 SourceLocation TypeLoc, 2753 TypeTy *argty, 2754 OffsetOfComponent *CompPtr, 2755 unsigned NumComponents, 2756 SourceLocation RPLoc) { 2757 QualType ArgTy = QualType::getFromOpaquePtr(argty); 2758 assert(!ArgTy.isNull() && "Missing type argument!"); 2759 2760 // We must have at least one component that refers to the type, and the first 2761 // one is known to be a field designator. Verify that the ArgTy represents 2762 // a struct/union/class. 2763 if (!ArgTy->isRecordType()) 2764 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString()); 2765 2766 // Otherwise, create a compound literal expression as the base, and 2767 // iteratively process the offsetof designators. 2768 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false); 2769 2770 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 2771 // GCC extension, diagnose them. 2772 if (NumComponents != 1) 2773 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator, 2774 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd)); 2775 2776 for (unsigned i = 0; i != NumComponents; ++i) { 2777 const OffsetOfComponent &OC = CompPtr[i]; 2778 if (OC.isBrackets) { 2779 // Offset of an array sub-field. TODO: Should we allow vector elements? 2780 const ArrayType *AT = Context.getAsArrayType(Res->getType()); 2781 if (!AT) { 2782 delete Res; 2783 return Diag(OC.LocEnd, diag::err_offsetof_array_type, 2784 Res->getType().getAsString()); 2785 } 2786 2787 // FIXME: C++: Verify that operator[] isn't overloaded. 2788 2789 // C99 6.5.2.1p1 2790 Expr *Idx = static_cast<Expr*>(OC.U.E); 2791 if (!Idx->getType()->isIntegerType()) 2792 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript, 2793 Idx->getSourceRange()); 2794 2795 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd); 2796 continue; 2797 } 2798 2799 const RecordType *RC = Res->getType()->getAsRecordType(); 2800 if (!RC) { 2801 delete Res; 2802 return Diag(OC.LocEnd, diag::err_offsetof_record_type, 2803 Res->getType().getAsString()); 2804 } 2805 2806 // Get the decl corresponding to this. 2807 RecordDecl *RD = RC->getDecl(); 2808 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo); 2809 if (!MemberDecl) 2810 return Diag(BuiltinLoc, diag::err_typecheck_no_member, 2811 OC.U.IdentInfo->getName(), 2812 SourceRange(OC.LocStart, OC.LocEnd)); 2813 2814 // FIXME: C++: Verify that MemberDecl isn't a static field. 2815 // FIXME: Verify that MemberDecl isn't a bitfield. 2816 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't 2817 // matter here. 2818 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType()); 2819 } 2820 2821 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(), 2822 BuiltinLoc); 2823} 2824 2825 2826Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc, 2827 TypeTy *arg1, TypeTy *arg2, 2828 SourceLocation RPLoc) { 2829 QualType argT1 = QualType::getFromOpaquePtr(arg1); 2830 QualType argT2 = QualType::getFromOpaquePtr(arg2); 2831 2832 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)"); 2833 2834 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc); 2835} 2836 2837Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond, 2838 ExprTy *expr1, ExprTy *expr2, 2839 SourceLocation RPLoc) { 2840 Expr *CondExpr = static_cast<Expr*>(cond); 2841 Expr *LHSExpr = static_cast<Expr*>(expr1); 2842 Expr *RHSExpr = static_cast<Expr*>(expr2); 2843 2844 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 2845 2846 // The conditional expression is required to be a constant expression. 2847 llvm::APSInt condEval(32); 2848 SourceLocation ExpLoc; 2849 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc)) 2850 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant, 2851 CondExpr->getSourceRange()); 2852 2853 // If the condition is > zero, then the AST type is the same as the LSHExpr. 2854 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() : 2855 RHSExpr->getType(); 2856 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc); 2857} 2858 2859//===----------------------------------------------------------------------===// 2860// Clang Extensions. 2861//===----------------------------------------------------------------------===// 2862 2863/// ActOnBlockStart - This callback is invoked when a block literal is started. 2864void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope, 2865 Declarator &ParamInfo) { 2866 // Analyze block parameters. 2867 BlockSemaInfo *BSI = new BlockSemaInfo(); 2868 2869 // Add BSI to CurBlock. 2870 BSI->PrevBlockInfo = CurBlock; 2871 CurBlock = BSI; 2872 2873 BSI->ReturnType = 0; 2874 BSI->TheScope = BlockScope; 2875 2876 // Analyze arguments to block. 2877 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function && 2878 "Not a function declarator!"); 2879 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun; 2880 2881 BSI->hasPrototype = FTI.hasPrototype; 2882 BSI->isVariadic = true; 2883 2884 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes 2885 // no arguments, not a function that takes a single void argument. 2886 if (FTI.hasPrototype && 2887 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 2888 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() && 2889 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) { 2890 // empty arg list, don't push any params. 2891 BSI->isVariadic = false; 2892 } else if (FTI.hasPrototype) { 2893 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) 2894 BSI->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param); 2895 BSI->isVariadic = FTI.isVariadic; 2896 } 2897} 2898 2899/// ActOnBlockError - If there is an error parsing a block, this callback 2900/// is invoked to pop the information about the block from the action impl. 2901void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 2902 // Ensure that CurBlock is deleted. 2903 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock); 2904 2905 // Pop off CurBlock, handle nested blocks. 2906 CurBlock = CurBlock->PrevBlockInfo; 2907 2908 // FIXME: Delete the ParmVarDecl objects as well??? 2909 2910} 2911 2912/// ActOnBlockStmtExpr - This is called when the body of a block statement 2913/// literal was successfully completed. ^(int x){...} 2914Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body, 2915 Scope *CurScope) { 2916 // Ensure that CurBlock is deleted. 2917 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock); 2918 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body)); 2919 2920 // Pop off CurBlock, handle nested blocks. 2921 CurBlock = CurBlock->PrevBlockInfo; 2922 2923 QualType RetTy = Context.VoidTy; 2924 if (BSI->ReturnType) 2925 RetTy = QualType(BSI->ReturnType, 0); 2926 2927 llvm::SmallVector<QualType, 8> ArgTypes; 2928 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i) 2929 ArgTypes.push_back(BSI->Params[i]->getType()); 2930 2931 QualType BlockTy; 2932 if (!BSI->hasPrototype) 2933 BlockTy = Context.getFunctionTypeNoProto(RetTy); 2934 else 2935 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(), 2936 BSI->isVariadic); 2937 2938 BlockTy = Context.getBlockPointerType(BlockTy); 2939 return new BlockExpr(CaretLoc, BlockTy, &BSI->Params[0], BSI->Params.size(), 2940 Body.take()); 2941} 2942 2943/// ExprsMatchFnType - return true if the Exprs in array Args have 2944/// QualTypes that match the QualTypes of the arguments of the FnType. 2945/// The number of arguments has already been validated to match the number of 2946/// arguments in FnType. 2947static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType, 2948 ASTContext &Context) { 2949 unsigned NumParams = FnType->getNumArgs(); 2950 for (unsigned i = 0; i != NumParams; ++i) { 2951 QualType ExprTy = Context.getCanonicalType(Args[i]->getType()); 2952 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i)); 2953 2954 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType()) 2955 return false; 2956 } 2957 return true; 2958} 2959 2960Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs, 2961 SourceLocation *CommaLocs, 2962 SourceLocation BuiltinLoc, 2963 SourceLocation RParenLoc) { 2964 // __builtin_overload requires at least 2 arguments 2965 if (NumArgs < 2) 2966 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args, 2967 SourceRange(BuiltinLoc, RParenLoc)); 2968 2969 // The first argument is required to be a constant expression. It tells us 2970 // the number of arguments to pass to each of the functions to be overloaded. 2971 Expr **Args = reinterpret_cast<Expr**>(args); 2972 Expr *NParamsExpr = Args[0]; 2973 llvm::APSInt constEval(32); 2974 SourceLocation ExpLoc; 2975 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc)) 2976 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant, 2977 NParamsExpr->getSourceRange()); 2978 2979 // Verify that the number of parameters is > 0 2980 unsigned NumParams = constEval.getZExtValue(); 2981 if (NumParams == 0) 2982 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant, 2983 NParamsExpr->getSourceRange()); 2984 // Verify that we have at least 1 + NumParams arguments to the builtin. 2985 if ((NumParams + 1) > NumArgs) 2986 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args, 2987 SourceRange(BuiltinLoc, RParenLoc)); 2988 2989 // Figure out the return type, by matching the args to one of the functions 2990 // listed after the parameters. 2991 OverloadExpr *OE = 0; 2992 for (unsigned i = NumParams + 1; i < NumArgs; ++i) { 2993 // UsualUnaryConversions will convert the function DeclRefExpr into a 2994 // pointer to function. 2995 Expr *Fn = UsualUnaryConversions(Args[i]); 2996 const FunctionTypeProto *FnType = 0; 2997 if (const PointerType *PT = Fn->getType()->getAsPointerType()) 2998 FnType = PT->getPointeeType()->getAsFunctionTypeProto(); 2999 3000 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no 3001 // parameters, and the number of parameters must match the value passed to 3002 // the builtin. 3003 if (!FnType || (FnType->getNumArgs() != NumParams)) 3004 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype, 3005 Fn->getSourceRange()); 3006 3007 // Scan the parameter list for the FunctionType, checking the QualType of 3008 // each parameter against the QualTypes of the arguments to the builtin. 3009 // If they match, return a new OverloadExpr. 3010 if (ExprsMatchFnType(Args+1, FnType, Context)) { 3011 if (OE) 3012 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match, 3013 OE->getFn()->getSourceRange()); 3014 // Remember our match, and continue processing the remaining arguments 3015 // to catch any errors. 3016 OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(), 3017 BuiltinLoc, RParenLoc); 3018 } 3019 } 3020 // Return the newly created OverloadExpr node, if we succeded in matching 3021 // exactly one of the candidate functions. 3022 if (OE) 3023 return OE; 3024 3025 // If we didn't find a matching function Expr in the __builtin_overload list 3026 // the return an error. 3027 std::string typeNames; 3028 for (unsigned i = 0; i != NumParams; ++i) { 3029 if (i != 0) typeNames += ", "; 3030 typeNames += Args[i+1]->getType().getAsString(); 3031 } 3032 3033 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames, 3034 SourceRange(BuiltinLoc, RParenLoc)); 3035} 3036 3037Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 3038 ExprTy *expr, TypeTy *type, 3039 SourceLocation RPLoc) { 3040 Expr *E = static_cast<Expr*>(expr); 3041 QualType T = QualType::getFromOpaquePtr(type); 3042 3043 InitBuiltinVaListType(); 3044 3045 // Get the va_list type 3046 QualType VaListType = Context.getBuiltinVaListType(); 3047 // Deal with implicit array decay; for example, on x86-64, 3048 // va_list is an array, but it's supposed to decay to 3049 // a pointer for va_arg. 3050 if (VaListType->isArrayType()) 3051 VaListType = Context.getArrayDecayedType(VaListType); 3052 // Make sure the input expression also decays appropriately. 3053 UsualUnaryConversions(E); 3054 3055 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible) 3056 return Diag(E->getLocStart(), 3057 diag::err_first_argument_to_va_arg_not_of_type_va_list, 3058 E->getType().getAsString(), 3059 E->getSourceRange()); 3060 3061 // FIXME: Warn if a non-POD type is passed in. 3062 3063 return new VAArgExpr(BuiltinLoc, E, T, RPLoc); 3064} 3065 3066bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 3067 SourceLocation Loc, 3068 QualType DstType, QualType SrcType, 3069 Expr *SrcExpr, const char *Flavor) { 3070 // Decode the result (notice that AST's are still created for extensions). 3071 bool isInvalid = false; 3072 unsigned DiagKind; 3073 switch (ConvTy) { 3074 default: assert(0 && "Unknown conversion type"); 3075 case Compatible: return false; 3076 case PointerToInt: 3077 DiagKind = diag::ext_typecheck_convert_pointer_int; 3078 break; 3079 case IntToPointer: 3080 DiagKind = diag::ext_typecheck_convert_int_pointer; 3081 break; 3082 case IncompatiblePointer: 3083 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 3084 break; 3085 case FunctionVoidPointer: 3086 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 3087 break; 3088 case CompatiblePointerDiscardsQualifiers: 3089 // If the qualifiers lost were because we were applying the 3090 // (deprecated) C++ conversion from a string literal to a char* 3091 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 3092 // Ideally, this check would be performed in 3093 // CheckPointerTypesForAssignment. However, that would require a 3094 // bit of refactoring (so that the second argument is an 3095 // expression, rather than a type), which should be done as part 3096 // of a larger effort to fix CheckPointerTypesForAssignment for 3097 // C++ semantics. 3098 if (getLangOptions().CPlusPlus && 3099 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 3100 return false; 3101 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 3102 break; 3103 case IntToBlockPointer: 3104 DiagKind = diag::err_int_to_block_pointer; 3105 break; 3106 case IncompatibleBlockPointer: 3107 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer; 3108 break; 3109 case BlockVoidPointer: 3110 DiagKind = diag::ext_typecheck_convert_pointer_void_block; 3111 break; 3112 case Incompatible: 3113 DiagKind = diag::err_typecheck_convert_incompatible; 3114 isInvalid = true; 3115 break; 3116 } 3117 3118 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor, 3119 SrcExpr->getSourceRange()); 3120 return isInvalid; 3121} 3122