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