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