SemaExpr.cpp revision f18d4c8326553440fb01bfeb368b2bc60996cfc2
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->isStr("super")) { 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) 698 << (isSizeof ? "sizeof" : "__alignof") << ExprRange; 699 else if (exprType->isIncompleteType()) 700 return Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type : 701 diag::err_alignof_incomplete_type) 702 << exprType.getAsString() << ExprRange; 703 704 return false; 705} 706 707/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and 708/// the same for @c alignof and @c __alignof 709/// Note that the ArgRange is invalid if isType is false. 710Action::ExprResult 711Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType, 712 void *TyOrEx, const SourceRange &ArgRange) { 713 // If error parsing type, ignore. 714 if (TyOrEx == 0) return true; 715 716 QualType ArgTy; 717 SourceRange Range; 718 if (isType) { 719 ArgTy = QualType::getFromOpaquePtr(TyOrEx); 720 Range = ArgRange; 721 } else { 722 // Get the end location. 723 Expr *ArgEx = (Expr *)TyOrEx; 724 Range = ArgEx->getSourceRange(); 725 ArgTy = ArgEx->getType(); 726 } 727 728 // Verify that the operand is valid. 729 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof)) 730 return true; 731 732 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 733 return new SizeOfAlignOfExpr(isSizeof, isType, TyOrEx, Context.getSizeType(), 734 OpLoc, Range.getEnd()); 735} 736 737QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) { 738 DefaultFunctionArrayConversion(V); 739 740 // These operators return the element type of a complex type. 741 if (const ComplexType *CT = V->getType()->getAsComplexType()) 742 return CT->getElementType(); 743 744 // Otherwise they pass through real integer and floating point types here. 745 if (V->getType()->isArithmeticType()) 746 return V->getType(); 747 748 // Reject anything else. 749 Diag(Loc, diag::err_realimag_invalid_type) << V->getType().getAsString(); 750 return QualType(); 751} 752 753 754 755Action::ExprResult Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 756 tok::TokenKind Kind, 757 ExprTy *Input) { 758 Expr *Arg = (Expr *)Input; 759 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 767 if (getLangOptions().CPlusPlus && 768 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) { 769 // Which overloaded operator? 770 OverloadedOperatorKind OverOp = 771 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus; 772 773 // C++ [over.inc]p1: 774 // 775 // [...] If the function is a member function with one 776 // parameter (which shall be of type int) or a non-member 777 // function with two parameters (the second of which shall be 778 // of type int), it defines the postfix increment operator ++ 779 // for objects of that type. When the postfix increment is 780 // called as a result of using the ++ operator, the int 781 // argument will have value zero. 782 Expr *Args[2] = { 783 Arg, 784 new IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0, 785 /*isSigned=*/true), 786 Context.IntTy, SourceLocation()) 787 }; 788 789 // Build the candidate set for overloading 790 OverloadCandidateSet CandidateSet; 791 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet); 792 793 // Perform overload resolution. 794 OverloadCandidateSet::iterator Best; 795 switch (BestViableFunction(CandidateSet, Best)) { 796 case OR_Success: { 797 // We found a built-in operator or an overloaded operator. 798 FunctionDecl *FnDecl = Best->Function; 799 800 if (FnDecl) { 801 // We matched an overloaded operator. Build a call to that 802 // operator. 803 804 // Convert the arguments. 805 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 806 if (PerformObjectArgumentInitialization(Arg, Method)) 807 return true; 808 } else { 809 // Convert the arguments. 810 if (PerformCopyInitialization(Arg, 811 FnDecl->getParamDecl(0)->getType(), 812 "passing")) 813 return true; 814 } 815 816 // Determine the result type 817 QualType ResultTy 818 = FnDecl->getType()->getAsFunctionType()->getResultType(); 819 ResultTy = ResultTy.getNonReferenceType(); 820 821 // Build the actual expression node. 822 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(), 823 SourceLocation()); 824 UsualUnaryConversions(FnExpr); 825 826 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, OpLoc); 827 } else { 828 // We matched a built-in operator. Convert the arguments, then 829 // break out so that we will build the appropriate built-in 830 // operator node. 831 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0], 832 "passing")) 833 return true; 834 835 break; 836 } 837 } 838 839 case OR_No_Viable_Function: 840 // No viable function; fall through to handling this as a 841 // built-in operator, which will produce an error message for us. 842 break; 843 844 case OR_Ambiguous: 845 Diag(OpLoc, diag::err_ovl_ambiguous_oper) 846 << UnaryOperator::getOpcodeStr(Opc) 847 << Arg->getSourceRange(); 848 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 849 return true; 850 } 851 852 // Either we found no viable overloaded operator or we matched a 853 // built-in operator. In either case, fall through to trying to 854 // build a built-in operation. 855 } 856 857 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc); 858 if (result.isNull()) 859 return true; 860 return new UnaryOperator(Arg, Opc, result, OpLoc); 861} 862 863Action::ExprResult Sema:: 864ActOnArraySubscriptExpr(Scope *S, ExprTy *Base, SourceLocation LLoc, 865 ExprTy *Idx, SourceLocation RLoc) { 866 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx); 867 868 if (getLangOptions().CPlusPlus && 869 LHSExp->getType()->isRecordType() || 870 LHSExp->getType()->isEnumeralType() || 871 RHSExp->getType()->isRecordType() || 872 RHSExp->getType()->isRecordType()) { 873 // Add the appropriate overloaded operators (C++ [over.match.oper]) 874 // to the candidate set. 875 OverloadCandidateSet CandidateSet; 876 Expr *Args[2] = { LHSExp, RHSExp }; 877 AddOperatorCandidates(OO_Subscript, S, Args, 2, CandidateSet); 878 879 // Perform overload resolution. 880 OverloadCandidateSet::iterator Best; 881 switch (BestViableFunction(CandidateSet, Best)) { 882 case OR_Success: { 883 // We found a built-in operator or an overloaded operator. 884 FunctionDecl *FnDecl = Best->Function; 885 886 if (FnDecl) { 887 // We matched an overloaded operator. Build a call to that 888 // operator. 889 890 // Convert the arguments. 891 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 892 if (PerformObjectArgumentInitialization(LHSExp, Method) || 893 PerformCopyInitialization(RHSExp, 894 FnDecl->getParamDecl(0)->getType(), 895 "passing")) 896 return true; 897 } else { 898 // Convert the arguments. 899 if (PerformCopyInitialization(LHSExp, 900 FnDecl->getParamDecl(0)->getType(), 901 "passing") || 902 PerformCopyInitialization(RHSExp, 903 FnDecl->getParamDecl(1)->getType(), 904 "passing")) 905 return true; 906 } 907 908 // Determine the result type 909 QualType ResultTy 910 = FnDecl->getType()->getAsFunctionType()->getResultType(); 911 ResultTy = ResultTy.getNonReferenceType(); 912 913 // Build the actual expression node. 914 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(), 915 SourceLocation()); 916 UsualUnaryConversions(FnExpr); 917 918 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, LLoc); 919 } else { 920 // We matched a built-in operator. Convert the arguments, then 921 // break out so that we will build the appropriate built-in 922 // operator node. 923 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0], 924 "passing") || 925 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1], 926 "passing")) 927 return true; 928 929 break; 930 } 931 } 932 933 case OR_No_Viable_Function: 934 // No viable function; fall through to handling this as a 935 // built-in operator, which will produce an error message for us. 936 break; 937 938 case OR_Ambiguous: 939 Diag(LLoc, diag::err_ovl_ambiguous_oper) 940 << "[]" 941 << LHSExp->getSourceRange() << RHSExp->getSourceRange(); 942 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 943 return true; 944 } 945 946 // Either we found no viable overloaded operator or we matched a 947 // built-in operator. In either case, fall through to trying to 948 // build a built-in operation. 949 } 950 951 // Perform default conversions. 952 DefaultFunctionArrayConversion(LHSExp); 953 DefaultFunctionArrayConversion(RHSExp); 954 955 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 956 957 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 958 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 959 // in the subscript position. As a result, we need to derive the array base 960 // and index from the expression types. 961 Expr *BaseExpr, *IndexExpr; 962 QualType ResultType; 963 if (const PointerType *PTy = LHSTy->getAsPointerType()) { 964 BaseExpr = LHSExp; 965 IndexExpr = RHSExp; 966 // FIXME: need to deal with const... 967 ResultType = PTy->getPointeeType(); 968 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) { 969 // Handle the uncommon case of "123[Ptr]". 970 BaseExpr = RHSExp; 971 IndexExpr = LHSExp; 972 // FIXME: need to deal with const... 973 ResultType = PTy->getPointeeType(); 974 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) { 975 BaseExpr = LHSExp; // vectors: V[123] 976 IndexExpr = RHSExp; 977 978 // Component access limited to variables (reject vec4.rg[1]). 979 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) && 980 !isa<ExtVectorElementExpr>(BaseExpr)) 981 return Diag(LLoc, diag::err_ext_vector_component_access) 982 << SourceRange(LLoc, RLoc); 983 // FIXME: need to deal with const... 984 ResultType = VTy->getElementType(); 985 } else { 986 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value) 987 << RHSExp->getSourceRange(); 988 } 989 // C99 6.5.2.1p1 990 if (!IndexExpr->getType()->isIntegerType()) 991 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript) 992 << IndexExpr->getSourceRange(); 993 994 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice, 995 // the following check catches trying to index a pointer to a function (e.g. 996 // void (*)(int)) and pointers to incomplete types. Functions are not 997 // objects in C99. 998 if (!ResultType->isObjectType()) 999 return Diag(BaseExpr->getLocStart(), 1000 diag::err_typecheck_subscript_not_object) 1001 << BaseExpr->getType().getAsString() << BaseExpr->getSourceRange(); 1002 1003 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc); 1004} 1005 1006QualType Sema:: 1007CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc, 1008 IdentifierInfo &CompName, SourceLocation CompLoc) { 1009 const ExtVectorType *vecType = baseType->getAsExtVectorType(); 1010 1011 // This flag determines whether or not the component is to be treated as a 1012 // special name, or a regular GLSL-style component access. 1013 bool SpecialComponent = false; 1014 1015 // The vector accessor can't exceed the number of elements. 1016 const char *compStr = CompName.getName(); 1017 if (strlen(compStr) > vecType->getNumElements()) { 1018 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length) 1019 << baseType.getAsString() << SourceRange(CompLoc); 1020 return QualType(); 1021 } 1022 1023 // Check that we've found one of the special components, or that the component 1024 // names must come from the same set. 1025 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") || 1026 !strcmp(compStr, "e") || !strcmp(compStr, "o")) { 1027 SpecialComponent = true; 1028 } else if (vecType->getPointAccessorIdx(*compStr) != -1) { 1029 do 1030 compStr++; 1031 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1); 1032 } else if (vecType->getColorAccessorIdx(*compStr) != -1) { 1033 do 1034 compStr++; 1035 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1); 1036 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) { 1037 do 1038 compStr++; 1039 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1); 1040 } 1041 1042 if (!SpecialComponent && *compStr) { 1043 // We didn't get to the end of the string. This means the component names 1044 // didn't come from the same set *or* we encountered an illegal name. 1045 Diag(OpLoc, diag::err_ext_vector_component_name_illegal) 1046 << std::string(compStr,compStr+1) << SourceRange(CompLoc); 1047 return QualType(); 1048 } 1049 // Each component accessor can't exceed the vector type. 1050 compStr = CompName.getName(); 1051 while (*compStr) { 1052 if (vecType->isAccessorWithinNumElements(*compStr)) 1053 compStr++; 1054 else 1055 break; 1056 } 1057 if (!SpecialComponent && *compStr) { 1058 // We didn't get to the end of the string. This means a component accessor 1059 // exceeds the number of elements in the vector. 1060 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length) 1061 << baseType.getAsString() << SourceRange(CompLoc); 1062 return QualType(); 1063 } 1064 1065 // If we have a special component name, verify that the current vector length 1066 // is an even number, since all special component names return exactly half 1067 // the elements. 1068 if (SpecialComponent && (vecType->getNumElements() & 1U)) { 1069 Diag(OpLoc, diag::err_ext_vector_component_requires_even) 1070 << baseType.getAsString() << SourceRange(CompLoc); 1071 return QualType(); 1072 } 1073 1074 // The component accessor looks fine - now we need to compute the actual type. 1075 // The vector type is implied by the component accessor. For example, 1076 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc. 1077 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2. 1078 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2 1079 : CompName.getLength(); 1080 if (CompSize == 1) 1081 return vecType->getElementType(); 1082 1083 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize); 1084 // Now look up the TypeDefDecl from the vector type. Without this, 1085 // diagostics look bad. We want extended vector types to appear built-in. 1086 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) { 1087 if (ExtVectorDecls[i]->getUnderlyingType() == VT) 1088 return Context.getTypedefType(ExtVectorDecls[i]); 1089 } 1090 return VT; // should never get here (a typedef type should always be found). 1091} 1092 1093Action::ExprResult Sema:: 1094ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc, 1095 tok::TokenKind OpKind, SourceLocation MemberLoc, 1096 IdentifierInfo &Member) { 1097 Expr *BaseExpr = static_cast<Expr *>(Base); 1098 assert(BaseExpr && "no record expression"); 1099 1100 // Perform default conversions. 1101 DefaultFunctionArrayConversion(BaseExpr); 1102 1103 QualType BaseType = BaseExpr->getType(); 1104 assert(!BaseType.isNull() && "no type for member expression"); 1105 1106 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr 1107 // must have pointer type, and the accessed type is the pointee. 1108 if (OpKind == tok::arrow) { 1109 if (const PointerType *PT = BaseType->getAsPointerType()) 1110 BaseType = PT->getPointeeType(); 1111 else if (getLangOptions().CPlusPlus && BaseType->isRecordType()) 1112 return BuildOverloadedArrowExpr(BaseExpr, OpLoc, MemberLoc, Member); 1113 else 1114 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow) 1115 << BaseType.getAsString() << BaseExpr->getSourceRange(); 1116 } 1117 1118 // Handle field access to simple records. This also handles access to fields 1119 // of the ObjC 'id' struct. 1120 if (const RecordType *RTy = BaseType->getAsRecordType()) { 1121 RecordDecl *RDecl = RTy->getDecl(); 1122 if (RTy->isIncompleteType()) 1123 return Diag(OpLoc, diag::err_typecheck_incomplete_tag) 1124 << RDecl->getName() << BaseExpr->getSourceRange(); 1125 // The record definition is complete, now make sure the member is valid. 1126 FieldDecl *MemberDecl = RDecl->getMember(&Member); 1127 if (!MemberDecl) 1128 return Diag(MemberLoc, diag::err_typecheck_no_member) 1129 << &Member << BaseExpr->getSourceRange(); 1130 1131 // Figure out the type of the member; see C99 6.5.2.3p3 1132 // FIXME: Handle address space modifiers 1133 QualType MemberType = MemberDecl->getType(); 1134 unsigned combinedQualifiers = 1135 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers(); 1136 if (CXXFieldDecl *CXXMember = dyn_cast<CXXFieldDecl>(MemberDecl)) { 1137 if (CXXMember->isMutable()) 1138 combinedQualifiers &= ~QualType::Const; 1139 } 1140 MemberType = MemberType.getQualifiedType(combinedQualifiers); 1141 1142 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl, 1143 MemberLoc, MemberType); 1144 } 1145 1146 // Handle access to Objective-C instance variables, such as "Obj->ivar" and 1147 // (*Obj).ivar. 1148 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) { 1149 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) 1150 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr, 1151 OpKind == tok::arrow); 1152 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar) 1153 << IFTy->getDecl()->getName() << &Member 1154 << BaseExpr->getSourceRange(); 1155 } 1156 1157 // Handle Objective-C property access, which is "Obj.property" where Obj is a 1158 // pointer to a (potentially qualified) interface type. 1159 const PointerType *PTy; 1160 const ObjCInterfaceType *IFTy; 1161 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) && 1162 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) { 1163 ObjCInterfaceDecl *IFace = IFTy->getDecl(); 1164 1165 // Search for a declared property first. 1166 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) 1167 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr); 1168 1169 // Check protocols on qualified interfaces. 1170 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(), 1171 E = IFTy->qual_end(); I != E; ++I) 1172 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) 1173 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr); 1174 1175 // If that failed, look for an "implicit" property by seeing if the nullary 1176 // selector is implemented. 1177 1178 // FIXME: The logic for looking up nullary and unary selectors should be 1179 // shared with the code in ActOnInstanceMessage. 1180 1181 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member); 1182 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel); 1183 1184 // If this reference is in an @implementation, check for 'private' methods. 1185 if (!Getter) 1186 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) 1187 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) 1188 if (ObjCImplementationDecl *ImpDecl = 1189 ObjCImplementations[ClassDecl->getIdentifier()]) 1190 Getter = ImpDecl->getInstanceMethod(Sel); 1191 1192 // Look through local category implementations associated with the class. 1193 if (!Getter) { 1194 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) { 1195 if (ObjCCategoryImpls[i]->getClassInterface() == IFace) 1196 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel); 1197 } 1198 } 1199 if (Getter) { 1200 // If we found a getter then this may be a valid dot-reference, we 1201 // will look for the matching setter, if it is needed. But we don't 1202 // know this yet. 1203 return new ObjCKVCRefExpr(Getter, Getter->getResultType(), 1204 MemberLoc, BaseExpr); 1205 } 1206 } 1207 // Handle properties on qualified "id" protocols. 1208 const ObjCQualifiedIdType *QIdTy; 1209 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) { 1210 // Check protocols on qualified interfaces. 1211 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(), 1212 E = QIdTy->qual_end(); I != E; ++I) 1213 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) 1214 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr); 1215 } 1216 // Handle 'field access' to vectors, such as 'V.xx'. 1217 if (BaseType->isExtVectorType() && OpKind == tok::period) { 1218 // Component access limited to variables (reject vec4.rg.g). 1219 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) && 1220 !isa<ExtVectorElementExpr>(BaseExpr)) 1221 return Diag(MemberLoc, diag::err_ext_vector_component_access) 1222 << BaseExpr->getSourceRange(); 1223 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc); 1224 if (ret.isNull()) 1225 return true; 1226 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc); 1227 } 1228 1229 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union) 1230 << BaseType.getAsString() << BaseExpr->getSourceRange(); 1231} 1232 1233/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 1234/// This provides the location of the left/right parens and a list of comma 1235/// locations. 1236Action::ExprResult Sema:: 1237ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc, 1238 ExprTy **args, unsigned NumArgs, 1239 SourceLocation *CommaLocs, SourceLocation RParenLoc) { 1240 Expr *Fn = static_cast<Expr *>(fn); 1241 Expr **Args = reinterpret_cast<Expr**>(args); 1242 assert(Fn && "no function call expression"); 1243 FunctionDecl *FDecl = NULL; 1244 OverloadedFunctionDecl *Ovl = NULL; 1245 1246 // If we're directly calling a function or a set of overloaded 1247 // functions, get the appropriate declaration. 1248 { 1249 DeclRefExpr *DRExpr = NULL; 1250 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn)) 1251 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()); 1252 else 1253 DRExpr = dyn_cast<DeclRefExpr>(Fn); 1254 1255 if (DRExpr) { 1256 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()); 1257 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl()); 1258 } 1259 } 1260 1261 // If we have a set of overloaded functions, perform overload 1262 // resolution to pick the function. 1263 if (Ovl) { 1264 OverloadCandidateSet CandidateSet; 1265 AddOverloadCandidates(Ovl, Args, NumArgs, CandidateSet); 1266 OverloadCandidateSet::iterator Best; 1267 switch (BestViableFunction(CandidateSet, Best)) { 1268 case OR_Success: 1269 { 1270 // Success! Let the remainder of this function build a call to 1271 // the function selected by overload resolution. 1272 FDecl = Best->Function; 1273 Expr *NewFn = new DeclRefExpr(FDecl, FDecl->getType(), 1274 Fn->getSourceRange().getBegin()); 1275 delete Fn; 1276 Fn = NewFn; 1277 } 1278 break; 1279 1280 case OR_No_Viable_Function: 1281 Diag(Fn->getSourceRange().getBegin(), 1282 diag::err_ovl_no_viable_function_in_call) 1283 << Ovl->getName() << (unsigned)CandidateSet.size() 1284 << Fn->getSourceRange(); 1285 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 1286 return true; 1287 1288 case OR_Ambiguous: 1289 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call) 1290 << Ovl->getName() << Fn->getSourceRange(); 1291 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 1292 return true; 1293 } 1294 } 1295 1296 if (getLangOptions().CPlusPlus && Fn->getType()->isRecordType()) 1297 return BuildCallToObjectOfClassType(Fn, LParenLoc, Args, NumArgs, 1298 CommaLocs, RParenLoc); 1299 1300 // Promote the function operand. 1301 UsualUnaryConversions(Fn); 1302 1303 // Make the call expr early, before semantic checks. This guarantees cleanup 1304 // of arguments and function on error. 1305 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs, 1306 Context.BoolTy, RParenLoc)); 1307 const FunctionType *FuncT; 1308 if (!Fn->getType()->isBlockPointerType()) { 1309 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 1310 // have type pointer to function". 1311 const PointerType *PT = Fn->getType()->getAsPointerType(); 1312 if (PT == 0) 1313 return Diag(LParenLoc, diag::err_typecheck_call_not_function) 1314 << Fn->getType().getAsString() << Fn->getSourceRange(); 1315 FuncT = PT->getPointeeType()->getAsFunctionType(); 1316 } else { // This is a block call. 1317 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()-> 1318 getAsFunctionType(); 1319 } 1320 if (FuncT == 0) 1321 return Diag(LParenLoc, diag::err_typecheck_call_not_function) 1322 << Fn->getType().getAsString() << Fn->getSourceRange(); 1323 1324 // We know the result type of the call, set it. 1325 TheCall->setType(FuncT->getResultType().getNonReferenceType()); 1326 1327 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) { 1328 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 1329 // assignment, to the types of the corresponding parameter, ... 1330 unsigned NumArgsInProto = Proto->getNumArgs(); 1331 unsigned NumArgsToCheck = NumArgs; 1332 1333 // If too few arguments are available (and we don't have default 1334 // arguments for the remaining parameters), don't make the call. 1335 if (NumArgs < NumArgsInProto) { 1336 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments()) 1337 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args) 1338 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange(); 1339 // Use default arguments for missing arguments 1340 NumArgsToCheck = NumArgsInProto; 1341 TheCall->setNumArgs(NumArgsInProto); 1342 } 1343 1344 // If too many are passed and not variadic, error on the extras and drop 1345 // them. 1346 if (NumArgs > NumArgsInProto) { 1347 if (!Proto->isVariadic()) { 1348 Diag(Args[NumArgsInProto]->getLocStart(), 1349 diag::err_typecheck_call_too_many_args) 1350 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange() 1351 << SourceRange(Args[NumArgsInProto]->getLocStart(), 1352 Args[NumArgs-1]->getLocEnd()); 1353 // This deletes the extra arguments. 1354 TheCall->setNumArgs(NumArgsInProto); 1355 } 1356 NumArgsToCheck = NumArgsInProto; 1357 } 1358 1359 // Continue to check argument types (even if we have too few/many args). 1360 for (unsigned i = 0; i != NumArgsToCheck; i++) { 1361 QualType ProtoArgType = Proto->getArgType(i); 1362 1363 Expr *Arg; 1364 if (i < NumArgs) 1365 Arg = Args[i]; 1366 else 1367 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i)); 1368 QualType ArgType = Arg->getType(); 1369 1370 // Pass the argument. 1371 if (PerformCopyInitialization(Arg, ProtoArgType, "passing")) 1372 return true; 1373 1374 TheCall->setArg(i, Arg); 1375 } 1376 1377 // If this is a variadic call, handle args passed through "...". 1378 if (Proto->isVariadic()) { 1379 // Promote the arguments (C99 6.5.2.2p7). 1380 for (unsigned i = NumArgsInProto; i != NumArgs; i++) { 1381 Expr *Arg = Args[i]; 1382 DefaultArgumentPromotion(Arg); 1383 TheCall->setArg(i, Arg); 1384 } 1385 } 1386 } else { 1387 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!"); 1388 1389 // Promote the arguments (C99 6.5.2.2p6). 1390 for (unsigned i = 0; i != NumArgs; i++) { 1391 Expr *Arg = Args[i]; 1392 DefaultArgumentPromotion(Arg); 1393 TheCall->setArg(i, Arg); 1394 } 1395 } 1396 1397 // Do special checking on direct calls to functions. 1398 if (FDecl) 1399 return CheckFunctionCall(FDecl, TheCall.take()); 1400 1401 return TheCall.take(); 1402} 1403 1404Action::ExprResult Sema:: 1405ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty, 1406 SourceLocation RParenLoc, ExprTy *InitExpr) { 1407 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type"); 1408 QualType literalType = QualType::getFromOpaquePtr(Ty); 1409 // FIXME: put back this assert when initializers are worked out. 1410 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 1411 Expr *literalExpr = static_cast<Expr*>(InitExpr); 1412 1413 if (literalType->isArrayType()) { 1414 if (literalType->isVariableArrayType()) 1415 return Diag(LParenLoc, diag::err_variable_object_no_init) 1416 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()); 1417 } else if (literalType->isIncompleteType()) { 1418 return Diag(LParenLoc, diag::err_typecheck_decl_incomplete_type) 1419 << literalType.getAsString() 1420 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()); 1421 } 1422 1423 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc, 1424 "temporary")) 1425 return true; 1426 1427 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl(); 1428 if (isFileScope) { // 6.5.2.5p3 1429 if (CheckForConstantInitializer(literalExpr, literalType)) 1430 return true; 1431 } 1432 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, 1433 isFileScope); 1434} 1435 1436Action::ExprResult Sema:: 1437ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit, 1438 InitListDesignations &Designators, 1439 SourceLocation RBraceLoc) { 1440 Expr **InitList = reinterpret_cast<Expr**>(initlist); 1441 1442 // Semantic analysis for initializers is done by ActOnDeclarator() and 1443 // CheckInitializer() - it requires knowledge of the object being intialized. 1444 1445 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc, 1446 Designators.hasAnyDesignators()); 1447 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 1448 return E; 1449} 1450 1451/// CheckCastTypes - Check type constraints for casting between types. 1452bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) { 1453 UsualUnaryConversions(castExpr); 1454 1455 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression 1456 // type needs to be scalar. 1457 if (castType->isVoidType()) { 1458 // Cast to void allows any expr type. 1459 } else if (!castType->isScalarType() && !castType->isVectorType()) { 1460 // GCC struct/union extension: allow cast to self. 1461 if (Context.getCanonicalType(castType) != 1462 Context.getCanonicalType(castExpr->getType()) || 1463 (!castType->isStructureType() && !castType->isUnionType())) { 1464 // Reject any other conversions to non-scalar types. 1465 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar) 1466 << castType.getAsString() << castExpr->getSourceRange(); 1467 } 1468 1469 // accept this, but emit an ext-warn. 1470 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar) 1471 << castType.getAsString() << castExpr->getSourceRange(); 1472 } else if (!castExpr->getType()->isScalarType() && 1473 !castExpr->getType()->isVectorType()) { 1474 return Diag(castExpr->getLocStart(), 1475 diag::err_typecheck_expect_scalar_operand) 1476 << castExpr->getType().getAsString() << castExpr->getSourceRange(); 1477 } else if (castExpr->getType()->isVectorType()) { 1478 if (CheckVectorCast(TyR, castExpr->getType(), castType)) 1479 return true; 1480 } else if (castType->isVectorType()) { 1481 if (CheckVectorCast(TyR, castType, castExpr->getType())) 1482 return true; 1483 } 1484 return false; 1485} 1486 1487bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) { 1488 assert(VectorTy->isVectorType() && "Not a vector type!"); 1489 1490 if (Ty->isVectorType() || Ty->isIntegerType()) { 1491 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty)) 1492 return Diag(R.getBegin(), 1493 Ty->isVectorType() ? 1494 diag::err_invalid_conversion_between_vectors : 1495 diag::err_invalid_conversion_between_vector_and_integer) 1496 << VectorTy.getAsString() << Ty.getAsString() << R; 1497 } else 1498 return Diag(R.getBegin(), 1499 diag::err_invalid_conversion_between_vector_and_scalar) 1500 << VectorTy.getAsString() << Ty.getAsString() << R; 1501 1502 return false; 1503} 1504 1505Action::ExprResult Sema:: 1506ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty, 1507 SourceLocation RParenLoc, ExprTy *Op) { 1508 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr"); 1509 1510 Expr *castExpr = static_cast<Expr*>(Op); 1511 QualType castType = QualType::getFromOpaquePtr(Ty); 1512 1513 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr)) 1514 return true; 1515 return new CStyleCastExpr(castType, castExpr, castType, LParenLoc, RParenLoc); 1516} 1517 1518/// Note that lex is not null here, even if this is the gnu "x ?: y" extension. 1519/// In that case, lex = cond. 1520inline QualType Sema::CheckConditionalOperands( // C99 6.5.15 1521 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) { 1522 UsualUnaryConversions(cond); 1523 UsualUnaryConversions(lex); 1524 UsualUnaryConversions(rex); 1525 QualType condT = cond->getType(); 1526 QualType lexT = lex->getType(); 1527 QualType rexT = rex->getType(); 1528 1529 // first, check the condition. 1530 if (!condT->isScalarType()) { // C99 6.5.15p2 1531 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) 1532 << condT.getAsString(); 1533 return QualType(); 1534 } 1535 1536 // Now check the two expressions. 1537 1538 // If both operands have arithmetic type, do the usual arithmetic conversions 1539 // to find a common type: C99 6.5.15p3,5. 1540 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { 1541 UsualArithmeticConversions(lex, rex); 1542 return lex->getType(); 1543 } 1544 1545 // If both operands are the same structure or union type, the result is that 1546 // type. 1547 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3 1548 if (const RecordType *RHSRT = rexT->getAsRecordType()) 1549 if (LHSRT->getDecl() == RHSRT->getDecl()) 1550 // "If both the operands have structure or union type, the result has 1551 // that type." This implies that CV qualifiers are dropped. 1552 return lexT.getUnqualifiedType(); 1553 } 1554 1555 // C99 6.5.15p5: "If both operands have void type, the result has void type." 1556 // The following || allows only one side to be void (a GCC-ism). 1557 if (lexT->isVoidType() || rexT->isVoidType()) { 1558 if (!lexT->isVoidType()) 1559 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void) 1560 << rex->getSourceRange(); 1561 if (!rexT->isVoidType()) 1562 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void) 1563 << lex->getSourceRange(); 1564 ImpCastExprToType(lex, Context.VoidTy); 1565 ImpCastExprToType(rex, Context.VoidTy); 1566 return Context.VoidTy; 1567 } 1568 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 1569 // the type of the other operand." 1570 if ((lexT->isPointerType() || lexT->isBlockPointerType() || 1571 Context.isObjCObjectPointerType(lexT)) && 1572 rex->isNullPointerConstant(Context)) { 1573 ImpCastExprToType(rex, lexT); // promote the null to a pointer. 1574 return lexT; 1575 } 1576 if ((rexT->isPointerType() || rexT->isBlockPointerType() || 1577 Context.isObjCObjectPointerType(rexT)) && 1578 lex->isNullPointerConstant(Context)) { 1579 ImpCastExprToType(lex, rexT); // promote the null to a pointer. 1580 return rexT; 1581 } 1582 // Handle the case where both operands are pointers before we handle null 1583 // pointer constants in case both operands are null pointer constants. 1584 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6 1585 if (const PointerType *RHSPT = rexT->getAsPointerType()) { 1586 // get the "pointed to" types 1587 QualType lhptee = LHSPT->getPointeeType(); 1588 QualType rhptee = RHSPT->getPointeeType(); 1589 1590 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 1591 if (lhptee->isVoidType() && 1592 rhptee->isIncompleteOrObjectType()) { 1593 // Figure out necessary qualifiers (C99 6.5.15p6) 1594 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers()); 1595 QualType destType = Context.getPointerType(destPointee); 1596 ImpCastExprToType(lex, destType); // add qualifiers if necessary 1597 ImpCastExprToType(rex, destType); // promote to void* 1598 return destType; 1599 } 1600 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 1601 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers()); 1602 QualType destType = Context.getPointerType(destPointee); 1603 ImpCastExprToType(lex, destType); // add qualifiers if necessary 1604 ImpCastExprToType(rex, destType); // promote to void* 1605 return destType; 1606 } 1607 1608 QualType compositeType = lexT; 1609 1610 // If either type is an Objective-C object type then check 1611 // compatibility according to Objective-C. 1612 if (Context.isObjCObjectPointerType(lexT) || 1613 Context.isObjCObjectPointerType(rexT)) { 1614 // If both operands are interfaces and either operand can be 1615 // assigned to the other, use that type as the composite 1616 // type. This allows 1617 // xxx ? (A*) a : (B*) b 1618 // where B is a subclass of A. 1619 // 1620 // Additionally, as for assignment, if either type is 'id' 1621 // allow silent coercion. Finally, if the types are 1622 // incompatible then make sure to use 'id' as the composite 1623 // type so the result is acceptable for sending messages to. 1624 1625 // FIXME: This code should not be localized to here. Also this 1626 // should use a compatible check instead of abusing the 1627 // canAssignObjCInterfaces code. 1628 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType(); 1629 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType(); 1630 if (LHSIface && RHSIface && 1631 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) { 1632 compositeType = lexT; 1633 } else if (LHSIface && RHSIface && 1634 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) { 1635 compositeType = rexT; 1636 } else if (Context.isObjCIdType(lhptee) || 1637 Context.isObjCIdType(rhptee)) { 1638 // FIXME: This code looks wrong, because isObjCIdType checks 1639 // the struct but getObjCIdType returns the pointer to 1640 // struct. This is horrible and should be fixed. 1641 compositeType = Context.getObjCIdType(); 1642 } else { 1643 QualType incompatTy = Context.getObjCIdType(); 1644 ImpCastExprToType(lex, incompatTy); 1645 ImpCastExprToType(rex, incompatTy); 1646 return incompatTy; 1647 } 1648 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(), 1649 rhptee.getUnqualifiedType())) { 1650 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers) 1651 << lexT.getAsString() << rexT.getAsString() 1652 << lex->getSourceRange() << rex->getSourceRange(); 1653 // In this situation, we assume void* type. No especially good 1654 // reason, but this is what gcc does, and we do have to pick 1655 // to get a consistent AST. 1656 QualType incompatTy = Context.getPointerType(Context.VoidTy); 1657 ImpCastExprToType(lex, incompatTy); 1658 ImpCastExprToType(rex, incompatTy); 1659 return incompatTy; 1660 } 1661 // The pointer types are compatible. 1662 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to 1663 // differently qualified versions of compatible types, the result type is 1664 // a pointer to an appropriately qualified version of the *composite* 1665 // type. 1666 // FIXME: Need to calculate the composite type. 1667 // FIXME: Need to add qualifiers 1668 ImpCastExprToType(lex, compositeType); 1669 ImpCastExprToType(rex, compositeType); 1670 return compositeType; 1671 } 1672 } 1673 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type 1674 // evaluates to "struct objc_object *" (and is handled above when comparing 1675 // id with statically typed objects). 1676 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) { 1677 // GCC allows qualified id and any Objective-C type to devolve to 1678 // id. Currently localizing to here until clear this should be 1679 // part of ObjCQualifiedIdTypesAreCompatible. 1680 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) || 1681 (lexT->isObjCQualifiedIdType() && 1682 Context.isObjCObjectPointerType(rexT)) || 1683 (rexT->isObjCQualifiedIdType() && 1684 Context.isObjCObjectPointerType(lexT))) { 1685 // FIXME: This is not the correct composite type. This only 1686 // happens to work because id can more or less be used anywhere, 1687 // however this may change the type of method sends. 1688 // FIXME: gcc adds some type-checking of the arguments and emits 1689 // (confusing) incompatible comparison warnings in some 1690 // cases. Investigate. 1691 QualType compositeType = Context.getObjCIdType(); 1692 ImpCastExprToType(lex, compositeType); 1693 ImpCastExprToType(rex, compositeType); 1694 return compositeType; 1695 } 1696 } 1697 1698 // Selection between block pointer types is ok as long as they are the same. 1699 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() && 1700 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT)) 1701 return lexT; 1702 1703 // Otherwise, the operands are not compatible. 1704 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands) 1705 << lexT.getAsString() << rexT.getAsString() 1706 << lex->getSourceRange() << rex->getSourceRange(); 1707 return QualType(); 1708} 1709 1710/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 1711/// in the case of a the GNU conditional expr extension. 1712Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 1713 SourceLocation ColonLoc, 1714 ExprTy *Cond, ExprTy *LHS, 1715 ExprTy *RHS) { 1716 Expr *CondExpr = (Expr *) Cond; 1717 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS; 1718 1719 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 1720 // was the condition. 1721 bool isLHSNull = LHSExpr == 0; 1722 if (isLHSNull) 1723 LHSExpr = CondExpr; 1724 1725 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, 1726 RHSExpr, QuestionLoc); 1727 if (result.isNull()) 1728 return true; 1729 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr, 1730 RHSExpr, result); 1731} 1732 1733 1734// CheckPointerTypesForAssignment - This is a very tricky routine (despite 1735// being closely modeled after the C99 spec:-). The odd characteristic of this 1736// routine is it effectively iqnores the qualifiers on the top level pointee. 1737// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 1738// FIXME: add a couple examples in this comment. 1739Sema::AssignConvertType 1740Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) { 1741 QualType lhptee, rhptee; 1742 1743 // get the "pointed to" type (ignoring qualifiers at the top level) 1744 lhptee = lhsType->getAsPointerType()->getPointeeType(); 1745 rhptee = rhsType->getAsPointerType()->getPointeeType(); 1746 1747 // make sure we operate on the canonical type 1748 lhptee = Context.getCanonicalType(lhptee); 1749 rhptee = Context.getCanonicalType(rhptee); 1750 1751 AssignConvertType ConvTy = Compatible; 1752 1753 // C99 6.5.16.1p1: This following citation is common to constraints 1754 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 1755 // qualifiers of the type *pointed to* by the right; 1756 // FIXME: Handle ASQualType 1757 if (!lhptee.isAtLeastAsQualifiedAs(rhptee)) 1758 ConvTy = CompatiblePointerDiscardsQualifiers; 1759 1760 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 1761 // incomplete type and the other is a pointer to a qualified or unqualified 1762 // version of void... 1763 if (lhptee->isVoidType()) { 1764 if (rhptee->isIncompleteOrObjectType()) 1765 return ConvTy; 1766 1767 // As an extension, we allow cast to/from void* to function pointer. 1768 assert(rhptee->isFunctionType()); 1769 return FunctionVoidPointer; 1770 } 1771 1772 if (rhptee->isVoidType()) { 1773 if (lhptee->isIncompleteOrObjectType()) 1774 return ConvTy; 1775 1776 // As an extension, we allow cast to/from void* to function pointer. 1777 assert(lhptee->isFunctionType()); 1778 return FunctionVoidPointer; 1779 } 1780 1781 // Check for ObjC interfaces 1782 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType(); 1783 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType(); 1784 if (LHSIface && RHSIface && 1785 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) 1786 return ConvTy; 1787 1788 // ID acts sort of like void* for ObjC interfaces 1789 if (LHSIface && Context.isObjCIdType(rhptee)) 1790 return ConvTy; 1791 if (RHSIface && Context.isObjCIdType(lhptee)) 1792 return ConvTy; 1793 1794 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 1795 // unqualified versions of compatible types, ... 1796 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(), 1797 rhptee.getUnqualifiedType())) 1798 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers 1799 return ConvTy; 1800} 1801 1802/// CheckBlockPointerTypesForAssignment - This routine determines whether two 1803/// block pointer types are compatible or whether a block and normal pointer 1804/// are compatible. It is more restrict than comparing two function pointer 1805// types. 1806Sema::AssignConvertType 1807Sema::CheckBlockPointerTypesForAssignment(QualType lhsType, 1808 QualType rhsType) { 1809 QualType lhptee, rhptee; 1810 1811 // get the "pointed to" type (ignoring qualifiers at the top level) 1812 lhptee = lhsType->getAsBlockPointerType()->getPointeeType(); 1813 rhptee = rhsType->getAsBlockPointerType()->getPointeeType(); 1814 1815 // make sure we operate on the canonical type 1816 lhptee = Context.getCanonicalType(lhptee); 1817 rhptee = Context.getCanonicalType(rhptee); 1818 1819 AssignConvertType ConvTy = Compatible; 1820 1821 // For blocks we enforce that qualifiers are identical. 1822 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers()) 1823 ConvTy = CompatiblePointerDiscardsQualifiers; 1824 1825 if (!Context.typesAreBlockCompatible(lhptee, rhptee)) 1826 return IncompatibleBlockPointer; 1827 return ConvTy; 1828} 1829 1830/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 1831/// has code to accommodate several GCC extensions when type checking 1832/// pointers. Here are some objectionable examples that GCC considers warnings: 1833/// 1834/// int a, *pint; 1835/// short *pshort; 1836/// struct foo *pfoo; 1837/// 1838/// pint = pshort; // warning: assignment from incompatible pointer type 1839/// a = pint; // warning: assignment makes integer from pointer without a cast 1840/// pint = a; // warning: assignment makes pointer from integer without a cast 1841/// pint = pfoo; // warning: assignment from incompatible pointer type 1842/// 1843/// As a result, the code for dealing with pointers is more complex than the 1844/// C99 spec dictates. 1845/// 1846Sema::AssignConvertType 1847Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) { 1848 // Get canonical types. We're not formatting these types, just comparing 1849 // them. 1850 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType(); 1851 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType(); 1852 1853 if (lhsType == rhsType) 1854 return Compatible; // Common case: fast path an exact match. 1855 1856 // If the left-hand side is a reference type, then we are in a 1857 // (rare!) case where we've allowed the use of references in C, 1858 // e.g., as a parameter type in a built-in function. In this case, 1859 // just make sure that the type referenced is compatible with the 1860 // right-hand side type. The caller is responsible for adjusting 1861 // lhsType so that the resulting expression does not have reference 1862 // type. 1863 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) { 1864 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) 1865 return Compatible; 1866 return Incompatible; 1867 } 1868 1869 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) { 1870 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false)) 1871 return Compatible; 1872 // Relax integer conversions like we do for pointers below. 1873 if (rhsType->isIntegerType()) 1874 return IntToPointer; 1875 if (lhsType->isIntegerType()) 1876 return PointerToInt; 1877 return IncompatibleObjCQualifiedId; 1878 } 1879 1880 if (lhsType->isVectorType() || rhsType->isVectorType()) { 1881 // For ExtVector, allow vector splats; float -> <n x float> 1882 if (const ExtVectorType *LV = lhsType->getAsExtVectorType()) 1883 if (LV->getElementType() == rhsType) 1884 return Compatible; 1885 1886 // If we are allowing lax vector conversions, and LHS and RHS are both 1887 // vectors, the total size only needs to be the same. This is a bitcast; 1888 // no bits are changed but the result type is different. 1889 if (getLangOptions().LaxVectorConversions && 1890 lhsType->isVectorType() && rhsType->isVectorType()) { 1891 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType)) 1892 return Compatible; 1893 } 1894 return Incompatible; 1895 } 1896 1897 if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) 1898 return Compatible; 1899 1900 if (isa<PointerType>(lhsType)) { 1901 if (rhsType->isIntegerType()) 1902 return IntToPointer; 1903 1904 if (isa<PointerType>(rhsType)) 1905 return CheckPointerTypesForAssignment(lhsType, rhsType); 1906 1907 if (rhsType->getAsBlockPointerType()) { 1908 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType()) 1909 return BlockVoidPointer; 1910 1911 // Treat block pointers as objects. 1912 if (getLangOptions().ObjC1 && 1913 lhsType == Context.getCanonicalType(Context.getObjCIdType())) 1914 return Compatible; 1915 } 1916 return Incompatible; 1917 } 1918 1919 if (isa<BlockPointerType>(lhsType)) { 1920 if (rhsType->isIntegerType()) 1921 return IntToPointer; 1922 1923 // Treat block pointers as objects. 1924 if (getLangOptions().ObjC1 && 1925 rhsType == Context.getCanonicalType(Context.getObjCIdType())) 1926 return Compatible; 1927 1928 if (rhsType->isBlockPointerType()) 1929 return CheckBlockPointerTypesForAssignment(lhsType, rhsType); 1930 1931 if (const PointerType *RHSPT = rhsType->getAsPointerType()) { 1932 if (RHSPT->getPointeeType()->isVoidType()) 1933 return BlockVoidPointer; 1934 } 1935 return Incompatible; 1936 } 1937 1938 if (isa<PointerType>(rhsType)) { 1939 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer. 1940 if (lhsType == Context.BoolTy) 1941 return Compatible; 1942 1943 if (lhsType->isIntegerType()) 1944 return PointerToInt; 1945 1946 if (isa<PointerType>(lhsType)) 1947 return CheckPointerTypesForAssignment(lhsType, rhsType); 1948 1949 if (isa<BlockPointerType>(lhsType) && 1950 rhsType->getAsPointerType()->getPointeeType()->isVoidType()) 1951 return BlockVoidPointer; 1952 return Incompatible; 1953 } 1954 1955 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) { 1956 if (Context.typesAreCompatible(lhsType, rhsType)) 1957 return Compatible; 1958 } 1959 return Incompatible; 1960} 1961 1962Sema::AssignConvertType 1963Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) { 1964 if (getLangOptions().CPlusPlus) { 1965 if (!lhsType->isRecordType()) { 1966 // C++ 5.17p3: If the left operand is not of class type, the 1967 // expression is implicitly converted (C++ 4) to the 1968 // cv-unqualified type of the left operand. 1969 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType())) 1970 return Incompatible; 1971 else 1972 return Compatible; 1973 } 1974 1975 // FIXME: Currently, we fall through and treat C++ classes like C 1976 // structures. 1977 } 1978 1979 // C99 6.5.16.1p1: the left operand is a pointer and the right is 1980 // a null pointer constant. 1981 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() || 1982 lhsType->isBlockPointerType()) 1983 && rExpr->isNullPointerConstant(Context)) { 1984 ImpCastExprToType(rExpr, lhsType); 1985 return Compatible; 1986 } 1987 1988 // We don't allow conversion of non-null-pointer constants to integers. 1989 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType()) 1990 return IntToBlockPointer; 1991 1992 // This check seems unnatural, however it is necessary to ensure the proper 1993 // conversion of functions/arrays. If the conversion were done for all 1994 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary 1995 // expressions that surpress this implicit conversion (&, sizeof). 1996 // 1997 // Suppress this for references: C++ 8.5.3p5. 1998 if (!lhsType->isReferenceType()) 1999 DefaultFunctionArrayConversion(rExpr); 2000 2001 Sema::AssignConvertType result = 2002 CheckAssignmentConstraints(lhsType, rExpr->getType()); 2003 2004 // C99 6.5.16.1p2: The value of the right operand is converted to the 2005 // type of the assignment expression. 2006 // CheckAssignmentConstraints allows the left-hand side to be a reference, 2007 // so that we can use references in built-in functions even in C. 2008 // The getNonReferenceType() call makes sure that the resulting expression 2009 // does not have reference type. 2010 if (rExpr->getType() != lhsType) 2011 ImpCastExprToType(rExpr, lhsType.getNonReferenceType()); 2012 return result; 2013} 2014 2015Sema::AssignConvertType 2016Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) { 2017 return CheckAssignmentConstraints(lhsType, rhsType); 2018} 2019 2020QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) { 2021 Diag(Loc, diag::err_typecheck_invalid_operands) 2022 << lex->getType().getAsString() << rex->getType().getAsString() 2023 << lex->getSourceRange() << rex->getSourceRange(); 2024 return QualType(); 2025} 2026 2027inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, 2028 Expr *&rex) { 2029 // For conversion purposes, we ignore any qualifiers. 2030 // For example, "const float" and "float" are equivalent. 2031 QualType lhsType = 2032 Context.getCanonicalType(lex->getType()).getUnqualifiedType(); 2033 QualType rhsType = 2034 Context.getCanonicalType(rex->getType()).getUnqualifiedType(); 2035 2036 // If the vector types are identical, return. 2037 if (lhsType == rhsType) 2038 return lhsType; 2039 2040 // Handle the case of a vector & extvector type of the same size and element 2041 // type. It would be nice if we only had one vector type someday. 2042 if (getLangOptions().LaxVectorConversions) 2043 if (const VectorType *LV = lhsType->getAsVectorType()) 2044 if (const VectorType *RV = rhsType->getAsVectorType()) 2045 if (LV->getElementType() == RV->getElementType() && 2046 LV->getNumElements() == RV->getNumElements()) 2047 return lhsType->isExtVectorType() ? lhsType : rhsType; 2048 2049 // If the lhs is an extended vector and the rhs is a scalar of the same type 2050 // or a literal, promote the rhs to the vector type. 2051 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) { 2052 QualType eltType = V->getElementType(); 2053 2054 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) || 2055 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) || 2056 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) { 2057 ImpCastExprToType(rex, lhsType); 2058 return lhsType; 2059 } 2060 } 2061 2062 // If the rhs is an extended vector and the lhs is a scalar of the same type, 2063 // promote the lhs to the vector type. 2064 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) { 2065 QualType eltType = V->getElementType(); 2066 2067 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) || 2068 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) || 2069 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) { 2070 ImpCastExprToType(lex, rhsType); 2071 return rhsType; 2072 } 2073 } 2074 2075 // You cannot convert between vector values of different size. 2076 Diag(Loc, diag::err_typecheck_vector_not_convertable) 2077 << lex->getType().getAsString() << rex->getType().getAsString() 2078 << lex->getSourceRange() << rex->getSourceRange(); 2079 return QualType(); 2080} 2081 2082inline QualType Sema::CheckMultiplyDivideOperands( 2083 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) 2084{ 2085 QualType lhsType = lex->getType(), rhsType = rex->getType(); 2086 2087 if (lhsType->isVectorType() || rhsType->isVectorType()) 2088 return CheckVectorOperands(Loc, lex, rex); 2089 2090 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 2091 2092 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 2093 return compType; 2094 return InvalidOperands(Loc, lex, rex); 2095} 2096 2097inline QualType Sema::CheckRemainderOperands( 2098 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) 2099{ 2100 QualType lhsType = lex->getType(), rhsType = rex->getType(); 2101 2102 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 2103 2104 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType()) 2105 return compType; 2106 return InvalidOperands(Loc, lex, rex); 2107} 2108 2109inline QualType Sema::CheckAdditionOperands( // C99 6.5.6 2110 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) 2111{ 2112 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 2113 return CheckVectorOperands(Loc, lex, rex); 2114 2115 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 2116 2117 // handle the common case first (both operands are arithmetic). 2118 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 2119 return compType; 2120 2121 // Put any potential pointer into PExp 2122 Expr* PExp = lex, *IExp = rex; 2123 if (IExp->getType()->isPointerType()) 2124 std::swap(PExp, IExp); 2125 2126 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) { 2127 if (IExp->getType()->isIntegerType()) { 2128 // Check for arithmetic on pointers to incomplete types 2129 if (!PTy->getPointeeType()->isObjectType()) { 2130 if (PTy->getPointeeType()->isVoidType()) { 2131 Diag(Loc, diag::ext_gnu_void_ptr) 2132 << lex->getSourceRange() << rex->getSourceRange(); 2133 } else { 2134 Diag(Loc, diag::err_typecheck_arithmetic_incomplete_type) 2135 << lex->getType().getAsString() << lex->getSourceRange(); 2136 return QualType(); 2137 } 2138 } 2139 return PExp->getType(); 2140 } 2141 } 2142 2143 return InvalidOperands(Loc, lex, rex); 2144} 2145 2146// C99 6.5.6 2147QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex, 2148 SourceLocation Loc, bool isCompAssign) { 2149 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 2150 return CheckVectorOperands(Loc, lex, rex); 2151 2152 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 2153 2154 // Enforce type constraints: C99 6.5.6p3. 2155 2156 // Handle the common case first (both operands are arithmetic). 2157 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 2158 return compType; 2159 2160 // Either ptr - int or ptr - ptr. 2161 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) { 2162 QualType lpointee = LHSPTy->getPointeeType(); 2163 2164 // The LHS must be an object type, not incomplete, function, etc. 2165 if (!lpointee->isObjectType()) { 2166 // Handle the GNU void* extension. 2167 if (lpointee->isVoidType()) { 2168 Diag(Loc, diag::ext_gnu_void_ptr) 2169 << lex->getSourceRange() << rex->getSourceRange(); 2170 } else { 2171 Diag(Loc, diag::err_typecheck_sub_ptr_object) 2172 << lex->getType().getAsString() << lex->getSourceRange(); 2173 return QualType(); 2174 } 2175 } 2176 2177 // The result type of a pointer-int computation is the pointer type. 2178 if (rex->getType()->isIntegerType()) 2179 return lex->getType(); 2180 2181 // Handle pointer-pointer subtractions. 2182 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) { 2183 QualType rpointee = RHSPTy->getPointeeType(); 2184 2185 // RHS must be an object type, unless void (GNU). 2186 if (!rpointee->isObjectType()) { 2187 // Handle the GNU void* extension. 2188 if (rpointee->isVoidType()) { 2189 if (!lpointee->isVoidType()) 2190 Diag(Loc, diag::ext_gnu_void_ptr) 2191 << lex->getSourceRange() << rex->getSourceRange(); 2192 } else { 2193 Diag(Loc, diag::err_typecheck_sub_ptr_object) 2194 << rex->getType().getAsString() << rex->getSourceRange(); 2195 return QualType(); 2196 } 2197 } 2198 2199 // Pointee types must be compatible. 2200 if (!Context.typesAreCompatible( 2201 Context.getCanonicalType(lpointee).getUnqualifiedType(), 2202 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 2203 Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 2204 << lex->getType().getAsString() << rex->getType().getAsString() 2205 << lex->getSourceRange() << rex->getSourceRange(); 2206 return QualType(); 2207 } 2208 2209 return Context.getPointerDiffType(); 2210 } 2211 } 2212 2213 return InvalidOperands(Loc, lex, rex); 2214} 2215 2216// C99 6.5.7 2217QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc, 2218 bool isCompAssign) { 2219 // C99 6.5.7p2: Each of the operands shall have integer type. 2220 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType()) 2221 return InvalidOperands(Loc, lex, rex); 2222 2223 // Shifts don't perform usual arithmetic conversions, they just do integer 2224 // promotions on each operand. C99 6.5.7p3 2225 if (!isCompAssign) 2226 UsualUnaryConversions(lex); 2227 UsualUnaryConversions(rex); 2228 2229 // "The type of the result is that of the promoted left operand." 2230 return lex->getType(); 2231} 2232 2233static bool areComparableObjCInterfaces(QualType LHS, QualType RHS, 2234 ASTContext& Context) { 2235 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType(); 2236 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType(); 2237 // ID acts sort of like void* for ObjC interfaces 2238 if (LHSIface && Context.isObjCIdType(RHS)) 2239 return true; 2240 if (RHSIface && Context.isObjCIdType(LHS)) 2241 return true; 2242 if (!LHSIface || !RHSIface) 2243 return false; 2244 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) || 2245 Context.canAssignObjCInterfaces(RHSIface, LHSIface); 2246} 2247 2248// C99 6.5.8 2249QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc, 2250 bool isRelational) { 2251 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 2252 return CheckVectorCompareOperands(lex, rex, Loc, isRelational); 2253 2254 // C99 6.5.8p3 / C99 6.5.9p4 2255 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 2256 UsualArithmeticConversions(lex, rex); 2257 else { 2258 UsualUnaryConversions(lex); 2259 UsualUnaryConversions(rex); 2260 } 2261 QualType lType = lex->getType(); 2262 QualType rType = rex->getType(); 2263 2264 // For non-floating point types, check for self-comparisons of the form 2265 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 2266 // often indicate logic errors in the program. 2267 if (!lType->isFloatingType()) { 2268 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens())) 2269 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens())) 2270 if (DRL->getDecl() == DRR->getDecl()) 2271 Diag(Loc, diag::warn_selfcomparison); 2272 } 2273 2274 // The result of comparisons is 'bool' in C++, 'int' in C. 2275 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy; 2276 2277 if (isRelational) { 2278 if (lType->isRealType() && rType->isRealType()) 2279 return ResultTy; 2280 } else { 2281 // Check for comparisons of floating point operands using != and ==. 2282 if (lType->isFloatingType()) { 2283 assert (rType->isFloatingType()); 2284 CheckFloatComparison(Loc,lex,rex); 2285 } 2286 2287 if (lType->isArithmeticType() && rType->isArithmeticType()) 2288 return ResultTy; 2289 } 2290 2291 bool LHSIsNull = lex->isNullPointerConstant(Context); 2292 bool RHSIsNull = rex->isNullPointerConstant(Context); 2293 2294 // All of the following pointer related warnings are GCC extensions, except 2295 // when handling null pointer constants. One day, we can consider making them 2296 // errors (when -pedantic-errors is enabled). 2297 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2 2298 QualType LCanPointeeTy = 2299 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType()); 2300 QualType RCanPointeeTy = 2301 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType()); 2302 2303 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2 2304 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() && 2305 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 2306 RCanPointeeTy.getUnqualifiedType()) && 2307 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) { 2308 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers) 2309 << lType.getAsString() << rType.getAsString() 2310 << lex->getSourceRange() << rex->getSourceRange(); 2311 } 2312 ImpCastExprToType(rex, lType); // promote the pointer to pointer 2313 return ResultTy; 2314 } 2315 // Handle block pointer types. 2316 if (lType->isBlockPointerType() && rType->isBlockPointerType()) { 2317 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType(); 2318 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType(); 2319 2320 if (!LHSIsNull && !RHSIsNull && 2321 !Context.typesAreBlockCompatible(lpointee, rpointee)) { 2322 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 2323 << lType.getAsString() << rType.getAsString() 2324 << lex->getSourceRange() << rex->getSourceRange(); 2325 } 2326 ImpCastExprToType(rex, lType); // promote the pointer to pointer 2327 return ResultTy; 2328 } 2329 // Allow block pointers to be compared with null pointer constants. 2330 if ((lType->isBlockPointerType() && rType->isPointerType()) || 2331 (lType->isPointerType() && rType->isBlockPointerType())) { 2332 if (!LHSIsNull && !RHSIsNull) { 2333 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 2334 << lType.getAsString() << rType.getAsString() 2335 << lex->getSourceRange() << rex->getSourceRange(); 2336 } 2337 ImpCastExprToType(rex, lType); // promote the pointer to pointer 2338 return ResultTy; 2339 } 2340 2341 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) { 2342 if (lType->isPointerType() || rType->isPointerType()) { 2343 const PointerType *LPT = lType->getAsPointerType(); 2344 const PointerType *RPT = rType->getAsPointerType(); 2345 bool LPtrToVoid = LPT ? 2346 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false; 2347 bool RPtrToVoid = RPT ? 2348 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false; 2349 2350 if (!LPtrToVoid && !RPtrToVoid && 2351 !Context.typesAreCompatible(lType, rType)) { 2352 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers) 2353 << lType.getAsString() << rType.getAsString() 2354 << lex->getSourceRange() << rex->getSourceRange(); 2355 ImpCastExprToType(rex, lType); 2356 return ResultTy; 2357 } 2358 ImpCastExprToType(rex, lType); 2359 return ResultTy; 2360 } 2361 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) { 2362 ImpCastExprToType(rex, lType); 2363 return ResultTy; 2364 } else { 2365 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) { 2366 Diag(Loc, diag::warn_incompatible_qualified_id_operands) 2367 << lType.getAsString() << rType.getAsString() 2368 << lex->getSourceRange() << rex->getSourceRange(); 2369 ImpCastExprToType(rex, lType); 2370 return ResultTy; 2371 } 2372 } 2373 } 2374 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) && 2375 rType->isIntegerType()) { 2376 if (!RHSIsNull) 2377 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer) 2378 << lType.getAsString() << rType.getAsString() 2379 << lex->getSourceRange() << rex->getSourceRange(); 2380 ImpCastExprToType(rex, lType); // promote the integer to pointer 2381 return ResultTy; 2382 } 2383 if (lType->isIntegerType() && 2384 (rType->isPointerType() || rType->isObjCQualifiedIdType())) { 2385 if (!LHSIsNull) 2386 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer) 2387 << lType.getAsString() << rType.getAsString() 2388 << lex->getSourceRange() << rex->getSourceRange(); 2389 ImpCastExprToType(lex, rType); // promote the integer to pointer 2390 return ResultTy; 2391 } 2392 // Handle block pointers. 2393 if (lType->isBlockPointerType() && rType->isIntegerType()) { 2394 if (!RHSIsNull) 2395 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer) 2396 << lType.getAsString() << rType.getAsString() 2397 << lex->getSourceRange() << rex->getSourceRange(); 2398 ImpCastExprToType(rex, lType); // promote the integer to pointer 2399 return ResultTy; 2400 } 2401 if (lType->isIntegerType() && rType->isBlockPointerType()) { 2402 if (!LHSIsNull) 2403 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer) 2404 << lType.getAsString() << rType.getAsString() 2405 << lex->getSourceRange() << rex->getSourceRange(); 2406 ImpCastExprToType(lex, rType); // promote the integer to pointer 2407 return ResultTy; 2408 } 2409 return InvalidOperands(Loc, lex, rex); 2410} 2411 2412/// CheckVectorCompareOperands - vector comparisons are a clang extension that 2413/// operates on extended vector types. Instead of producing an IntTy result, 2414/// like a scalar comparison, a vector comparison produces a vector of integer 2415/// types. 2416QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex, 2417 SourceLocation Loc, 2418 bool isRelational) { 2419 // Check to make sure we're operating on vectors of the same type and width, 2420 // Allowing one side to be a scalar of element type. 2421 QualType vType = CheckVectorOperands(Loc, lex, rex); 2422 if (vType.isNull()) 2423 return vType; 2424 2425 QualType lType = lex->getType(); 2426 QualType rType = rex->getType(); 2427 2428 // For non-floating point types, check for self-comparisons of the form 2429 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 2430 // often indicate logic errors in the program. 2431 if (!lType->isFloatingType()) { 2432 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens())) 2433 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens())) 2434 if (DRL->getDecl() == DRR->getDecl()) 2435 Diag(Loc, diag::warn_selfcomparison); 2436 } 2437 2438 // Check for comparisons of floating point operands using != and ==. 2439 if (!isRelational && lType->isFloatingType()) { 2440 assert (rType->isFloatingType()); 2441 CheckFloatComparison(Loc,lex,rex); 2442 } 2443 2444 // Return the type for the comparison, which is the same as vector type for 2445 // integer vectors, or an integer type of identical size and number of 2446 // elements for floating point vectors. 2447 if (lType->isIntegerType()) 2448 return lType; 2449 2450 const VectorType *VTy = lType->getAsVectorType(); 2451 2452 // FIXME: need to deal with non-32b int / non-64b long long 2453 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 2454 if (TypeSize == 32) { 2455 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 2456 } 2457 assert(TypeSize == 64 && "Unhandled vector element size in vector compare"); 2458 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 2459} 2460 2461inline QualType Sema::CheckBitwiseOperands( 2462 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) 2463{ 2464 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 2465 return CheckVectorOperands(Loc, lex, rex); 2466 2467 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 2468 2469 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType()) 2470 return compType; 2471 return InvalidOperands(Loc, lex, rex); 2472} 2473 2474inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 2475 Expr *&lex, Expr *&rex, SourceLocation Loc) 2476{ 2477 UsualUnaryConversions(lex); 2478 UsualUnaryConversions(rex); 2479 2480 if (lex->getType()->isScalarType() && rex->getType()->isScalarType()) 2481 return Context.IntTy; 2482 return InvalidOperands(Loc, lex, rex); 2483} 2484 2485/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 2486/// emit an error and return true. If so, return false. 2487static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 2488 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context); 2489 if (IsLV == Expr::MLV_Valid) 2490 return false; 2491 2492 unsigned Diag = 0; 2493 bool NeedType = false; 2494 switch (IsLV) { // C99 6.5.16p2 2495 default: assert(0 && "Unknown result from isModifiableLvalue!"); 2496 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break; 2497 case Expr::MLV_ArrayType: 2498 Diag = diag::err_typecheck_array_not_modifiable_lvalue; 2499 NeedType = true; 2500 break; 2501 case Expr::MLV_NotObjectType: 2502 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue; 2503 NeedType = true; 2504 break; 2505 case Expr::MLV_LValueCast: 2506 Diag = diag::err_typecheck_lvalue_casts_not_supported; 2507 break; 2508 case Expr::MLV_InvalidExpression: 2509 Diag = diag::err_typecheck_expression_not_modifiable_lvalue; 2510 break; 2511 case Expr::MLV_IncompleteType: 2512 case Expr::MLV_IncompleteVoidType: 2513 Diag = diag::err_typecheck_incomplete_type_not_modifiable_lvalue; 2514 NeedType = true; 2515 break; 2516 case Expr::MLV_DuplicateVectorComponents: 2517 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 2518 break; 2519 case Expr::MLV_NotBlockQualified: 2520 Diag = diag::err_block_decl_ref_not_modifiable_lvalue; 2521 break; 2522 case Expr::MLV_ReadonlyProperty: 2523 Diag = diag::error_readonly_property_assignment; 2524 break; 2525 } 2526 2527 if (NeedType) 2528 S.Diag(Loc, Diag) << E->getType().getAsString() << E->getSourceRange(); 2529 else 2530 S.Diag(Loc, Diag) << E->getSourceRange(); 2531 return true; 2532} 2533 2534 2535 2536// C99 6.5.16.1 2537QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS, 2538 SourceLocation Loc, 2539 QualType CompoundType) { 2540 // Verify that LHS is a modifiable lvalue, and emit error if not. 2541 if (CheckForModifiableLvalue(LHS, Loc, *this)) 2542 return QualType(); 2543 2544 QualType LHSType = LHS->getType(); 2545 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType; 2546 2547 AssignConvertType ConvTy; 2548 if (CompoundType.isNull()) { 2549 // Simple assignment "x = y". 2550 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS); 2551 2552 // If the RHS is a unary plus or minus, check to see if they = and + are 2553 // right next to each other. If so, the user may have typo'd "x =+ 4" 2554 // instead of "x += 4". 2555 Expr *RHSCheck = RHS; 2556 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 2557 RHSCheck = ICE->getSubExpr(); 2558 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 2559 if ((UO->getOpcode() == UnaryOperator::Plus || 2560 UO->getOpcode() == UnaryOperator::Minus) && 2561 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 2562 // Only if the two operators are exactly adjacent. 2563 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc()) 2564 Diag(Loc, diag::warn_not_compound_assign) 2565 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-") 2566 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 2567 } 2568 } else { 2569 // Compound assignment "x += y" 2570 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType); 2571 } 2572 2573 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 2574 RHS, "assigning")) 2575 return QualType(); 2576 2577 // C99 6.5.16p3: The type of an assignment expression is the type of the 2578 // left operand unless the left operand has qualified type, in which case 2579 // it is the unqualified version of the type of the left operand. 2580 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 2581 // is converted to the type of the assignment expression (above). 2582 // C++ 5.17p1: the type of the assignment expression is that of its left 2583 // oprdu. 2584 return LHSType.getUnqualifiedType(); 2585} 2586 2587// C99 6.5.17 2588QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) { 2589 // FIXME: what is required for LHS? 2590 2591 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions. 2592 DefaultFunctionArrayConversion(RHS); 2593 return RHS->getType(); 2594} 2595 2596/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 2597/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 2598QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc) { 2599 QualType ResType = Op->getType(); 2600 assert(!ResType.isNull() && "no type for increment/decrement expression"); 2601 2602 // C99 6.5.2.4p1: We allow complex as a GCC extension. 2603 if (ResType->isRealType()) { 2604 // OK! 2605 } else if (const PointerType *PT = ResType->getAsPointerType()) { 2606 // C99 6.5.2.4p2, 6.5.6p2 2607 if (PT->getPointeeType()->isObjectType()) { 2608 // Pointer to object is ok! 2609 } else if (PT->getPointeeType()->isVoidType()) { 2610 // Pointer to void is extension. 2611 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange(); 2612 } else { 2613 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type) 2614 << ResType.getAsString() << Op->getSourceRange(); 2615 return QualType(); 2616 } 2617 } else if (ResType->isComplexType()) { 2618 // C99 does not support ++/-- on complex types, we allow as an extension. 2619 Diag(OpLoc, diag::ext_integer_increment_complex) 2620 << ResType.getAsString() << Op->getSourceRange(); 2621 } else { 2622 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 2623 << ResType.getAsString() << Op->getSourceRange(); 2624 return QualType(); 2625 } 2626 // At this point, we know we have a real, complex or pointer type. 2627 // Now make sure the operand is a modifiable lvalue. 2628 if (CheckForModifiableLvalue(Op, OpLoc, *this)) 2629 return QualType(); 2630 return ResType; 2631} 2632 2633/// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 2634/// This routine allows us to typecheck complex/recursive expressions 2635/// where the declaration is needed for type checking. We only need to 2636/// handle cases when the expression references a function designator 2637/// or is an lvalue. Here are some examples: 2638/// - &(x) => x 2639/// - &*****f => f for f a function designator. 2640/// - &s.xx => s 2641/// - &s.zz[1].yy -> s, if zz is an array 2642/// - *(x + 1) -> x, if x is an array 2643/// - &"123"[2] -> 0 2644/// - & __real__ x -> x 2645static NamedDecl *getPrimaryDecl(Expr *E) { 2646 switch (E->getStmtClass()) { 2647 case Stmt::DeclRefExprClass: 2648 return cast<DeclRefExpr>(E)->getDecl(); 2649 case Stmt::MemberExprClass: 2650 // Fields cannot be declared with a 'register' storage class. 2651 // &X->f is always ok, even if X is declared register. 2652 if (cast<MemberExpr>(E)->isArrow()) 2653 return 0; 2654 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 2655 case Stmt::ArraySubscriptExprClass: { 2656 // &X[4] and &4[X] refers to X if X is not a pointer. 2657 2658 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase()); 2659 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D); 2660 if (!VD || VD->getType()->isPointerType()) 2661 return 0; 2662 else 2663 return VD; 2664 } 2665 case Stmt::UnaryOperatorClass: { 2666 UnaryOperator *UO = cast<UnaryOperator>(E); 2667 2668 switch(UO->getOpcode()) { 2669 case UnaryOperator::Deref: { 2670 // *(X + 1) refers to X if X is not a pointer. 2671 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) { 2672 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2673 if (!VD || VD->getType()->isPointerType()) 2674 return 0; 2675 return VD; 2676 } 2677 return 0; 2678 } 2679 case UnaryOperator::Real: 2680 case UnaryOperator::Imag: 2681 case UnaryOperator::Extension: 2682 return getPrimaryDecl(UO->getSubExpr()); 2683 default: 2684 return 0; 2685 } 2686 } 2687 case Stmt::BinaryOperatorClass: { 2688 BinaryOperator *BO = cast<BinaryOperator>(E); 2689 2690 // Handle cases involving pointer arithmetic. The result of an 2691 // Assign or AddAssign is not an lvalue so they can be ignored. 2692 2693 // (x + n) or (n + x) => x 2694 if (BO->getOpcode() == BinaryOperator::Add) { 2695 if (BO->getLHS()->getType()->isPointerType()) { 2696 return getPrimaryDecl(BO->getLHS()); 2697 } else if (BO->getRHS()->getType()->isPointerType()) { 2698 return getPrimaryDecl(BO->getRHS()); 2699 } 2700 } 2701 2702 return 0; 2703 } 2704 case Stmt::ParenExprClass: 2705 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 2706 case Stmt::ImplicitCastExprClass: 2707 // &X[4] when X is an array, has an implicit cast from array to pointer. 2708 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 2709 default: 2710 return 0; 2711 } 2712} 2713 2714/// CheckAddressOfOperand - The operand of & must be either a function 2715/// designator or an lvalue designating an object. If it is an lvalue, the 2716/// object cannot be declared with storage class register or be a bit field. 2717/// Note: The usual conversions are *not* applied to the operand of the & 2718/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 2719/// In C++, the operand might be an overloaded function name, in which case 2720/// we allow the '&' but retain the overloaded-function type. 2721QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) { 2722 if (getLangOptions().C99) { 2723 // Implement C99-only parts of addressof rules. 2724 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 2725 if (uOp->getOpcode() == UnaryOperator::Deref) 2726 // Per C99 6.5.3.2, the address of a deref always returns a valid result 2727 // (assuming the deref expression is valid). 2728 return uOp->getSubExpr()->getType(); 2729 } 2730 // Technically, there should be a check for array subscript 2731 // expressions here, but the result of one is always an lvalue anyway. 2732 } 2733 NamedDecl *dcl = getPrimaryDecl(op); 2734 Expr::isLvalueResult lval = op->isLvalue(Context); 2735 2736 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1 2737 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators 2738 // FIXME: emit more specific diag... 2739 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 2740 << op->getSourceRange(); 2741 return QualType(); 2742 } 2743 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1 2744 if (MemExpr->getMemberDecl()->isBitField()) { 2745 Diag(OpLoc, diag::err_typecheck_address_of) 2746 << "bit-field" << op->getSourceRange(); 2747 return QualType(); 2748 } 2749 // Check for Apple extension for accessing vector components. 2750 } else if (isa<ArraySubscriptExpr>(op) && 2751 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) { 2752 Diag(OpLoc, diag::err_typecheck_address_of) 2753 << "vector" << op->getSourceRange(); 2754 return QualType(); 2755 } else if (dcl) { // C99 6.5.3.2p1 2756 // We have an lvalue with a decl. Make sure the decl is not declared 2757 // with the register storage-class specifier. 2758 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 2759 if (vd->getStorageClass() == VarDecl::Register) { 2760 Diag(OpLoc, diag::err_typecheck_address_of) 2761 << "register variable" << op->getSourceRange(); 2762 return QualType(); 2763 } 2764 } else if (isa<OverloadedFunctionDecl>(dcl)) 2765 return Context.OverloadTy; 2766 else 2767 assert(0 && "Unknown/unexpected decl type"); 2768 } 2769 2770 // If the operand has type "type", the result has type "pointer to type". 2771 return Context.getPointerType(op->getType()); 2772} 2773 2774QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) { 2775 UsualUnaryConversions(op); 2776 QualType qType = op->getType(); 2777 2778 if (const PointerType *PT = qType->getAsPointerType()) { 2779 // Note that per both C89 and C99, this is always legal, even 2780 // if ptype is an incomplete type or void. 2781 // It would be possible to warn about dereferencing a 2782 // void pointer, but it's completely well-defined, 2783 // and such a warning is unlikely to catch any mistakes. 2784 return PT->getPointeeType(); 2785 } 2786 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 2787 << qType.getAsString() << op->getSourceRange(); 2788 return QualType(); 2789} 2790 2791static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode( 2792 tok::TokenKind Kind) { 2793 BinaryOperator::Opcode Opc; 2794 switch (Kind) { 2795 default: assert(0 && "Unknown binop!"); 2796 case tok::star: Opc = BinaryOperator::Mul; break; 2797 case tok::slash: Opc = BinaryOperator::Div; break; 2798 case tok::percent: Opc = BinaryOperator::Rem; break; 2799 case tok::plus: Opc = BinaryOperator::Add; break; 2800 case tok::minus: Opc = BinaryOperator::Sub; break; 2801 case tok::lessless: Opc = BinaryOperator::Shl; break; 2802 case tok::greatergreater: Opc = BinaryOperator::Shr; break; 2803 case tok::lessequal: Opc = BinaryOperator::LE; break; 2804 case tok::less: Opc = BinaryOperator::LT; break; 2805 case tok::greaterequal: Opc = BinaryOperator::GE; break; 2806 case tok::greater: Opc = BinaryOperator::GT; break; 2807 case tok::exclaimequal: Opc = BinaryOperator::NE; break; 2808 case tok::equalequal: Opc = BinaryOperator::EQ; break; 2809 case tok::amp: Opc = BinaryOperator::And; break; 2810 case tok::caret: Opc = BinaryOperator::Xor; break; 2811 case tok::pipe: Opc = BinaryOperator::Or; break; 2812 case tok::ampamp: Opc = BinaryOperator::LAnd; break; 2813 case tok::pipepipe: Opc = BinaryOperator::LOr; break; 2814 case tok::equal: Opc = BinaryOperator::Assign; break; 2815 case tok::starequal: Opc = BinaryOperator::MulAssign; break; 2816 case tok::slashequal: Opc = BinaryOperator::DivAssign; break; 2817 case tok::percentequal: Opc = BinaryOperator::RemAssign; break; 2818 case tok::plusequal: Opc = BinaryOperator::AddAssign; break; 2819 case tok::minusequal: Opc = BinaryOperator::SubAssign; break; 2820 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break; 2821 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break; 2822 case tok::ampequal: Opc = BinaryOperator::AndAssign; break; 2823 case tok::caretequal: Opc = BinaryOperator::XorAssign; break; 2824 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break; 2825 case tok::comma: Opc = BinaryOperator::Comma; break; 2826 } 2827 return Opc; 2828} 2829 2830static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode( 2831 tok::TokenKind Kind) { 2832 UnaryOperator::Opcode Opc; 2833 switch (Kind) { 2834 default: assert(0 && "Unknown unary op!"); 2835 case tok::plusplus: Opc = UnaryOperator::PreInc; break; 2836 case tok::minusminus: Opc = UnaryOperator::PreDec; break; 2837 case tok::amp: Opc = UnaryOperator::AddrOf; break; 2838 case tok::star: Opc = UnaryOperator::Deref; break; 2839 case tok::plus: Opc = UnaryOperator::Plus; break; 2840 case tok::minus: Opc = UnaryOperator::Minus; break; 2841 case tok::tilde: Opc = UnaryOperator::Not; break; 2842 case tok::exclaim: Opc = UnaryOperator::LNot; break; 2843 case tok::kw___real: Opc = UnaryOperator::Real; break; 2844 case tok::kw___imag: Opc = UnaryOperator::Imag; break; 2845 case tok::kw___extension__: Opc = UnaryOperator::Extension; break; 2846 } 2847 return Opc; 2848} 2849 2850/// CreateBuiltinBinOp - Creates a new built-in binary operation with 2851/// operator @p Opc at location @c TokLoc. This routine only supports 2852/// built-in operations; ActOnBinOp handles overloaded operators. 2853Action::ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 2854 unsigned Op, 2855 Expr *lhs, Expr *rhs) { 2856 QualType ResultTy; // Result type of the binary operator. 2857 QualType CompTy; // Computation type for compound assignments (e.g. '+=') 2858 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op; 2859 2860 switch (Opc) { 2861 default: 2862 assert(0 && "Unknown binary expr!"); 2863 case BinaryOperator::Assign: 2864 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType()); 2865 break; 2866 case BinaryOperator::Mul: 2867 case BinaryOperator::Div: 2868 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc); 2869 break; 2870 case BinaryOperator::Rem: 2871 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc); 2872 break; 2873 case BinaryOperator::Add: 2874 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc); 2875 break; 2876 case BinaryOperator::Sub: 2877 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc); 2878 break; 2879 case BinaryOperator::Shl: 2880 case BinaryOperator::Shr: 2881 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc); 2882 break; 2883 case BinaryOperator::LE: 2884 case BinaryOperator::LT: 2885 case BinaryOperator::GE: 2886 case BinaryOperator::GT: 2887 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true); 2888 break; 2889 case BinaryOperator::EQ: 2890 case BinaryOperator::NE: 2891 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false); 2892 break; 2893 case BinaryOperator::And: 2894 case BinaryOperator::Xor: 2895 case BinaryOperator::Or: 2896 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc); 2897 break; 2898 case BinaryOperator::LAnd: 2899 case BinaryOperator::LOr: 2900 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc); 2901 break; 2902 case BinaryOperator::MulAssign: 2903 case BinaryOperator::DivAssign: 2904 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true); 2905 if (!CompTy.isNull()) 2906 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy); 2907 break; 2908 case BinaryOperator::RemAssign: 2909 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true); 2910 if (!CompTy.isNull()) 2911 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy); 2912 break; 2913 case BinaryOperator::AddAssign: 2914 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true); 2915 if (!CompTy.isNull()) 2916 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy); 2917 break; 2918 case BinaryOperator::SubAssign: 2919 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true); 2920 if (!CompTy.isNull()) 2921 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy); 2922 break; 2923 case BinaryOperator::ShlAssign: 2924 case BinaryOperator::ShrAssign: 2925 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true); 2926 if (!CompTy.isNull()) 2927 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy); 2928 break; 2929 case BinaryOperator::AndAssign: 2930 case BinaryOperator::XorAssign: 2931 case BinaryOperator::OrAssign: 2932 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true); 2933 if (!CompTy.isNull()) 2934 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy); 2935 break; 2936 case BinaryOperator::Comma: 2937 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc); 2938 break; 2939 } 2940 if (ResultTy.isNull()) 2941 return true; 2942 if (CompTy.isNull()) 2943 return new BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc); 2944 else 2945 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, OpLoc); 2946} 2947 2948// Binary Operators. 'Tok' is the token for the operator. 2949Action::ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 2950 tok::TokenKind Kind, 2951 ExprTy *LHS, ExprTy *RHS) { 2952 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind); 2953 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS; 2954 2955 assert((lhs != 0) && "ActOnBinOp(): missing left expression"); 2956 assert((rhs != 0) && "ActOnBinOp(): missing right expression"); 2957 2958 if (getLangOptions().CPlusPlus && 2959 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() || 2960 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) { 2961 // If this is one of the assignment operators, we only perform 2962 // overload resolution if the left-hand side is a class or 2963 // enumeration type (C++ [expr.ass]p3). 2964 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign && 2965 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) { 2966 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs); 2967 } 2968 2969 // Determine which overloaded operator we're dealing with. 2970 static const OverloadedOperatorKind OverOps[] = { 2971 OO_Star, OO_Slash, OO_Percent, 2972 OO_Plus, OO_Minus, 2973 OO_LessLess, OO_GreaterGreater, 2974 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual, 2975 OO_EqualEqual, OO_ExclaimEqual, 2976 OO_Amp, 2977 OO_Caret, 2978 OO_Pipe, 2979 OO_AmpAmp, 2980 OO_PipePipe, 2981 OO_Equal, OO_StarEqual, 2982 OO_SlashEqual, OO_PercentEqual, 2983 OO_PlusEqual, OO_MinusEqual, 2984 OO_LessLessEqual, OO_GreaterGreaterEqual, 2985 OO_AmpEqual, OO_CaretEqual, 2986 OO_PipeEqual, 2987 OO_Comma 2988 }; 2989 OverloadedOperatorKind OverOp = OverOps[Opc]; 2990 2991 // Add the appropriate overloaded operators (C++ [over.match.oper]) 2992 // to the candidate set. 2993 OverloadCandidateSet CandidateSet; 2994 Expr *Args[2] = { lhs, rhs }; 2995 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet); 2996 2997 // Perform overload resolution. 2998 OverloadCandidateSet::iterator Best; 2999 switch (BestViableFunction(CandidateSet, Best)) { 3000 case OR_Success: { 3001 // We found a built-in operator or an overloaded operator. 3002 FunctionDecl *FnDecl = Best->Function; 3003 3004 if (FnDecl) { 3005 // We matched an overloaded operator. Build a call to that 3006 // operator. 3007 3008 // Convert the arguments. 3009 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 3010 if (PerformObjectArgumentInitialization(lhs, Method) || 3011 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(), 3012 "passing")) 3013 return true; 3014 } else { 3015 // Convert the arguments. 3016 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(), 3017 "passing") || 3018 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(), 3019 "passing")) 3020 return true; 3021 } 3022 3023 // Determine the result type 3024 QualType ResultTy 3025 = FnDecl->getType()->getAsFunctionType()->getResultType(); 3026 ResultTy = ResultTy.getNonReferenceType(); 3027 3028 // Build the actual expression node. 3029 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(), 3030 SourceLocation()); 3031 UsualUnaryConversions(FnExpr); 3032 3033 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, TokLoc); 3034 } else { 3035 // We matched a built-in operator. Convert the arguments, then 3036 // break out so that we will build the appropriate built-in 3037 // operator node. 3038 if (PerformCopyInitialization(lhs, Best->BuiltinTypes.ParamTypes[0], 3039 "passing") || 3040 PerformCopyInitialization(rhs, Best->BuiltinTypes.ParamTypes[1], 3041 "passing")) 3042 return true; 3043 3044 break; 3045 } 3046 } 3047 3048 case OR_No_Viable_Function: 3049 // No viable function; fall through to handling this as a 3050 // built-in operator, which will produce an error message for us. 3051 break; 3052 3053 case OR_Ambiguous: 3054 Diag(TokLoc, diag::err_ovl_ambiguous_oper) 3055 << BinaryOperator::getOpcodeStr(Opc) 3056 << lhs->getSourceRange() << rhs->getSourceRange(); 3057 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 3058 return true; 3059 } 3060 3061 // Either we found no viable overloaded operator or we matched a 3062 // built-in operator. In either case, fall through to trying to 3063 // build a built-in operation. 3064 } 3065 3066 // Build a built-in binary operation. 3067 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs); 3068} 3069 3070// Unary Operators. 'Tok' is the token for the operator. 3071Action::ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 3072 tok::TokenKind Op, ExprTy *input) { 3073 Expr *Input = (Expr*)input; 3074 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op); 3075 3076 if (getLangOptions().CPlusPlus && 3077 (Input->getType()->isRecordType() 3078 || Input->getType()->isEnumeralType())) { 3079 // Determine which overloaded operator we're dealing with. 3080 static const OverloadedOperatorKind OverOps[] = { 3081 OO_None, OO_None, 3082 OO_PlusPlus, OO_MinusMinus, 3083 OO_Amp, OO_Star, 3084 OO_Plus, OO_Minus, 3085 OO_Tilde, OO_Exclaim, 3086 OO_None, OO_None, 3087 OO_None, 3088 OO_None 3089 }; 3090 OverloadedOperatorKind OverOp = OverOps[Opc]; 3091 3092 // Add the appropriate overloaded operators (C++ [over.match.oper]) 3093 // to the candidate set. 3094 OverloadCandidateSet CandidateSet; 3095 if (OverOp != OO_None) 3096 AddOperatorCandidates(OverOp, S, &Input, 1, CandidateSet); 3097 3098 // Perform overload resolution. 3099 OverloadCandidateSet::iterator Best; 3100 switch (BestViableFunction(CandidateSet, Best)) { 3101 case OR_Success: { 3102 // We found a built-in operator or an overloaded operator. 3103 FunctionDecl *FnDecl = Best->Function; 3104 3105 if (FnDecl) { 3106 // We matched an overloaded operator. Build a call to that 3107 // operator. 3108 3109 // Convert the arguments. 3110 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 3111 if (PerformObjectArgumentInitialization(Input, Method)) 3112 return true; 3113 } else { 3114 // Convert the arguments. 3115 if (PerformCopyInitialization(Input, 3116 FnDecl->getParamDecl(0)->getType(), 3117 "passing")) 3118 return true; 3119 } 3120 3121 // Determine the result type 3122 QualType ResultTy 3123 = FnDecl->getType()->getAsFunctionType()->getResultType(); 3124 ResultTy = ResultTy.getNonReferenceType(); 3125 3126 // Build the actual expression node. 3127 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(), 3128 SourceLocation()); 3129 UsualUnaryConversions(FnExpr); 3130 3131 return new CXXOperatorCallExpr(FnExpr, &Input, 1, ResultTy, OpLoc); 3132 } else { 3133 // We matched a built-in operator. Convert the arguments, then 3134 // break out so that we will build the appropriate built-in 3135 // operator node. 3136 if (PerformCopyInitialization(Input, Best->BuiltinTypes.ParamTypes[0], 3137 "passing")) 3138 return true; 3139 3140 break; 3141 } 3142 } 3143 3144 case OR_No_Viable_Function: 3145 // No viable function; fall through to handling this as a 3146 // built-in operator, which will produce an error message for us. 3147 break; 3148 3149 case OR_Ambiguous: 3150 Diag(OpLoc, diag::err_ovl_ambiguous_oper) 3151 << UnaryOperator::getOpcodeStr(Opc) 3152 << Input->getSourceRange(); 3153 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 3154 return true; 3155 } 3156 3157 // Either we found no viable overloaded operator or we matched a 3158 // built-in operator. In either case, fall through to trying to 3159 // build a built-in operation. 3160 } 3161 3162 3163 QualType resultType; 3164 switch (Opc) { 3165 default: 3166 assert(0 && "Unimplemented unary expr!"); 3167 case UnaryOperator::PreInc: 3168 case UnaryOperator::PreDec: 3169 resultType = CheckIncrementDecrementOperand(Input, OpLoc); 3170 break; 3171 case UnaryOperator::AddrOf: 3172 resultType = CheckAddressOfOperand(Input, OpLoc); 3173 break; 3174 case UnaryOperator::Deref: 3175 DefaultFunctionArrayConversion(Input); 3176 resultType = CheckIndirectionOperand(Input, OpLoc); 3177 break; 3178 case UnaryOperator::Plus: 3179 case UnaryOperator::Minus: 3180 UsualUnaryConversions(Input); 3181 resultType = Input->getType(); 3182 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 3183 break; 3184 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7 3185 resultType->isEnumeralType()) 3186 break; 3187 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6 3188 Opc == UnaryOperator::Plus && 3189 resultType->isPointerType()) 3190 break; 3191 3192 return Diag(OpLoc, diag::err_typecheck_unary_expr) 3193 << resultType.getAsString(); 3194 case UnaryOperator::Not: // bitwise complement 3195 UsualUnaryConversions(Input); 3196 resultType = Input->getType(); 3197 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 3198 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 3199 // C99 does not support '~' for complex conjugation. 3200 Diag(OpLoc, diag::ext_integer_complement_complex) 3201 << resultType.getAsString() << Input->getSourceRange(); 3202 else if (!resultType->isIntegerType()) 3203 return Diag(OpLoc, diag::err_typecheck_unary_expr) 3204 << resultType.getAsString() << Input->getSourceRange(); 3205 break; 3206 case UnaryOperator::LNot: // logical negation 3207 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 3208 DefaultFunctionArrayConversion(Input); 3209 resultType = Input->getType(); 3210 if (!resultType->isScalarType()) // C99 6.5.3.3p1 3211 return Diag(OpLoc, diag::err_typecheck_unary_expr) 3212 << resultType.getAsString(); 3213 // LNot always has type int. C99 6.5.3.3p5. 3214 resultType = Context.IntTy; 3215 break; 3216 case UnaryOperator::Real: 3217 case UnaryOperator::Imag: 3218 resultType = CheckRealImagOperand(Input, OpLoc); 3219 break; 3220 case UnaryOperator::Extension: 3221 resultType = Input->getType(); 3222 break; 3223 } 3224 if (resultType.isNull()) 3225 return true; 3226 return new UnaryOperator(Input, Opc, resultType, OpLoc); 3227} 3228 3229/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 3230Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, 3231 SourceLocation LabLoc, 3232 IdentifierInfo *LabelII) { 3233 // Look up the record for this label identifier. 3234 LabelStmt *&LabelDecl = LabelMap[LabelII]; 3235 3236 // If we haven't seen this label yet, create a forward reference. It 3237 // will be validated and/or cleaned up in ActOnFinishFunctionBody. 3238 if (LabelDecl == 0) 3239 LabelDecl = new LabelStmt(LabLoc, LabelII, 0); 3240 3241 // Create the AST node. The address of a label always has type 'void*'. 3242 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl, 3243 Context.getPointerType(Context.VoidTy)); 3244} 3245 3246Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt, 3247 SourceLocation RPLoc) { // "({..})" 3248 Stmt *SubStmt = static_cast<Stmt*>(substmt); 3249 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 3250 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 3251 3252 // FIXME: there are a variety of strange constraints to enforce here, for 3253 // example, it is not possible to goto into a stmt expression apparently. 3254 // More semantic analysis is needed. 3255 3256 // FIXME: the last statement in the compount stmt has its value used. We 3257 // should not warn about it being unused. 3258 3259 // If there are sub stmts in the compound stmt, take the type of the last one 3260 // as the type of the stmtexpr. 3261 QualType Ty = Context.VoidTy; 3262 3263 if (!Compound->body_empty()) { 3264 Stmt *LastStmt = Compound->body_back(); 3265 // If LastStmt is a label, skip down through into the body. 3266 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) 3267 LastStmt = Label->getSubStmt(); 3268 3269 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) 3270 Ty = LastExpr->getType(); 3271 } 3272 3273 return new StmtExpr(Compound, Ty, LPLoc, RPLoc); 3274} 3275 3276Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc, 3277 SourceLocation TypeLoc, 3278 TypeTy *argty, 3279 OffsetOfComponent *CompPtr, 3280 unsigned NumComponents, 3281 SourceLocation RPLoc) { 3282 QualType ArgTy = QualType::getFromOpaquePtr(argty); 3283 assert(!ArgTy.isNull() && "Missing type argument!"); 3284 3285 // We must have at least one component that refers to the type, and the first 3286 // one is known to be a field designator. Verify that the ArgTy represents 3287 // a struct/union/class. 3288 if (!ArgTy->isRecordType()) 3289 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy.getAsString(); 3290 3291 // Otherwise, create a compound literal expression as the base, and 3292 // iteratively process the offsetof designators. 3293 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false); 3294 3295 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 3296 // GCC extension, diagnose them. 3297 if (NumComponents != 1) 3298 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 3299 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); 3300 3301 for (unsigned i = 0; i != NumComponents; ++i) { 3302 const OffsetOfComponent &OC = CompPtr[i]; 3303 if (OC.isBrackets) { 3304 // Offset of an array sub-field. TODO: Should we allow vector elements? 3305 const ArrayType *AT = Context.getAsArrayType(Res->getType()); 3306 if (!AT) { 3307 delete Res; 3308 return Diag(OC.LocEnd, diag::err_offsetof_array_type) 3309 << Res->getType().getAsString(); 3310 } 3311 3312 // FIXME: C++: Verify that operator[] isn't overloaded. 3313 3314 // C99 6.5.2.1p1 3315 Expr *Idx = static_cast<Expr*>(OC.U.E); 3316 if (!Idx->getType()->isIntegerType()) 3317 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript) 3318 << Idx->getSourceRange(); 3319 3320 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd); 3321 continue; 3322 } 3323 3324 const RecordType *RC = Res->getType()->getAsRecordType(); 3325 if (!RC) { 3326 delete Res; 3327 return Diag(OC.LocEnd, diag::err_offsetof_record_type) 3328 << Res->getType().getAsString(); 3329 } 3330 3331 // Get the decl corresponding to this. 3332 RecordDecl *RD = RC->getDecl(); 3333 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo); 3334 if (!MemberDecl) 3335 return Diag(BuiltinLoc, diag::err_typecheck_no_member) 3336 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd); 3337 3338 // FIXME: C++: Verify that MemberDecl isn't a static field. 3339 // FIXME: Verify that MemberDecl isn't a bitfield. 3340 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't 3341 // matter here. 3342 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, 3343 MemberDecl->getType().getNonReferenceType()); 3344 } 3345 3346 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(), 3347 BuiltinLoc); 3348} 3349 3350 3351Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc, 3352 TypeTy *arg1, TypeTy *arg2, 3353 SourceLocation RPLoc) { 3354 QualType argT1 = QualType::getFromOpaquePtr(arg1); 3355 QualType argT2 = QualType::getFromOpaquePtr(arg2); 3356 3357 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)"); 3358 3359 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc); 3360} 3361 3362Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond, 3363 ExprTy *expr1, ExprTy *expr2, 3364 SourceLocation RPLoc) { 3365 Expr *CondExpr = static_cast<Expr*>(cond); 3366 Expr *LHSExpr = static_cast<Expr*>(expr1); 3367 Expr *RHSExpr = static_cast<Expr*>(expr2); 3368 3369 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 3370 3371 // The conditional expression is required to be a constant expression. 3372 llvm::APSInt condEval(32); 3373 SourceLocation ExpLoc; 3374 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc)) 3375 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant) 3376 << CondExpr->getSourceRange(); 3377 3378 // If the condition is > zero, then the AST type is the same as the LSHExpr. 3379 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() : 3380 RHSExpr->getType(); 3381 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc); 3382} 3383 3384//===----------------------------------------------------------------------===// 3385// Clang Extensions. 3386//===----------------------------------------------------------------------===// 3387 3388/// ActOnBlockStart - This callback is invoked when a block literal is started. 3389void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) { 3390 // Analyze block parameters. 3391 BlockSemaInfo *BSI = new BlockSemaInfo(); 3392 3393 // Add BSI to CurBlock. 3394 BSI->PrevBlockInfo = CurBlock; 3395 CurBlock = BSI; 3396 3397 BSI->ReturnType = 0; 3398 BSI->TheScope = BlockScope; 3399 3400 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc); 3401 PushDeclContext(BSI->TheDecl); 3402} 3403 3404void Sema::ActOnBlockArguments(Declarator &ParamInfo) { 3405 // Analyze arguments to block. 3406 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function && 3407 "Not a function declarator!"); 3408 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun; 3409 3410 CurBlock->hasPrototype = FTI.hasPrototype; 3411 CurBlock->isVariadic = true; 3412 3413 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes 3414 // no arguments, not a function that takes a single void argument. 3415 if (FTI.hasPrototype && 3416 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 3417 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() && 3418 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) { 3419 // empty arg list, don't push any params. 3420 CurBlock->isVariadic = false; 3421 } else if (FTI.hasPrototype) { 3422 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) 3423 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param); 3424 CurBlock->isVariadic = FTI.isVariadic; 3425 } 3426 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size()); 3427 3428 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(), 3429 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) 3430 // If this has an identifier, add it to the scope stack. 3431 if ((*AI)->getIdentifier()) 3432 PushOnScopeChains(*AI, CurBlock->TheScope); 3433} 3434 3435/// ActOnBlockError - If there is an error parsing a block, this callback 3436/// is invoked to pop the information about the block from the action impl. 3437void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 3438 // Ensure that CurBlock is deleted. 3439 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock); 3440 3441 // Pop off CurBlock, handle nested blocks. 3442 CurBlock = CurBlock->PrevBlockInfo; 3443 3444 // FIXME: Delete the ParmVarDecl objects as well??? 3445 3446} 3447 3448/// ActOnBlockStmtExpr - This is called when the body of a block statement 3449/// literal was successfully completed. ^(int x){...} 3450Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body, 3451 Scope *CurScope) { 3452 // Ensure that CurBlock is deleted. 3453 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock); 3454 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body)); 3455 3456 PopDeclContext(); 3457 3458 // Pop off CurBlock, handle nested blocks. 3459 CurBlock = CurBlock->PrevBlockInfo; 3460 3461 QualType RetTy = Context.VoidTy; 3462 if (BSI->ReturnType) 3463 RetTy = QualType(BSI->ReturnType, 0); 3464 3465 llvm::SmallVector<QualType, 8> ArgTypes; 3466 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i) 3467 ArgTypes.push_back(BSI->Params[i]->getType()); 3468 3469 QualType BlockTy; 3470 if (!BSI->hasPrototype) 3471 BlockTy = Context.getFunctionTypeNoProto(RetTy); 3472 else 3473 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(), 3474 BSI->isVariadic, 0); 3475 3476 BlockTy = Context.getBlockPointerType(BlockTy); 3477 3478 BSI->TheDecl->setBody(Body.take()); 3479 return new BlockExpr(BSI->TheDecl, BlockTy); 3480} 3481 3482/// ExprsMatchFnType - return true if the Exprs in array Args have 3483/// QualTypes that match the QualTypes of the arguments of the FnType. 3484/// The number of arguments has already been validated to match the number of 3485/// arguments in FnType. 3486static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType, 3487 ASTContext &Context) { 3488 unsigned NumParams = FnType->getNumArgs(); 3489 for (unsigned i = 0; i != NumParams; ++i) { 3490 QualType ExprTy = Context.getCanonicalType(Args[i]->getType()); 3491 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i)); 3492 3493 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType()) 3494 return false; 3495 } 3496 return true; 3497} 3498 3499Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs, 3500 SourceLocation *CommaLocs, 3501 SourceLocation BuiltinLoc, 3502 SourceLocation RParenLoc) { 3503 // __builtin_overload requires at least 2 arguments 3504 if (NumArgs < 2) 3505 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args) 3506 << SourceRange(BuiltinLoc, RParenLoc); 3507 3508 // The first argument is required to be a constant expression. It tells us 3509 // the number of arguments to pass to each of the functions to be overloaded. 3510 Expr **Args = reinterpret_cast<Expr**>(args); 3511 Expr *NParamsExpr = Args[0]; 3512 llvm::APSInt constEval(32); 3513 SourceLocation ExpLoc; 3514 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc)) 3515 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant) 3516 << NParamsExpr->getSourceRange(); 3517 3518 // Verify that the number of parameters is > 0 3519 unsigned NumParams = constEval.getZExtValue(); 3520 if (NumParams == 0) 3521 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant) 3522 << NParamsExpr->getSourceRange(); 3523 // Verify that we have at least 1 + NumParams arguments to the builtin. 3524 if ((NumParams + 1) > NumArgs) 3525 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args) 3526 << SourceRange(BuiltinLoc, RParenLoc); 3527 3528 // Figure out the return type, by matching the args to one of the functions 3529 // listed after the parameters. 3530 OverloadExpr *OE = 0; 3531 for (unsigned i = NumParams + 1; i < NumArgs; ++i) { 3532 // UsualUnaryConversions will convert the function DeclRefExpr into a 3533 // pointer to function. 3534 Expr *Fn = UsualUnaryConversions(Args[i]); 3535 const FunctionTypeProto *FnType = 0; 3536 if (const PointerType *PT = Fn->getType()->getAsPointerType()) 3537 FnType = PT->getPointeeType()->getAsFunctionTypeProto(); 3538 3539 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no 3540 // parameters, and the number of parameters must match the value passed to 3541 // the builtin. 3542 if (!FnType || (FnType->getNumArgs() != NumParams)) 3543 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype) 3544 << Fn->getSourceRange(); 3545 3546 // Scan the parameter list for the FunctionType, checking the QualType of 3547 // each parameter against the QualTypes of the arguments to the builtin. 3548 // If they match, return a new OverloadExpr. 3549 if (ExprsMatchFnType(Args+1, FnType, Context)) { 3550 if (OE) 3551 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match) 3552 << OE->getFn()->getSourceRange(); 3553 // Remember our match, and continue processing the remaining arguments 3554 // to catch any errors. 3555 OE = new OverloadExpr(Args, NumArgs, i, 3556 FnType->getResultType().getNonReferenceType(), 3557 BuiltinLoc, RParenLoc); 3558 } 3559 } 3560 // Return the newly created OverloadExpr node, if we succeded in matching 3561 // exactly one of the candidate functions. 3562 if (OE) 3563 return OE; 3564 3565 // If we didn't find a matching function Expr in the __builtin_overload list 3566 // the return an error. 3567 std::string typeNames; 3568 for (unsigned i = 0; i != NumParams; ++i) { 3569 if (i != 0) typeNames += ", "; 3570 typeNames += Args[i+1]->getType().getAsString(); 3571 } 3572 3573 return Diag(BuiltinLoc, diag::err_overload_no_match) 3574 << typeNames << SourceRange(BuiltinLoc, RParenLoc); 3575} 3576 3577Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 3578 ExprTy *expr, TypeTy *type, 3579 SourceLocation RPLoc) { 3580 Expr *E = static_cast<Expr*>(expr); 3581 QualType T = QualType::getFromOpaquePtr(type); 3582 3583 InitBuiltinVaListType(); 3584 3585 // Get the va_list type 3586 QualType VaListType = Context.getBuiltinVaListType(); 3587 // Deal with implicit array decay; for example, on x86-64, 3588 // va_list is an array, but it's supposed to decay to 3589 // a pointer for va_arg. 3590 if (VaListType->isArrayType()) 3591 VaListType = Context.getArrayDecayedType(VaListType); 3592 // Make sure the input expression also decays appropriately. 3593 UsualUnaryConversions(E); 3594 3595 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible) 3596 return Diag(E->getLocStart(), 3597 diag::err_first_argument_to_va_arg_not_of_type_va_list) 3598 << E->getType().getAsString() << E->getSourceRange(); 3599 3600 // FIXME: Warn if a non-POD type is passed in. 3601 3602 return new VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc); 3603} 3604 3605bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 3606 SourceLocation Loc, 3607 QualType DstType, QualType SrcType, 3608 Expr *SrcExpr, const char *Flavor) { 3609 // Decode the result (notice that AST's are still created for extensions). 3610 bool isInvalid = false; 3611 unsigned DiagKind; 3612 switch (ConvTy) { 3613 default: assert(0 && "Unknown conversion type"); 3614 case Compatible: return false; 3615 case PointerToInt: 3616 DiagKind = diag::ext_typecheck_convert_pointer_int; 3617 break; 3618 case IntToPointer: 3619 DiagKind = diag::ext_typecheck_convert_int_pointer; 3620 break; 3621 case IncompatiblePointer: 3622 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 3623 break; 3624 case FunctionVoidPointer: 3625 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 3626 break; 3627 case CompatiblePointerDiscardsQualifiers: 3628 // If the qualifiers lost were because we were applying the 3629 // (deprecated) C++ conversion from a string literal to a char* 3630 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 3631 // Ideally, this check would be performed in 3632 // CheckPointerTypesForAssignment. However, that would require a 3633 // bit of refactoring (so that the second argument is an 3634 // expression, rather than a type), which should be done as part 3635 // of a larger effort to fix CheckPointerTypesForAssignment for 3636 // C++ semantics. 3637 if (getLangOptions().CPlusPlus && 3638 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 3639 return false; 3640 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 3641 break; 3642 case IntToBlockPointer: 3643 DiagKind = diag::err_int_to_block_pointer; 3644 break; 3645 case IncompatibleBlockPointer: 3646 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer; 3647 break; 3648 case BlockVoidPointer: 3649 DiagKind = diag::ext_typecheck_convert_pointer_void_block; 3650 break; 3651 case IncompatibleObjCQualifiedId: 3652 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since 3653 // it can give a more specific diagnostic. 3654 DiagKind = diag::warn_incompatible_qualified_id; 3655 break; 3656 case Incompatible: 3657 DiagKind = diag::err_typecheck_convert_incompatible; 3658 isInvalid = true; 3659 break; 3660 } 3661 3662 Diag(Loc, DiagKind) << DstType.getAsString() << SrcType.getAsString() 3663 << Flavor << SrcExpr->getSourceRange(); 3664 return isInvalid; 3665} 3666