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