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