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