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