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/AST/DeclTemplate.h" 20 #include "clang/Lex/Preprocessor.h" 21 #include "clang/Lex/LiteralSupport.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" 27 using namespace clang; 28 29 /// \brief Determine whether the use of this declaration is valid, and 30 /// emit any corresponding diagnostics. 31 /// 32 /// This routine diagnoses various problems with referencing 33 /// declarations that can occur when using a declaration. For example, 34 /// it might warn if a deprecated or unavailable declaration is being 35 /// used, or produce an error (and return true) if a C++0x deleted 36 /// function is being used. 37 /// 38 /// \returns true if there was an error (this declaration cannot be 39 /// referenced), false otherwise. 40 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) { 41 // See if the decl is deprecated. 42 if (D->getAttr<DeprecatedAttr>()) { 43 // Implementing deprecated stuff requires referencing deprecated 44 // stuff. Don't warn if we are implementing a deprecated 45 // construct. 46 bool isSilenced = false; 47 48 if (NamedDecl *ND = getCurFunctionOrMethodDecl()) { 49 // If this reference happens *in* a deprecated function or method, don't 50 // warn. 51 isSilenced = ND->getAttr<DeprecatedAttr>(); 52 53 // If this is an Objective-C method implementation, check to see if the 54 // method was deprecated on the declaration, not the definition. 55 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND)) { 56 // The semantic decl context of a ObjCMethodDecl is the 57 // ObjCImplementationDecl. 58 if (ObjCImplementationDecl *Impl 59 = dyn_cast<ObjCImplementationDecl>(MD->getParent())) { 60 61 MD = Impl->getClassInterface()->getMethod(MD->getSelector(), 62 MD->isInstanceMethod()); 63 isSilenced |= MD && MD->getAttr<DeprecatedAttr>(); 64 } 65 } 66 } 67 68 if (!isSilenced) 69 Diag(Loc, diag::warn_deprecated) << D->getDeclName(); 70 } 71 72 // See if this is a deleted function. 73 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 74 if (FD->isDeleted()) { 75 Diag(Loc, diag::err_deleted_function_use); 76 Diag(D->getLocation(), diag::note_unavailable_here) << true; 77 return true; 78 } 79 } 80 81 // See if the decl is unavailable 82 if (D->getAttr<UnavailableAttr>()) { 83 Diag(Loc, diag::warn_unavailable) << D->getDeclName(); 84 Diag(D->getLocation(), diag::note_unavailable_here) << 0; 85 } 86 87 return false; 88 } 89 90 /// DiagnoseSentinelCalls - This routine checks on method dispatch calls 91 /// (and other functions in future), which have been declared with sentinel 92 /// attribute. It warns if call does not have the sentinel argument. 93 /// 94 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 95 Expr **Args, unsigned NumArgs) 96 { 97 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 98 if (!attr) 99 return; 100 int sentinelPos = attr->getSentinel(); 101 int nullPos = attr->getNullPos(); 102 103 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common 104 // base class. Then we won't be needing two versions of the same code. 105 unsigned int i = 0; 106 bool warnNotEnoughArgs = false; 107 int isMethod = 0; 108 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 109 // skip over named parameters. 110 ObjCMethodDecl::param_iterator P, E = MD->param_end(); 111 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) { 112 if (nullPos) 113 --nullPos; 114 else 115 ++i; 116 } 117 warnNotEnoughArgs = (P != E || i >= NumArgs); 118 isMethod = 1; 119 } 120 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 121 // skip over named parameters. 122 ObjCMethodDecl::param_iterator P, E = FD->param_end(); 123 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) { 124 if (nullPos) 125 --nullPos; 126 else 127 ++i; 128 } 129 warnNotEnoughArgs = (P != E || i >= NumArgs); 130 } 131 else if (VarDecl *V = dyn_cast<VarDecl>(D)) { 132 // block or function pointer call. 133 QualType Ty = V->getType(); 134 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) { 135 const FunctionType *FT = Ty->isFunctionPointerType() 136 ? Ty->getAsPointerType()->getPointeeType()->getAsFunctionType() 137 : Ty->getAsBlockPointerType()->getPointeeType()->getAsFunctionType(); 138 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) { 139 unsigned NumArgsInProto = Proto->getNumArgs(); 140 unsigned k; 141 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) { 142 if (nullPos) 143 --nullPos; 144 else 145 ++i; 146 } 147 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs); 148 } 149 if (Ty->isBlockPointerType()) 150 isMethod = 2; 151 } 152 else 153 return; 154 } 155 else 156 return; 157 158 if (warnNotEnoughArgs) { 159 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 160 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod; 161 return; 162 } 163 int sentinel = i; 164 while (sentinelPos > 0 && i < NumArgs-1) { 165 --sentinelPos; 166 ++i; 167 } 168 if (sentinelPos > 0) { 169 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 170 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod; 171 return; 172 } 173 while (i < NumArgs-1) { 174 ++i; 175 ++sentinel; 176 } 177 Expr *sentinelExpr = Args[sentinel]; 178 if (sentinelExpr && (!sentinelExpr->getType()->isPointerType() || 179 !sentinelExpr->isNullPointerConstant(Context))) { 180 Diag(Loc, diag::warn_missing_sentinel) << isMethod; 181 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod; 182 } 183 return; 184 } 185 186 SourceRange Sema::getExprRange(ExprTy *E) const { 187 Expr *Ex = (Expr *)E; 188 return Ex? Ex->getSourceRange() : SourceRange(); 189 } 190 191 //===----------------------------------------------------------------------===// 192 // Standard Promotions and Conversions 193 //===----------------------------------------------------------------------===// 194 195 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 196 void Sema::DefaultFunctionArrayConversion(Expr *&E) { 197 QualType Ty = E->getType(); 198 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 199 200 if (Ty->isFunctionType()) 201 ImpCastExprToType(E, Context.getPointerType(Ty)); 202 else if (Ty->isArrayType()) { 203 // In C90 mode, arrays only promote to pointers if the array expression is 204 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 205 // type 'array of type' is converted to an expression that has type 'pointer 206 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 207 // that has type 'array of type' ...". The relevant change is "an lvalue" 208 // (C90) to "an expression" (C99). 209 // 210 // C++ 4.2p1: 211 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 212 // T" can be converted to an rvalue of type "pointer to T". 213 // 214 if (getLangOptions().C99 || getLangOptions().CPlusPlus || 215 E->isLvalue(Context) == Expr::LV_Valid) 216 ImpCastExprToType(E, Context.getArrayDecayedType(Ty)); 217 } 218 } 219 220 /// \brief Whether this is a promotable bitfield reference according 221 /// to C99 6.3.1.1p2, bullet 2. 222 /// 223 /// \returns the type this bit-field will promote to, or NULL if no 224 /// promotion occurs. 225 static QualType isPromotableBitField(Expr *E, ASTContext &Context) { 226 FieldDecl *Field = E->getBitField(); 227 if (!Field) 228 return QualType(); 229 230 const BuiltinType *BT = Field->getType()->getAsBuiltinType(); 231 if (!BT) 232 return QualType(); 233 234 if (BT->getKind() != BuiltinType::Bool && 235 BT->getKind() != BuiltinType::Int && 236 BT->getKind() != BuiltinType::UInt) 237 return QualType(); 238 239 llvm::APSInt BitWidthAP; 240 if (!Field->getBitWidth()->isIntegerConstantExpr(BitWidthAP, Context)) 241 return QualType(); 242 243 uint64_t BitWidth = BitWidthAP.getZExtValue(); 244 uint64_t IntSize = Context.getTypeSize(Context.IntTy); 245 if (BitWidth < IntSize || 246 (Field->getType()->isSignedIntegerType() && BitWidth == IntSize)) 247 return Context.IntTy; 248 249 if (BitWidth == IntSize && Field->getType()->isUnsignedIntegerType()) 250 return Context.UnsignedIntTy; 251 252 return QualType(); 253 } 254 255 /// UsualUnaryConversions - Performs various conversions that are common to most 256 /// operators (C99 6.3). The conversions of array and function types are 257 /// sometimes surpressed. For example, the array->pointer conversion doesn't 258 /// apply if the array is an argument to the sizeof or address (&) operators. 259 /// In these instances, this routine should *not* be called. 260 Expr *Sema::UsualUnaryConversions(Expr *&Expr) { 261 QualType Ty = Expr->getType(); 262 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 263 264 // C99 6.3.1.1p2: 265 // 266 // The following may be used in an expression wherever an int or 267 // unsigned int may be used: 268 // - an object or expression with an integer type whose integer 269 // conversion rank is less than or equal to the rank of int 270 // and unsigned int. 271 // - A bit-field of type _Bool, int, signed int, or unsigned int. 272 // 273 // If an int can represent all values of the original type, the 274 // value is converted to an int; otherwise, it is converted to an 275 // unsigned int. These are called the integer promotions. All 276 // other types are unchanged by the integer promotions. 277 if (Ty->isPromotableIntegerType()) { 278 ImpCastExprToType(Expr, Context.IntTy); 279 return Expr; 280 } else { 281 QualType T = isPromotableBitField(Expr, Context); 282 if (!T.isNull()) { 283 ImpCastExprToType(Expr, T); 284 return Expr; 285 } 286 } 287 288 DefaultFunctionArrayConversion(Expr); 289 return Expr; 290 } 291 292 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 293 /// do not have a prototype. Arguments that have type float are promoted to 294 /// double. All other argument types are converted by UsualUnaryConversions(). 295 void Sema::DefaultArgumentPromotion(Expr *&Expr) { 296 QualType Ty = Expr->getType(); 297 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 298 299 // If this is a 'float' (CVR qualified or typedef) promote to double. 300 if (const BuiltinType *BT = Ty->getAsBuiltinType()) 301 if (BT->getKind() == BuiltinType::Float) 302 return ImpCastExprToType(Expr, Context.DoubleTy); 303 304 UsualUnaryConversions(Expr); 305 } 306 307 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 308 /// will warn if the resulting type is not a POD type, and rejects ObjC 309 /// interfaces passed by value. This returns true if the argument type is 310 /// completely illegal. 311 bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) { 312 DefaultArgumentPromotion(Expr); 313 314 if (Expr->getType()->isObjCInterfaceType()) { 315 Diag(Expr->getLocStart(), 316 diag::err_cannot_pass_objc_interface_to_vararg) 317 << Expr->getType() << CT; 318 return true; 319 } 320 321 if (!Expr->getType()->isPODType()) 322 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg) 323 << Expr->getType() << CT; 324 325 return false; 326 } 327 328 329 /// UsualArithmeticConversions - Performs various conversions that are common to 330 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 331 /// routine returns the first non-arithmetic type found. The client is 332 /// responsible for emitting appropriate error diagnostics. 333 /// FIXME: verify the conversion rules for "complex int" are consistent with 334 /// GCC. 335 QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr, 336 bool isCompAssign) { 337 if (!isCompAssign) 338 UsualUnaryConversions(lhsExpr); 339 340 UsualUnaryConversions(rhsExpr); 341 342 // For conversion purposes, we ignore any qualifiers. 343 // For example, "const float" and "float" are equivalent. 344 QualType lhs = 345 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType(); 346 QualType rhs = 347 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType(); 348 349 // If both types are identical, no conversion is needed. 350 if (lhs == rhs) 351 return lhs; 352 353 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 354 // The caller can deal with this (e.g. pointer + int). 355 if (!lhs->isArithmeticType() || !rhs->isArithmeticType()) 356 return lhs; 357 358 // Perform bitfield promotions. 359 QualType LHSBitfieldPromoteTy = isPromotableBitField(lhsExpr, Context); 360 if (!LHSBitfieldPromoteTy.isNull()) 361 lhs = LHSBitfieldPromoteTy; 362 QualType RHSBitfieldPromoteTy = isPromotableBitField(rhsExpr, Context); 363 if (!RHSBitfieldPromoteTy.isNull()) 364 rhs = RHSBitfieldPromoteTy; 365 366 QualType destType = UsualArithmeticConversionsType(lhs, rhs); 367 if (!isCompAssign) 368 ImpCastExprToType(lhsExpr, destType); 369 ImpCastExprToType(rhsExpr, destType); 370 return destType; 371 } 372 373 QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) { 374 // Perform the usual unary conversions. We do this early so that 375 // integral promotions to "int" can allow us to exit early, in the 376 // lhs == rhs check. Also, for conversion purposes, we ignore any 377 // qualifiers. For example, "const float" and "float" are 378 // equivalent. 379 if (lhs->isPromotableIntegerType()) 380 lhs = Context.IntTy; 381 else 382 lhs = lhs.getUnqualifiedType(); 383 if (rhs->isPromotableIntegerType()) 384 rhs = Context.IntTy; 385 else 386 rhs = rhs.getUnqualifiedType(); 387 388 // If both types are identical, no conversion is needed. 389 if (lhs == rhs) 390 return lhs; 391 392 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 393 // The caller can deal with this (e.g. pointer + int). 394 if (!lhs->isArithmeticType() || !rhs->isArithmeticType()) 395 return lhs; 396 397 // At this point, we have two different arithmetic types. 398 399 // Handle complex types first (C99 6.3.1.8p1). 400 if (lhs->isComplexType() || rhs->isComplexType()) { 401 // if we have an integer operand, the result is the complex type. 402 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) { 403 // convert the rhs to the lhs complex type. 404 return lhs; 405 } 406 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) { 407 // convert the lhs to the rhs complex type. 408 return rhs; 409 } 410 // This handles complex/complex, complex/float, or float/complex. 411 // When both operands are complex, the shorter operand is converted to the 412 // type of the longer, and that is the type of the result. This corresponds 413 // to what is done when combining two real floating-point operands. 414 // The fun begins when size promotion occur across type domains. 415 // From H&S 6.3.4: When one operand is complex and the other is a real 416 // floating-point type, the less precise type is converted, within it's 417 // real or complex domain, to the precision of the other type. For example, 418 // when combining a "long double" with a "double _Complex", the 419 // "double _Complex" is promoted to "long double _Complex". 420 int result = Context.getFloatingTypeOrder(lhs, rhs); 421 422 if (result > 0) { // The left side is bigger, convert rhs. 423 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs); 424 } else if (result < 0) { // The right side is bigger, convert lhs. 425 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs); 426 } 427 // At this point, lhs and rhs have the same rank/size. Now, make sure the 428 // domains match. This is a requirement for our implementation, C99 429 // does not require this promotion. 430 if (lhs != rhs) { // Domains don't match, we have complex/float mix. 431 if (lhs->isRealFloatingType()) { // handle "double, _Complex double". 432 return rhs; 433 } else { // handle "_Complex double, double". 434 return lhs; 435 } 436 } 437 return lhs; // The domain/size match exactly. 438 } 439 // Now handle "real" floating types (i.e. float, double, long double). 440 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) { 441 // if we have an integer operand, the result is the real floating type. 442 if (rhs->isIntegerType()) { 443 // convert rhs to the lhs floating point type. 444 return lhs; 445 } 446 if (rhs->isComplexIntegerType()) { 447 // convert rhs to the complex floating point type. 448 return Context.getComplexType(lhs); 449 } 450 if (lhs->isIntegerType()) { 451 // convert lhs to the rhs floating point type. 452 return rhs; 453 } 454 if (lhs->isComplexIntegerType()) { 455 // convert lhs to the complex floating point type. 456 return Context.getComplexType(rhs); 457 } 458 // We have two real floating types, float/complex combos were handled above. 459 // Convert the smaller operand to the bigger result. 460 int result = Context.getFloatingTypeOrder(lhs, rhs); 461 if (result > 0) // convert the rhs 462 return lhs; 463 assert(result < 0 && "illegal float comparison"); 464 return rhs; // convert the lhs 465 } 466 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) { 467 // Handle GCC complex int extension. 468 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType(); 469 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType(); 470 471 if (lhsComplexInt && rhsComplexInt) { 472 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(), 473 rhsComplexInt->getElementType()) >= 0) 474 return lhs; // convert the rhs 475 return rhs; 476 } else if (lhsComplexInt && rhs->isIntegerType()) { 477 // convert the rhs to the lhs complex type. 478 return lhs; 479 } else if (rhsComplexInt && lhs->isIntegerType()) { 480 // convert the lhs to the rhs complex type. 481 return rhs; 482 } 483 } 484 // Finally, we have two differing integer types. 485 // The rules for this case are in C99 6.3.1.8 486 int compare = Context.getIntegerTypeOrder(lhs, rhs); 487 bool lhsSigned = lhs->isSignedIntegerType(), 488 rhsSigned = rhs->isSignedIntegerType(); 489 QualType destType; 490 if (lhsSigned == rhsSigned) { 491 // Same signedness; use the higher-ranked type 492 destType = compare >= 0 ? lhs : rhs; 493 } else if (compare != (lhsSigned ? 1 : -1)) { 494 // The unsigned type has greater than or equal rank to the 495 // signed type, so use the unsigned type 496 destType = lhsSigned ? rhs : lhs; 497 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) { 498 // The two types are different widths; if we are here, that 499 // means the signed type is larger than the unsigned type, so 500 // use the signed type. 501 destType = lhsSigned ? lhs : rhs; 502 } else { 503 // The signed type is higher-ranked than the unsigned type, 504 // but isn't actually any bigger (like unsigned int and long 505 // on most 32-bit systems). Use the unsigned type corresponding 506 // to the signed type. 507 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs); 508 } 509 return destType; 510 } 511 512 //===----------------------------------------------------------------------===// 513 // Semantic Analysis for various Expression Types 514 //===----------------------------------------------------------------------===// 515 516 517 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 518 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 519 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 520 /// multiple tokens. However, the common case is that StringToks points to one 521 /// string. 522 /// 523 Action::OwningExprResult 524 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) { 525 assert(NumStringToks && "Must have at least one string!"); 526 527 StringLiteralParser Literal(StringToks, NumStringToks, PP); 528 if (Literal.hadError) 529 return ExprError(); 530 531 llvm::SmallVector<SourceLocation, 4> StringTokLocs; 532 for (unsigned i = 0; i != NumStringToks; ++i) 533 StringTokLocs.push_back(StringToks[i].getLocation()); 534 535 QualType StrTy = Context.CharTy; 536 if (Literal.AnyWide) StrTy = Context.getWCharType(); 537 if (Literal.Pascal) StrTy = Context.UnsignedCharTy; 538 539 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 540 if (getLangOptions().CPlusPlus) 541 StrTy.addConst(); 542 543 // Get an array type for the string, according to C99 6.4.5. This includes 544 // the nul terminator character as well as the string length for pascal 545 // strings. 546 StrTy = Context.getConstantArrayType(StrTy, 547 llvm::APInt(32, Literal.GetNumStringChars()+1), 548 ArrayType::Normal, 0); 549 550 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 551 return Owned(StringLiteral::Create(Context, Literal.GetString(), 552 Literal.GetStringLength(), 553 Literal.AnyWide, StrTy, 554 &StringTokLocs[0], 555 StringTokLocs.size())); 556 } 557 558 /// ShouldSnapshotBlockValueReference - Return true if a reference inside of 559 /// CurBlock to VD should cause it to be snapshotted (as we do for auto 560 /// variables defined outside the block) or false if this is not needed (e.g. 561 /// for values inside the block or for globals). 562 /// 563 /// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records 564 /// up-to-date. 565 /// 566 static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock, 567 ValueDecl *VD) { 568 // If the value is defined inside the block, we couldn't snapshot it even if 569 // we wanted to. 570 if (CurBlock->TheDecl == VD->getDeclContext()) 571 return false; 572 573 // If this is an enum constant or function, it is constant, don't snapshot. 574 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD)) 575 return false; 576 577 // If this is a reference to an extern, static, or global variable, no need to 578 // snapshot it. 579 // FIXME: What about 'const' variables in C++? 580 if (const VarDecl *Var = dyn_cast<VarDecl>(VD)) 581 if (!Var->hasLocalStorage()) 582 return false; 583 584 // Blocks that have these can't be constant. 585 CurBlock->hasBlockDeclRefExprs = true; 586 587 // If we have nested blocks, the decl may be declared in an outer block (in 588 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may 589 // be defined outside all of the current blocks (in which case the blocks do 590 // all get the bit). Walk the nesting chain. 591 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock; 592 NextBlock = NextBlock->PrevBlockInfo) { 593 // If we found the defining block for the variable, don't mark the block as 594 // having a reference outside it. 595 if (NextBlock->TheDecl == VD->getDeclContext()) 596 break; 597 598 // Otherwise, the DeclRef from the inner block causes the outer one to need 599 // a snapshot as well. 600 NextBlock->hasBlockDeclRefExprs = true; 601 } 602 603 return true; 604 } 605 606 607 608 /// ActOnIdentifierExpr - The parser read an identifier in expression context, 609 /// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this 610 /// identifier is used in a function call context. 611 /// SS is only used for a C++ qualified-id (foo::bar) to indicate the 612 /// class or namespace that the identifier must be a member of. 613 Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc, 614 IdentifierInfo &II, 615 bool HasTrailingLParen, 616 const CXXScopeSpec *SS, 617 bool isAddressOfOperand) { 618 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS, 619 isAddressOfOperand); 620 } 621 622 /// BuildDeclRefExpr - Build either a DeclRefExpr or a 623 /// QualifiedDeclRefExpr based on whether or not SS is a 624 /// nested-name-specifier. 625 Sema::OwningExprResult 626 Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc, 627 bool TypeDependent, bool ValueDependent, 628 const CXXScopeSpec *SS) { 629 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) { 630 Diag(Loc, 631 diag::err_auto_variable_cannot_appear_in_own_initializer) 632 << D->getDeclName(); 633 return ExprError(); 634 } 635 636 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 637 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) { 638 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) { 639 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) { 640 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function) 641 << D->getIdentifier() << FD->getDeclName(); 642 Diag(D->getLocation(), diag::note_local_variable_declared_here) 643 << D->getIdentifier(); 644 return ExprError(); 645 } 646 } 647 } 648 } 649 650 MarkDeclarationReferenced(Loc, D); 651 652 Expr *E; 653 if (SS && !SS->isEmpty()) { 654 E = new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent, 655 ValueDependent, SS->getRange(), 656 static_cast<NestedNameSpecifier *>(SS->getScopeRep())); 657 } else 658 E = new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent); 659 660 return Owned(E); 661 } 662 663 /// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or 664 /// variable corresponding to the anonymous union or struct whose type 665 /// is Record. 666 static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context, 667 RecordDecl *Record) { 668 assert(Record->isAnonymousStructOrUnion() && 669 "Record must be an anonymous struct or union!"); 670 671 // FIXME: Once Decls are directly linked together, this will be an O(1) 672 // operation rather than a slow walk through DeclContext's vector (which 673 // itself will be eliminated). DeclGroups might make this even better. 674 DeclContext *Ctx = Record->getDeclContext(); 675 for (DeclContext::decl_iterator D = Ctx->decls_begin(), 676 DEnd = Ctx->decls_end(); 677 D != DEnd; ++D) { 678 if (*D == Record) { 679 // The object for the anonymous struct/union directly 680 // follows its type in the list of declarations. 681 ++D; 682 assert(D != DEnd && "Missing object for anonymous record"); 683 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed"); 684 return *D; 685 } 686 } 687 688 assert(false && "Missing object for anonymous record"); 689 return 0; 690 } 691 692 /// \brief Given a field that represents a member of an anonymous 693 /// struct/union, build the path from that field's context to the 694 /// actual member. 695 /// 696 /// Construct the sequence of field member references we'll have to 697 /// perform to get to the field in the anonymous union/struct. The 698 /// list of members is built from the field outward, so traverse it 699 /// backwards to go from an object in the current context to the field 700 /// we found. 701 /// 702 /// \returns The variable from which the field access should begin, 703 /// for an anonymous struct/union that is not a member of another 704 /// class. Otherwise, returns NULL. 705 VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field, 706 llvm::SmallVectorImpl<FieldDecl *> &Path) { 707 assert(Field->getDeclContext()->isRecord() && 708 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion() 709 && "Field must be stored inside an anonymous struct or union"); 710 711 Path.push_back(Field); 712 VarDecl *BaseObject = 0; 713 DeclContext *Ctx = Field->getDeclContext(); 714 do { 715 RecordDecl *Record = cast<RecordDecl>(Ctx); 716 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record); 717 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject)) 718 Path.push_back(AnonField); 719 else { 720 BaseObject = cast<VarDecl>(AnonObject); 721 break; 722 } 723 Ctx = Ctx->getParent(); 724 } while (Ctx->isRecord() && 725 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()); 726 727 return BaseObject; 728 } 729 730 Sema::OwningExprResult 731 Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc, 732 FieldDecl *Field, 733 Expr *BaseObjectExpr, 734 SourceLocation OpLoc) { 735 llvm::SmallVector<FieldDecl *, 4> AnonFields; 736 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field, 737 AnonFields); 738 739 // Build the expression that refers to the base object, from 740 // which we will build a sequence of member references to each 741 // of the anonymous union objects and, eventually, the field we 742 // found via name lookup. 743 bool BaseObjectIsPointer = false; 744 unsigned ExtraQuals = 0; 745 if (BaseObject) { 746 // BaseObject is an anonymous struct/union variable (and is, 747 // therefore, not part of another non-anonymous record). 748 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context); 749 MarkDeclarationReferenced(Loc, BaseObject); 750 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(), 751 SourceLocation()); 752 ExtraQuals 753 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers(); 754 } else if (BaseObjectExpr) { 755 // The caller provided the base object expression. Determine 756 // whether its a pointer and whether it adds any qualifiers to the 757 // anonymous struct/union fields we're looking into. 758 QualType ObjectType = BaseObjectExpr->getType(); 759 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) { 760 BaseObjectIsPointer = true; 761 ObjectType = ObjectPtr->getPointeeType(); 762 } 763 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers(); 764 } else { 765 // We've found a member of an anonymous struct/union that is 766 // inside a non-anonymous struct/union, so in a well-formed 767 // program our base object expression is "this". 768 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) { 769 if (!MD->isStatic()) { 770 QualType AnonFieldType 771 = Context.getTagDeclType( 772 cast<RecordDecl>(AnonFields.back()->getDeclContext())); 773 QualType ThisType = Context.getTagDeclType(MD->getParent()); 774 if ((Context.getCanonicalType(AnonFieldType) 775 == Context.getCanonicalType(ThisType)) || 776 IsDerivedFrom(ThisType, AnonFieldType)) { 777 // Our base object expression is "this". 778 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(), 779 MD->getThisType(Context)); 780 BaseObjectIsPointer = true; 781 } 782 } else { 783 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method) 784 << Field->getDeclName()); 785 } 786 ExtraQuals = MD->getTypeQualifiers(); 787 } 788 789 if (!BaseObjectExpr) 790 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use) 791 << Field->getDeclName()); 792 } 793 794 // Build the implicit member references to the field of the 795 // anonymous struct/union. 796 Expr *Result = BaseObjectExpr; 797 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator 798 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend(); 799 FI != FIEnd; ++FI) { 800 QualType MemberType = (*FI)->getType(); 801 if (!(*FI)->isMutable()) { 802 unsigned combinedQualifiers 803 = MemberType.getCVRQualifiers() | ExtraQuals; 804 MemberType = MemberType.getQualifiedType(combinedQualifiers); 805 } 806 MarkDeclarationReferenced(Loc, *FI); 807 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI, 808 OpLoc, MemberType); 809 BaseObjectIsPointer = false; 810 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers(); 811 } 812 813 return Owned(Result); 814 } 815 816 /// ActOnDeclarationNameExpr - The parser has read some kind of name 817 /// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine 818 /// performs lookup on that name and returns an expression that refers 819 /// to that name. This routine isn't directly called from the parser, 820 /// because the parser doesn't know about DeclarationName. Rather, 821 /// this routine is called by ActOnIdentifierExpr, 822 /// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr, 823 /// which form the DeclarationName from the corresponding syntactic 824 /// forms. 825 /// 826 /// HasTrailingLParen indicates whether this identifier is used in a 827 /// function call context. LookupCtx is only used for a C++ 828 /// qualified-id (foo::bar) to indicate the class or namespace that 829 /// the identifier must be a member of. 830 /// 831 /// isAddressOfOperand means that this expression is the direct operand 832 /// of an address-of operator. This matters because this is the only 833 /// situation where a qualified name referencing a non-static member may 834 /// appear outside a member function of this class. 835 Sema::OwningExprResult 836 Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc, 837 DeclarationName Name, bool HasTrailingLParen, 838 const CXXScopeSpec *SS, 839 bool isAddressOfOperand) { 840 // Could be enum-constant, value decl, instance variable, etc. 841 if (SS && SS->isInvalid()) 842 return ExprError(); 843 844 // C++ [temp.dep.expr]p3: 845 // An id-expression is type-dependent if it contains: 846 // -- a nested-name-specifier that contains a class-name that 847 // names a dependent type. 848 // FIXME: Member of the current instantiation. 849 if (SS && isDependentScopeSpecifier(*SS)) { 850 return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy, 851 Loc, SS->getRange(), 852 static_cast<NestedNameSpecifier *>(SS->getScopeRep()), 853 isAddressOfOperand)); 854 } 855 856 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName, 857 false, true, Loc); 858 859 if (Lookup.isAmbiguous()) { 860 DiagnoseAmbiguousLookup(Lookup, Name, Loc, 861 SS && SS->isSet() ? SS->getRange() 862 : SourceRange()); 863 return ExprError(); 864 } 865 866 NamedDecl *D = Lookup.getAsDecl(); 867 868 // If this reference is in an Objective-C method, then ivar lookup happens as 869 // well. 870 IdentifierInfo *II = Name.getAsIdentifierInfo(); 871 if (II && getCurMethodDecl()) { 872 // There are two cases to handle here. 1) scoped lookup could have failed, 873 // in which case we should look for an ivar. 2) scoped lookup could have 874 // found a decl, but that decl is outside the current instance method (i.e. 875 // a global variable). In these two cases, we do a lookup for an ivar with 876 // this name, if the lookup sucedes, we replace it our current decl. 877 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) { 878 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface(); 879 ObjCInterfaceDecl *ClassDeclared; 880 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 881 // Check if referencing a field with __attribute__((deprecated)). 882 if (DiagnoseUseOfDecl(IV, Loc)) 883 return ExprError(); 884 885 // If we're referencing an invalid decl, just return this as a silent 886 // error node. The error diagnostic was already emitted on the decl. 887 if (IV->isInvalidDecl()) 888 return ExprError(); 889 890 bool IsClsMethod = getCurMethodDecl()->isClassMethod(); 891 // If a class method attemps to use a free standing ivar, this is 892 // an error. 893 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod()) 894 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 895 << IV->getDeclName()); 896 // If a class method uses a global variable, even if an ivar with 897 // same name exists, use the global. 898 if (!IsClsMethod) { 899 if (IV->getAccessControl() == ObjCIvarDecl::Private && 900 ClassDeclared != IFace) 901 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 902 // FIXME: This should use a new expr for a direct reference, don't 903 // turn this into Self->ivar, just return a BareIVarExpr or something. 904 IdentifierInfo &II = Context.Idents.get("self"); 905 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false); 906 MarkDeclarationReferenced(Loc, IV); 907 return Owned(new (Context) 908 ObjCIvarRefExpr(IV, IV->getType(), Loc, 909 SelfExpr.takeAs<Expr>(), true, true)); 910 } 911 } 912 } 913 else if (getCurMethodDecl()->isInstanceMethod()) { 914 // We should warn if a local variable hides an ivar. 915 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface(); 916 ObjCInterfaceDecl *ClassDeclared; 917 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 918 if (IV->getAccessControl() != ObjCIvarDecl::Private || 919 IFace == ClassDeclared) 920 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 921 } 922 } 923 // Needed to implement property "super.method" notation. 924 if (D == 0 && II->isStr("super")) { 925 QualType T; 926 927 if (getCurMethodDecl()->isInstanceMethod()) 928 T = Context.getPointerType(Context.getObjCInterfaceType( 929 getCurMethodDecl()->getClassInterface())); 930 else 931 T = Context.getObjCClassType(); 932 return Owned(new (Context) ObjCSuperExpr(Loc, T)); 933 } 934 } 935 936 // Determine whether this name might be a candidate for 937 // argument-dependent lookup. 938 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) && 939 HasTrailingLParen; 940 941 if (ADL && D == 0) { 942 // We've seen something of the form 943 // 944 // identifier( 945 // 946 // and we did not find any entity by the name 947 // "identifier". However, this identifier is still subject to 948 // argument-dependent lookup, so keep track of the name. 949 return Owned(new (Context) UnresolvedFunctionNameExpr(Name, 950 Context.OverloadTy, 951 Loc)); 952 } 953 954 if (D == 0) { 955 // Otherwise, this could be an implicitly declared function reference (legal 956 // in C90, extension in C99). 957 if (HasTrailingLParen && II && 958 !getLangOptions().CPlusPlus) // Not in C++. 959 D = ImplicitlyDefineFunction(Loc, *II, S); 960 else { 961 // If this name wasn't predeclared and if this is not a function call, 962 // diagnose the problem. 963 if (SS && !SS->isEmpty()) 964 return ExprError(Diag(Loc, diag::err_typecheck_no_member) 965 << Name << SS->getRange()); 966 else if (Name.getNameKind() == DeclarationName::CXXOperatorName || 967 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) 968 return ExprError(Diag(Loc, diag::err_undeclared_use) 969 << Name.getAsString()); 970 else 971 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name); 972 } 973 } 974 975 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 976 // Warn about constructs like: 977 // if (void *X = foo()) { ... } else { X }. 978 // In the else block, the pointer is always false. 979 980 // FIXME: In a template instantiation, we don't have scope 981 // information to check this property. 982 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) { 983 Scope *CheckS = S; 984 while (CheckS) { 985 if (CheckS->isWithinElse() && 986 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) { 987 if (Var->getType()->isBooleanType()) 988 ExprError(Diag(Loc, diag::warn_value_always_false) 989 << Var->getDeclName()); 990 else 991 ExprError(Diag(Loc, diag::warn_value_always_zero) 992 << Var->getDeclName()); 993 break; 994 } 995 996 // Move up one more control parent to check again. 997 CheckS = CheckS->getControlParent(); 998 if (CheckS) 999 CheckS = CheckS->getParent(); 1000 } 1001 } 1002 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D)) { 1003 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) { 1004 // C99 DR 316 says that, if a function type comes from a 1005 // function definition (without a prototype), that type is only 1006 // used for checking compatibility. Therefore, when referencing 1007 // the function, we pretend that we don't have the full function 1008 // type. 1009 if (DiagnoseUseOfDecl(Func, Loc)) 1010 return ExprError(); 1011 1012 QualType T = Func->getType(); 1013 QualType NoProtoType = T; 1014 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType()) 1015 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType()); 1016 return BuildDeclRefExpr(Func, NoProtoType, Loc, false, false, SS); 1017 } 1018 } 1019 1020 return BuildDeclarationNameExpr(Loc, D, HasTrailingLParen, SS, isAddressOfOperand); 1021 } 1022 1023 /// \brief Complete semantic analysis for a reference to the given declaration. 1024 Sema::OwningExprResult 1025 Sema::BuildDeclarationNameExpr(SourceLocation Loc, NamedDecl *D, 1026 bool HasTrailingLParen, 1027 const CXXScopeSpec *SS, 1028 bool isAddressOfOperand) { 1029 assert(D && "Cannot refer to a NULL declaration"); 1030 DeclarationName Name = D->getDeclName(); 1031 1032 // If this is an expression of the form &Class::member, don't build an 1033 // implicit member ref, because we want a pointer to the member in general, 1034 // not any specific instance's member. 1035 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) { 1036 DeclContext *DC = computeDeclContext(*SS); 1037 if (D && isa<CXXRecordDecl>(DC)) { 1038 QualType DType; 1039 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 1040 DType = FD->getType().getNonReferenceType(); 1041 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 1042 DType = Method->getType(); 1043 } else if (isa<OverloadedFunctionDecl>(D)) { 1044 DType = Context.OverloadTy; 1045 } 1046 // Could be an inner type. That's diagnosed below, so ignore it here. 1047 if (!DType.isNull()) { 1048 // The pointer is type- and value-dependent if it points into something 1049 // dependent. 1050 bool Dependent = DC->isDependentContext(); 1051 return BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS); 1052 } 1053 } 1054 } 1055 1056 // We may have found a field within an anonymous union or struct 1057 // (C++ [class.union]). 1058 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) 1059 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion()) 1060 return BuildAnonymousStructUnionMemberReference(Loc, FD); 1061 1062 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) { 1063 if (!MD->isStatic()) { 1064 // C++ [class.mfct.nonstatic]p2: 1065 // [...] if name lookup (3.4.1) resolves the name in the 1066 // id-expression to a nonstatic nontype member of class X or of 1067 // a base class of X, the id-expression is transformed into a 1068 // class member access expression (5.2.5) using (*this) (9.3.2) 1069 // as the postfix-expression to the left of the '.' operator. 1070 DeclContext *Ctx = 0; 1071 QualType MemberType; 1072 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 1073 Ctx = FD->getDeclContext(); 1074 MemberType = FD->getType(); 1075 1076 if (const ReferenceType *RefType = MemberType->getAsReferenceType()) 1077 MemberType = RefType->getPointeeType(); 1078 else if (!FD->isMutable()) { 1079 unsigned combinedQualifiers 1080 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers(); 1081 MemberType = MemberType.getQualifiedType(combinedQualifiers); 1082 } 1083 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 1084 if (!Method->isStatic()) { 1085 Ctx = Method->getParent(); 1086 MemberType = Method->getType(); 1087 } 1088 } else if (OverloadedFunctionDecl *Ovl 1089 = dyn_cast<OverloadedFunctionDecl>(D)) { 1090 for (OverloadedFunctionDecl::function_iterator 1091 Func = Ovl->function_begin(), 1092 FuncEnd = Ovl->function_end(); 1093 Func != FuncEnd; ++Func) { 1094 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func)) 1095 if (!DMethod->isStatic()) { 1096 Ctx = Ovl->getDeclContext(); 1097 MemberType = Context.OverloadTy; 1098 break; 1099 } 1100 } 1101 } 1102 1103 if (Ctx && Ctx->isRecord()) { 1104 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx)); 1105 QualType ThisType = Context.getTagDeclType(MD->getParent()); 1106 if ((Context.getCanonicalType(CtxType) 1107 == Context.getCanonicalType(ThisType)) || 1108 IsDerivedFrom(ThisType, CtxType)) { 1109 // Build the implicit member access expression. 1110 Expr *This = new (Context) CXXThisExpr(SourceLocation(), 1111 MD->getThisType(Context)); 1112 MarkDeclarationReferenced(Loc, D); 1113 return Owned(new (Context) MemberExpr(This, true, D, 1114 Loc, MemberType)); 1115 } 1116 } 1117 } 1118 } 1119 1120 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 1121 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) { 1122 if (MD->isStatic()) 1123 // "invalid use of member 'x' in static member function" 1124 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method) 1125 << FD->getDeclName()); 1126 } 1127 1128 // Any other ways we could have found the field in a well-formed 1129 // program would have been turned into implicit member expressions 1130 // above. 1131 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use) 1132 << FD->getDeclName()); 1133 } 1134 1135 if (isa<TypedefDecl>(D)) 1136 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name); 1137 if (isa<ObjCInterfaceDecl>(D)) 1138 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name); 1139 if (isa<NamespaceDecl>(D)) 1140 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name); 1141 1142 // Make the DeclRefExpr or BlockDeclRefExpr for the decl. 1143 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D)) 1144 return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc, 1145 false, false, SS); 1146 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 1147 return BuildDeclRefExpr(Template, Context.OverloadTy, Loc, 1148 false, false, SS); 1149 ValueDecl *VD = cast<ValueDecl>(D); 1150 1151 // Check whether this declaration can be used. Note that we suppress 1152 // this check when we're going to perform argument-dependent lookup 1153 // on this function name, because this might not be the function 1154 // that overload resolution actually selects. 1155 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) && 1156 HasTrailingLParen; 1157 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc)) 1158 return ExprError(); 1159 1160 // Only create DeclRefExpr's for valid Decl's. 1161 if (VD->isInvalidDecl()) 1162 return ExprError(); 1163 1164 // If the identifier reference is inside a block, and it refers to a value 1165 // that is outside the block, create a BlockDeclRefExpr instead of a 1166 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when 1167 // the block is formed. 1168 // 1169 // We do not do this for things like enum constants, global variables, etc, 1170 // as they do not get snapshotted. 1171 // 1172 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) { 1173 MarkDeclarationReferenced(Loc, VD); 1174 QualType ExprTy = VD->getType().getNonReferenceType(); 1175 // The BlocksAttr indicates the variable is bound by-reference. 1176 if (VD->getAttr<BlocksAttr>()) 1177 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true)); 1178 // This is to record that a 'const' was actually synthesize and added. 1179 bool constAdded = !ExprTy.isConstQualified(); 1180 // Variable will be bound by-copy, make it const within the closure. 1181 1182 ExprTy.addConst(); 1183 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false, 1184 constAdded)); 1185 } 1186 // If this reference is not in a block or if the referenced variable is 1187 // within the block, create a normal DeclRefExpr. 1188 1189 bool TypeDependent = false; 1190 bool ValueDependent = false; 1191 if (getLangOptions().CPlusPlus) { 1192 // C++ [temp.dep.expr]p3: 1193 // An id-expression is type-dependent if it contains: 1194 // - an identifier that was declared with a dependent type, 1195 if (VD->getType()->isDependentType()) 1196 TypeDependent = true; 1197 // - FIXME: a template-id that is dependent, 1198 // - a conversion-function-id that specifies a dependent type, 1199 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 1200 Name.getCXXNameType()->isDependentType()) 1201 TypeDependent = true; 1202 // - a nested-name-specifier that contains a class-name that 1203 // names a dependent type. 1204 else if (SS && !SS->isEmpty()) { 1205 for (DeclContext *DC = computeDeclContext(*SS); 1206 DC; DC = DC->getParent()) { 1207 // FIXME: could stop early at namespace scope. 1208 if (DC->isRecord()) { 1209 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 1210 if (Context.getTypeDeclType(Record)->isDependentType()) { 1211 TypeDependent = true; 1212 break; 1213 } 1214 } 1215 } 1216 } 1217 1218 // C++ [temp.dep.constexpr]p2: 1219 // 1220 // An identifier is value-dependent if it is: 1221 // - a name declared with a dependent type, 1222 if (TypeDependent) 1223 ValueDependent = true; 1224 // - the name of a non-type template parameter, 1225 else if (isa<NonTypeTemplateParmDecl>(VD)) 1226 ValueDependent = true; 1227 // - a constant with integral or enumeration type and is 1228 // initialized with an expression that is value-dependent 1229 else if (const VarDecl *Dcl = dyn_cast<VarDecl>(VD)) { 1230 if (Dcl->getType().getCVRQualifiers() == QualType::Const && 1231 Dcl->getInit()) { 1232 ValueDependent = Dcl->getInit()->isValueDependent(); 1233 } 1234 } 1235 } 1236 1237 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, 1238 TypeDependent, ValueDependent, SS); 1239 } 1240 1241 Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, 1242 tok::TokenKind Kind) { 1243 PredefinedExpr::IdentType IT; 1244 1245 switch (Kind) { 1246 default: assert(0 && "Unknown simple primary expr!"); 1247 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 1248 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 1249 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 1250 } 1251 1252 // Pre-defined identifiers are of type char[x], where x is the length of the 1253 // string. 1254 unsigned Length; 1255 if (FunctionDecl *FD = getCurFunctionDecl()) 1256 Length = FD->getIdentifier()->getLength(); 1257 else if (ObjCMethodDecl *MD = getCurMethodDecl()) 1258 Length = MD->getSynthesizedMethodSize(); 1259 else { 1260 Diag(Loc, diag::ext_predef_outside_function); 1261 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string. 1262 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0; 1263 } 1264 1265 1266 llvm::APInt LengthI(32, Length + 1); 1267 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const); 1268 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); 1269 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT)); 1270 } 1271 1272 Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) { 1273 llvm::SmallString<16> CharBuffer; 1274 CharBuffer.resize(Tok.getLength()); 1275 const char *ThisTokBegin = &CharBuffer[0]; 1276 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin); 1277 1278 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength, 1279 Tok.getLocation(), PP); 1280 if (Literal.hadError()) 1281 return ExprError(); 1282 1283 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy; 1284 1285 return Owned(new (Context) CharacterLiteral(Literal.getValue(), 1286 Literal.isWide(), 1287 type, Tok.getLocation())); 1288 } 1289 1290 Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) { 1291 // Fast path for a single digit (which is quite common). A single digit 1292 // cannot have a trigraph, escaped newline, radix prefix, or type suffix. 1293 if (Tok.getLength() == 1) { 1294 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 1295 unsigned IntSize = Context.Target.getIntWidth(); 1296 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'), 1297 Context.IntTy, Tok.getLocation())); 1298 } 1299 1300 llvm::SmallString<512> IntegerBuffer; 1301 // Add padding so that NumericLiteralParser can overread by one character. 1302 IntegerBuffer.resize(Tok.getLength()+1); 1303 const char *ThisTokBegin = &IntegerBuffer[0]; 1304 1305 // Get the spelling of the token, which eliminates trigraphs, etc. 1306 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin); 1307 1308 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength, 1309 Tok.getLocation(), PP); 1310 if (Literal.hadError) 1311 return ExprError(); 1312 1313 Expr *Res; 1314 1315 if (Literal.isFloatingLiteral()) { 1316 QualType Ty; 1317 if (Literal.isFloat) 1318 Ty = Context.FloatTy; 1319 else if (!Literal.isLong) 1320 Ty = Context.DoubleTy; 1321 else 1322 Ty = Context.LongDoubleTy; 1323 1324 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty); 1325 1326 // isExact will be set by GetFloatValue(). 1327 bool isExact = false; 1328 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact); 1329 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation()); 1330 1331 } else if (!Literal.isIntegerLiteral()) { 1332 return ExprError(); 1333 } else { 1334 QualType Ty; 1335 1336 // long long is a C99 feature. 1337 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x && 1338 Literal.isLongLong) 1339 Diag(Tok.getLocation(), diag::ext_longlong); 1340 1341 // Get the value in the widest-possible width. 1342 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0); 1343 1344 if (Literal.GetIntegerValue(ResultVal)) { 1345 // If this value didn't fit into uintmax_t, warn and force to ull. 1346 Diag(Tok.getLocation(), diag::warn_integer_too_large); 1347 Ty = Context.UnsignedLongLongTy; 1348 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 1349 "long long is not intmax_t?"); 1350 } else { 1351 // If this value fits into a ULL, try to figure out what else it fits into 1352 // according to the rules of C99 6.4.4.1p5. 1353 1354 // Octal, Hexadecimal, and integers with a U suffix are allowed to 1355 // be an unsigned int. 1356 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 1357 1358 // Check from smallest to largest, picking the smallest type we can. 1359 unsigned Width = 0; 1360 if (!Literal.isLong && !Literal.isLongLong) { 1361 // Are int/unsigned possibilities? 1362 unsigned IntSize = Context.Target.getIntWidth(); 1363 1364 // Does it fit in a unsigned int? 1365 if (ResultVal.isIntN(IntSize)) { 1366 // Does it fit in a signed int? 1367 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 1368 Ty = Context.IntTy; 1369 else if (AllowUnsigned) 1370 Ty = Context.UnsignedIntTy; 1371 Width = IntSize; 1372 } 1373 } 1374 1375 // Are long/unsigned long possibilities? 1376 if (Ty.isNull() && !Literal.isLongLong) { 1377 unsigned LongSize = Context.Target.getLongWidth(); 1378 1379 // Does it fit in a unsigned long? 1380 if (ResultVal.isIntN(LongSize)) { 1381 // Does it fit in a signed long? 1382 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 1383 Ty = Context.LongTy; 1384 else if (AllowUnsigned) 1385 Ty = Context.UnsignedLongTy; 1386 Width = LongSize; 1387 } 1388 } 1389 1390 // Finally, check long long if needed. 1391 if (Ty.isNull()) { 1392 unsigned LongLongSize = Context.Target.getLongLongWidth(); 1393 1394 // Does it fit in a unsigned long long? 1395 if (ResultVal.isIntN(LongLongSize)) { 1396 // Does it fit in a signed long long? 1397 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0) 1398 Ty = Context.LongLongTy; 1399 else if (AllowUnsigned) 1400 Ty = Context.UnsignedLongLongTy; 1401 Width = LongLongSize; 1402 } 1403 } 1404 1405 // If we still couldn't decide a type, we probably have something that 1406 // does not fit in a signed long long, but has no U suffix. 1407 if (Ty.isNull()) { 1408 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed); 1409 Ty = Context.UnsignedLongLongTy; 1410 Width = Context.Target.getLongLongWidth(); 1411 } 1412 1413 if (ResultVal.getBitWidth() != Width) 1414 ResultVal.trunc(Width); 1415 } 1416 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation()); 1417 } 1418 1419 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 1420 if (Literal.isImaginary) 1421 Res = new (Context) ImaginaryLiteral(Res, 1422 Context.getComplexType(Res->getType())); 1423 1424 return Owned(Res); 1425 } 1426 1427 Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L, 1428 SourceLocation R, ExprArg Val) { 1429 Expr *E = Val.takeAs<Expr>(); 1430 assert((E != 0) && "ActOnParenExpr() missing expr"); 1431 return Owned(new (Context) ParenExpr(L, R, E)); 1432 } 1433 1434 /// The UsualUnaryConversions() function is *not* called by this routine. 1435 /// See C99 6.3.2.1p[2-4] for more details. 1436 bool Sema::CheckSizeOfAlignOfOperand(QualType exprType, 1437 SourceLocation OpLoc, 1438 const SourceRange &ExprRange, 1439 bool isSizeof) { 1440 if (exprType->isDependentType()) 1441 return false; 1442 1443 // C99 6.5.3.4p1: 1444 if (isa<FunctionType>(exprType)) { 1445 // alignof(function) is allowed as an extension. 1446 if (isSizeof) 1447 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange; 1448 return false; 1449 } 1450 1451 // Allow sizeof(void)/alignof(void) as an extension. 1452 if (exprType->isVoidType()) { 1453 Diag(OpLoc, diag::ext_sizeof_void_type) 1454 << (isSizeof ? "sizeof" : "__alignof") << ExprRange; 1455 return false; 1456 } 1457 1458 if (RequireCompleteType(OpLoc, exprType, 1459 isSizeof ? diag::err_sizeof_incomplete_type : 1460 diag::err_alignof_incomplete_type, 1461 ExprRange)) 1462 return true; 1463 1464 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode. 1465 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) { 1466 Diag(OpLoc, diag::err_sizeof_nonfragile_interface) 1467 << exprType << isSizeof << ExprRange; 1468 return true; 1469 } 1470 1471 return false; 1472 } 1473 1474 bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc, 1475 const SourceRange &ExprRange) { 1476 E = E->IgnoreParens(); 1477 1478 // alignof decl is always ok. 1479 if (isa<DeclRefExpr>(E)) 1480 return false; 1481 1482 // Cannot know anything else if the expression is dependent. 1483 if (E->isTypeDependent()) 1484 return false; 1485 1486 if (E->getBitField()) { 1487 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange; 1488 return true; 1489 } 1490 1491 // Alignment of a field access is always okay, so long as it isn't a 1492 // bit-field. 1493 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) 1494 if (dyn_cast<FieldDecl>(ME->getMemberDecl())) 1495 return false; 1496 1497 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false); 1498 } 1499 1500 /// \brief Build a sizeof or alignof expression given a type operand. 1501 Action::OwningExprResult 1502 Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc, 1503 bool isSizeOf, SourceRange R) { 1504 if (T.isNull()) 1505 return ExprError(); 1506 1507 if (!T->isDependentType() && 1508 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf)) 1509 return ExprError(); 1510 1511 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 1512 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T, 1513 Context.getSizeType(), OpLoc, 1514 R.getEnd())); 1515 } 1516 1517 /// \brief Build a sizeof or alignof expression given an expression 1518 /// operand. 1519 Action::OwningExprResult 1520 Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc, 1521 bool isSizeOf, SourceRange R) { 1522 // Verify that the operand is valid. 1523 bool isInvalid = false; 1524 if (E->isTypeDependent()) { 1525 // Delay type-checking for type-dependent expressions. 1526 } else if (!isSizeOf) { 1527 isInvalid = CheckAlignOfExpr(E, OpLoc, R); 1528 } else if (E->getBitField()) { // C99 6.5.3.4p1. 1529 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0; 1530 isInvalid = true; 1531 } else { 1532 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true); 1533 } 1534 1535 if (isInvalid) 1536 return ExprError(); 1537 1538 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 1539 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E, 1540 Context.getSizeType(), OpLoc, 1541 R.getEnd())); 1542 } 1543 1544 /// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and 1545 /// the same for @c alignof and @c __alignof 1546 /// Note that the ArgRange is invalid if isType is false. 1547 Action::OwningExprResult 1548 Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType, 1549 void *TyOrEx, const SourceRange &ArgRange) { 1550 // If error parsing type, ignore. 1551 if (TyOrEx == 0) return ExprError(); 1552 1553 if (isType) { 1554 QualType ArgTy = QualType::getFromOpaquePtr(TyOrEx); 1555 return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange); 1556 } 1557 1558 // Get the end location. 1559 Expr *ArgEx = (Expr *)TyOrEx; 1560 Action::OwningExprResult Result 1561 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange()); 1562 1563 if (Result.isInvalid()) 1564 DeleteExpr(ArgEx); 1565 1566 return move(Result); 1567 } 1568 1569 QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) { 1570 if (V->isTypeDependent()) 1571 return Context.DependentTy; 1572 1573 // These operators return the element type of a complex type. 1574 if (const ComplexType *CT = V->getType()->getAsComplexType()) 1575 return CT->getElementType(); 1576 1577 // Otherwise they pass through real integer and floating point types here. 1578 if (V->getType()->isArithmeticType()) 1579 return V->getType(); 1580 1581 // Reject anything else. 1582 Diag(Loc, diag::err_realimag_invalid_type) << V->getType() 1583 << (isReal ? "__real" : "__imag"); 1584 return QualType(); 1585 } 1586 1587 1588 1589 Action::OwningExprResult 1590 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 1591 tok::TokenKind Kind, ExprArg Input) { 1592 Expr *Arg = (Expr *)Input.get(); 1593 1594 UnaryOperator::Opcode Opc; 1595 switch (Kind) { 1596 default: assert(0 && "Unknown unary op!"); 1597 case tok::plusplus: Opc = UnaryOperator::PostInc; break; 1598 case tok::minusminus: Opc = UnaryOperator::PostDec; break; 1599 } 1600 1601 if (getLangOptions().CPlusPlus && 1602 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) { 1603 // Which overloaded operator? 1604 OverloadedOperatorKind OverOp = 1605 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus; 1606 1607 // C++ [over.inc]p1: 1608 // 1609 // [...] If the function is a member function with one 1610 // parameter (which shall be of type int) or a non-member 1611 // function with two parameters (the second of which shall be 1612 // of type int), it defines the postfix increment operator ++ 1613 // for objects of that type. When the postfix increment is 1614 // called as a result of using the ++ operator, the int 1615 // argument will have value zero. 1616 Expr *Args[2] = { 1617 Arg, 1618 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0, 1619 /*isSigned=*/true), Context.IntTy, SourceLocation()) 1620 }; 1621 1622 // Build the candidate set for overloading 1623 OverloadCandidateSet CandidateSet; 1624 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet); 1625 1626 // Perform overload resolution. 1627 OverloadCandidateSet::iterator Best; 1628 switch (BestViableFunction(CandidateSet, OpLoc, Best)) { 1629 case OR_Success: { 1630 // We found a built-in operator or an overloaded operator. 1631 FunctionDecl *FnDecl = Best->Function; 1632 1633 if (FnDecl) { 1634 // We matched an overloaded operator. Build a call to that 1635 // operator. 1636 1637 // Convert the arguments. 1638 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 1639 if (PerformObjectArgumentInitialization(Arg, Method)) 1640 return ExprError(); 1641 } else { 1642 // Convert the arguments. 1643 if (PerformCopyInitialization(Arg, 1644 FnDecl->getParamDecl(0)->getType(), 1645 "passing")) 1646 return ExprError(); 1647 } 1648 1649 // Determine the result type 1650 QualType ResultTy 1651 = FnDecl->getType()->getAsFunctionType()->getResultType(); 1652 ResultTy = ResultTy.getNonReferenceType(); 1653 1654 // Build the actual expression node. 1655 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(), 1656 SourceLocation()); 1657 UsualUnaryConversions(FnExpr); 1658 1659 Input.release(); 1660 Args[0] = Arg; 1661 return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr, 1662 Args, 2, ResultTy, 1663 OpLoc)); 1664 } else { 1665 // We matched a built-in operator. Convert the arguments, then 1666 // break out so that we will build the appropriate built-in 1667 // operator node. 1668 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0], 1669 "passing")) 1670 return ExprError(); 1671 1672 break; 1673 } 1674 } 1675 1676 case OR_No_Viable_Function: 1677 // No viable function; fall through to handling this as a 1678 // built-in operator, which will produce an error message for us. 1679 break; 1680 1681 case OR_Ambiguous: 1682 Diag(OpLoc, diag::err_ovl_ambiguous_oper) 1683 << UnaryOperator::getOpcodeStr(Opc) 1684 << Arg->getSourceRange(); 1685 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 1686 return ExprError(); 1687 1688 case OR_Deleted: 1689 Diag(OpLoc, diag::err_ovl_deleted_oper) 1690 << Best->Function->isDeleted() 1691 << UnaryOperator::getOpcodeStr(Opc) 1692 << Arg->getSourceRange(); 1693 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 1694 return ExprError(); 1695 } 1696 1697 // Either we found no viable overloaded operator or we matched a 1698 // built-in operator. In either case, fall through to trying to 1699 // build a built-in operation. 1700 } 1701 1702 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc, 1703 Opc == UnaryOperator::PostInc); 1704 if (result.isNull()) 1705 return ExprError(); 1706 Input.release(); 1707 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc)); 1708 } 1709 1710 Action::OwningExprResult 1711 Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc, 1712 ExprArg Idx, SourceLocation RLoc) { 1713 Expr *LHSExp = static_cast<Expr*>(Base.get()), 1714 *RHSExp = static_cast<Expr*>(Idx.get()); 1715 1716 if (getLangOptions().CPlusPlus && 1717 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) { 1718 Base.release(); 1719 Idx.release(); 1720 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 1721 Context.DependentTy, RLoc)); 1722 } 1723 1724 if (getLangOptions().CPlusPlus && 1725 (LHSExp->getType()->isRecordType() || 1726 LHSExp->getType()->isEnumeralType() || 1727 RHSExp->getType()->isRecordType() || 1728 RHSExp->getType()->isEnumeralType())) { 1729 // Add the appropriate overloaded operators (C++ [over.match.oper]) 1730 // to the candidate set. 1731 OverloadCandidateSet CandidateSet; 1732 Expr *Args[2] = { LHSExp, RHSExp }; 1733 AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet, 1734 SourceRange(LLoc, RLoc)); 1735 1736 // Perform overload resolution. 1737 OverloadCandidateSet::iterator Best; 1738 switch (BestViableFunction(CandidateSet, LLoc, Best)) { 1739 case OR_Success: { 1740 // We found a built-in operator or an overloaded operator. 1741 FunctionDecl *FnDecl = Best->Function; 1742 1743 if (FnDecl) { 1744 // We matched an overloaded operator. Build a call to that 1745 // operator. 1746 1747 // Convert the arguments. 1748 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 1749 if (PerformObjectArgumentInitialization(LHSExp, Method) || 1750 PerformCopyInitialization(RHSExp, 1751 FnDecl->getParamDecl(0)->getType(), 1752 "passing")) 1753 return ExprError(); 1754 } else { 1755 // Convert the arguments. 1756 if (PerformCopyInitialization(LHSExp, 1757 FnDecl->getParamDecl(0)->getType(), 1758 "passing") || 1759 PerformCopyInitialization(RHSExp, 1760 FnDecl->getParamDecl(1)->getType(), 1761 "passing")) 1762 return ExprError(); 1763 } 1764 1765 // Determine the result type 1766 QualType ResultTy 1767 = FnDecl->getType()->getAsFunctionType()->getResultType(); 1768 ResultTy = ResultTy.getNonReferenceType(); 1769 1770 // Build the actual expression node. 1771 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(), 1772 SourceLocation()); 1773 UsualUnaryConversions(FnExpr); 1774 1775 Base.release(); 1776 Idx.release(); 1777 Args[0] = LHSExp; 1778 Args[1] = RHSExp; 1779 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 1780 FnExpr, Args, 2, 1781 ResultTy, LLoc)); 1782 } else { 1783 // We matched a built-in operator. Convert the arguments, then 1784 // break out so that we will build the appropriate built-in 1785 // operator node. 1786 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0], 1787 "passing") || 1788 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1], 1789 "passing")) 1790 return ExprError(); 1791 1792 break; 1793 } 1794 } 1795 1796 case OR_No_Viable_Function: 1797 // No viable function; fall through to handling this as a 1798 // built-in operator, which will produce an error message for us. 1799 break; 1800 1801 case OR_Ambiguous: 1802 Diag(LLoc, diag::err_ovl_ambiguous_oper) 1803 << "[]" 1804 << LHSExp->getSourceRange() << RHSExp->getSourceRange(); 1805 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 1806 return ExprError(); 1807 1808 case OR_Deleted: 1809 Diag(LLoc, diag::err_ovl_deleted_oper) 1810 << Best->Function->isDeleted() 1811 << "[]" 1812 << LHSExp->getSourceRange() << RHSExp->getSourceRange(); 1813 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 1814 return ExprError(); 1815 } 1816 1817 // Either we found no viable overloaded operator or we matched a 1818 // built-in operator. In either case, fall through to trying to 1819 // build a built-in operation. 1820 } 1821 1822 // Perform default conversions. 1823 DefaultFunctionArrayConversion(LHSExp); 1824 DefaultFunctionArrayConversion(RHSExp); 1825 1826 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 1827 1828 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 1829 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 1830 // in the subscript position. As a result, we need to derive the array base 1831 // and index from the expression types. 1832 Expr *BaseExpr, *IndexExpr; 1833 QualType ResultType; 1834 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 1835 BaseExpr = LHSExp; 1836 IndexExpr = RHSExp; 1837 ResultType = Context.DependentTy; 1838 } else if (const PointerType *PTy = LHSTy->getAsPointerType()) { 1839 BaseExpr = LHSExp; 1840 IndexExpr = RHSExp; 1841 ResultType = PTy->getPointeeType(); 1842 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) { 1843 // Handle the uncommon case of "123[Ptr]". 1844 BaseExpr = RHSExp; 1845 IndexExpr = LHSExp; 1846 ResultType = PTy->getPointeeType(); 1847 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) { 1848 BaseExpr = LHSExp; // vectors: V[123] 1849 IndexExpr = RHSExp; 1850 1851 // FIXME: need to deal with const... 1852 ResultType = VTy->getElementType(); 1853 } else if (LHSTy->isArrayType()) { 1854 // If we see an array that wasn't promoted by 1855 // DefaultFunctionArrayConversion, it must be an array that 1856 // wasn't promoted because of the C90 rule that doesn't 1857 // allow promoting non-lvalue arrays. Warn, then 1858 // force the promotion here. 1859 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 1860 LHSExp->getSourceRange(); 1861 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy)); 1862 LHSTy = LHSExp->getType(); 1863 1864 BaseExpr = LHSExp; 1865 IndexExpr = RHSExp; 1866 ResultType = LHSTy->getAsPointerType()->getPointeeType(); 1867 } else if (RHSTy->isArrayType()) { 1868 // Same as previous, except for 123[f().a] case 1869 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 1870 RHSExp->getSourceRange(); 1871 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy)); 1872 RHSTy = RHSExp->getType(); 1873 1874 BaseExpr = RHSExp; 1875 IndexExpr = LHSExp; 1876 ResultType = RHSTy->getAsPointerType()->getPointeeType(); 1877 } else { 1878 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 1879 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 1880 } 1881 // C99 6.5.2.1p1 1882 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 1883 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 1884 << IndexExpr->getSourceRange()); 1885 1886 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 1887 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 1888 // type. Note that Functions are not objects, and that (in C99 parlance) 1889 // incomplete types are not object types. 1890 if (ResultType->isFunctionType()) { 1891 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 1892 << ResultType << BaseExpr->getSourceRange(); 1893 return ExprError(); 1894 } 1895 1896 if (!ResultType->isDependentType() && 1897 RequireCompleteType(LLoc, ResultType, diag::err_subscript_incomplete_type, 1898 BaseExpr->getSourceRange())) 1899 return ExprError(); 1900 1901 // Diagnose bad cases where we step over interface counts. 1902 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) { 1903 Diag(LLoc, diag::err_subscript_nonfragile_interface) 1904 << ResultType << BaseExpr->getSourceRange(); 1905 return ExprError(); 1906 } 1907 1908 Base.release(); 1909 Idx.release(); 1910 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 1911 ResultType, RLoc)); 1912 } 1913 1914 QualType Sema:: 1915 CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc, 1916 IdentifierInfo &CompName, SourceLocation CompLoc) { 1917 const ExtVectorType *vecType = baseType->getAsExtVectorType(); 1918 1919 // The vector accessor can't exceed the number of elements. 1920 const char *compStr = CompName.getName(); 1921 1922 // This flag determines whether or not the component is one of the four 1923 // special names that indicate a subset of exactly half the elements are 1924 // to be selected. 1925 bool HalvingSwizzle = false; 1926 1927 // This flag determines whether or not CompName has an 's' char prefix, 1928 // indicating that it is a string of hex values to be used as vector indices. 1929 bool HexSwizzle = *compStr == 's' || *compStr == 'S'; 1930 1931 // Check that we've found one of the special components, or that the component 1932 // names must come from the same set. 1933 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") || 1934 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) { 1935 HalvingSwizzle = true; 1936 } else if (vecType->getPointAccessorIdx(*compStr) != -1) { 1937 do 1938 compStr++; 1939 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1); 1940 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) { 1941 do 1942 compStr++; 1943 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1); 1944 } 1945 1946 if (!HalvingSwizzle && *compStr) { 1947 // We didn't get to the end of the string. This means the component names 1948 // didn't come from the same set *or* we encountered an illegal name. 1949 Diag(OpLoc, diag::err_ext_vector_component_name_illegal) 1950 << std::string(compStr,compStr+1) << SourceRange(CompLoc); 1951 return QualType(); 1952 } 1953 1954 // Ensure no component accessor exceeds the width of the vector type it 1955 // operates on. 1956 if (!HalvingSwizzle) { 1957 compStr = CompName.getName(); 1958 1959 if (HexSwizzle) 1960 compStr++; 1961 1962 while (*compStr) { 1963 if (!vecType->isAccessorWithinNumElements(*compStr++)) { 1964 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length) 1965 << baseType << SourceRange(CompLoc); 1966 return QualType(); 1967 } 1968 } 1969 } 1970 1971 // If this is a halving swizzle, verify that the base type has an even 1972 // number of elements. 1973 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) { 1974 Diag(OpLoc, diag::err_ext_vector_component_requires_even) 1975 << baseType << SourceRange(CompLoc); 1976 return QualType(); 1977 } 1978 1979 // The component accessor looks fine - now we need to compute the actual type. 1980 // The vector type is implied by the component accessor. For example, 1981 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc. 1982 // vec4.s0 is a float, vec4.s23 is a vec3, etc. 1983 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2. 1984 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2 1985 : CompName.getLength(); 1986 if (HexSwizzle) 1987 CompSize--; 1988 1989 if (CompSize == 1) 1990 return vecType->getElementType(); 1991 1992 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize); 1993 // Now look up the TypeDefDecl from the vector type. Without this, 1994 // diagostics look bad. We want extended vector types to appear built-in. 1995 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) { 1996 if (ExtVectorDecls[i]->getUnderlyingType() == VT) 1997 return Context.getTypedefType(ExtVectorDecls[i]); 1998 } 1999 return VT; // should never get here (a typedef type should always be found). 2000 } 2001 2002 static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl, 2003 IdentifierInfo &Member, 2004 const Selector &Sel, 2005 ASTContext &Context) { 2006 2007 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(&Member)) 2008 return PD; 2009 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel)) 2010 return OMD; 2011 2012 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(), 2013 E = PDecl->protocol_end(); I != E; ++I) { 2014 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel, 2015 Context)) 2016 return D; 2017 } 2018 return 0; 2019 } 2020 2021 static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy, 2022 IdentifierInfo &Member, 2023 const Selector &Sel, 2024 ASTContext &Context) { 2025 // Check protocols on qualified interfaces. 2026 Decl *GDecl = 0; 2027 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(), 2028 E = QIdTy->qual_end(); I != E; ++I) { 2029 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) { 2030 GDecl = PD; 2031 break; 2032 } 2033 // Also must look for a getter name which uses property syntax. 2034 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) { 2035 GDecl = OMD; 2036 break; 2037 } 2038 } 2039 if (!GDecl) { 2040 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(), 2041 E = QIdTy->qual_end(); I != E; ++I) { 2042 // Search in the protocol-qualifier list of current protocol. 2043 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context); 2044 if (GDecl) 2045 return GDecl; 2046 } 2047 } 2048 return GDecl; 2049 } 2050 2051 /// FindMethodInNestedImplementations - Look up a method in current and 2052 /// all base class implementations. 2053 /// 2054 ObjCMethodDecl *Sema::FindMethodInNestedImplementations( 2055 const ObjCInterfaceDecl *IFace, 2056 const Selector &Sel) { 2057 ObjCMethodDecl *Method = 0; 2058 if (ObjCImplementationDecl *ImpDecl 2059 = LookupObjCImplementation(IFace->getIdentifier())) 2060 Method = ImpDecl->getInstanceMethod(Sel); 2061 2062 if (!Method && IFace->getSuperClass()) 2063 return FindMethodInNestedImplementations(IFace->getSuperClass(), Sel); 2064 return Method; 2065 } 2066 2067 Action::OwningExprResult 2068 Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc, 2069 tok::TokenKind OpKind, SourceLocation MemberLoc, 2070 IdentifierInfo &Member, 2071 DeclPtrTy ObjCImpDecl) { 2072 Expr *BaseExpr = Base.takeAs<Expr>(); 2073 assert(BaseExpr && "no record expression"); 2074 2075 // Perform default conversions. 2076 DefaultFunctionArrayConversion(BaseExpr); 2077 2078 QualType BaseType = BaseExpr->getType(); 2079 assert(!BaseType.isNull() && "no type for member expression"); 2080 2081 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr 2082 // must have pointer type, and the accessed type is the pointee. 2083 if (OpKind == tok::arrow) { 2084 if (BaseType->isDependentType()) 2085 return Owned(new (Context) CXXUnresolvedMemberExpr(Context, 2086 BaseExpr, true, 2087 OpLoc, 2088 DeclarationName(&Member), 2089 MemberLoc)); 2090 else if (const PointerType *PT = BaseType->getAsPointerType()) 2091 BaseType = PT->getPointeeType(); 2092 else if (getLangOptions().CPlusPlus && BaseType->isRecordType()) 2093 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc, 2094 MemberLoc, Member)); 2095 else 2096 return ExprError(Diag(MemberLoc, 2097 diag::err_typecheck_member_reference_arrow) 2098 << BaseType << BaseExpr->getSourceRange()); 2099 } else { 2100 if (BaseType->isDependentType()) { 2101 // Require that the base type isn't a pointer type 2102 // (so we'll report an error for) 2103 // T* t; 2104 // t.f; 2105 // 2106 // In Obj-C++, however, the above expression is valid, since it could be 2107 // accessing the 'f' property if T is an Obj-C interface. The extra check 2108 // allows this, while still reporting an error if T is a struct pointer. 2109 const PointerType *PT = BaseType->getAsPointerType(); 2110 2111 if (!PT || (getLangOptions().ObjC1 && 2112 !PT->getPointeeType()->isRecordType())) 2113 return Owned(new (Context) CXXUnresolvedMemberExpr(Context, 2114 BaseExpr, false, 2115 OpLoc, 2116 DeclarationName(&Member), 2117 MemberLoc)); 2118 } 2119 } 2120 2121 // Handle field access to simple records. This also handles access to fields 2122 // of the ObjC 'id' struct. 2123 if (const RecordType *RTy = BaseType->getAsRecordType()) { 2124 RecordDecl *RDecl = RTy->getDecl(); 2125 if (RequireCompleteType(OpLoc, BaseType, 2126 diag::err_typecheck_incomplete_tag, 2127 BaseExpr->getSourceRange())) 2128 return ExprError(); 2129 2130 // The record definition is complete, now make sure the member is valid. 2131 // FIXME: Qualified name lookup for C++ is a bit more complicated than this. 2132 LookupResult Result 2133 = LookupQualifiedName(RDecl, DeclarationName(&Member), 2134 LookupMemberName, false); 2135 2136 if (!Result) 2137 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member) 2138 << &Member << BaseExpr->getSourceRange()); 2139 if (Result.isAmbiguous()) { 2140 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member), 2141 MemberLoc, BaseExpr->getSourceRange()); 2142 return ExprError(); 2143 } 2144 2145 NamedDecl *MemberDecl = Result; 2146 2147 // If the decl being referenced had an error, return an error for this 2148 // sub-expr without emitting another error, in order to avoid cascading 2149 // error cases. 2150 if (MemberDecl->isInvalidDecl()) 2151 return ExprError(); 2152 2153 // Check the use of this field 2154 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc)) 2155 return ExprError(); 2156 2157 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) { 2158 // We may have found a field within an anonymous union or struct 2159 // (C++ [class.union]). 2160 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion()) 2161 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD, 2162 BaseExpr, OpLoc); 2163 2164 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref] 2165 // FIXME: Handle address space modifiers 2166 QualType MemberType = FD->getType(); 2167 if (const ReferenceType *Ref = MemberType->getAsReferenceType()) 2168 MemberType = Ref->getPointeeType(); 2169 else { 2170 unsigned combinedQualifiers = 2171 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers(); 2172 if (FD->isMutable()) 2173 combinedQualifiers &= ~QualType::Const; 2174 MemberType = MemberType.getQualifiedType(combinedQualifiers); 2175 } 2176 2177 MarkDeclarationReferenced(MemberLoc, FD); 2178 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD, 2179 MemberLoc, MemberType)); 2180 } 2181 2182 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) { 2183 MarkDeclarationReferenced(MemberLoc, MemberDecl); 2184 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, 2185 Var, MemberLoc, 2186 Var->getType().getNonReferenceType())); 2187 } 2188 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) { 2189 MarkDeclarationReferenced(MemberLoc, MemberDecl); 2190 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, 2191 MemberFn, MemberLoc, 2192 MemberFn->getType())); 2193 } 2194 if (OverloadedFunctionDecl *Ovl 2195 = dyn_cast<OverloadedFunctionDecl>(MemberDecl)) 2196 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl, 2197 MemberLoc, Context.OverloadTy)); 2198 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) { 2199 MarkDeclarationReferenced(MemberLoc, MemberDecl); 2200 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, 2201 Enum, MemberLoc, Enum->getType())); 2202 } 2203 if (isa<TypeDecl>(MemberDecl)) 2204 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type) 2205 << DeclarationName(&Member) << int(OpKind == tok::arrow)); 2206 2207 // We found a declaration kind that we didn't expect. This is a 2208 // generic error message that tells the user that she can't refer 2209 // to this member with '.' or '->'. 2210 return ExprError(Diag(MemberLoc, 2211 diag::err_typecheck_member_reference_unknown) 2212 << DeclarationName(&Member) << int(OpKind == tok::arrow)); 2213 } 2214 2215 // Handle access to Objective-C instance variables, such as "Obj->ivar" and 2216 // (*Obj).ivar. 2217 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) { 2218 ObjCInterfaceDecl *ClassDeclared; 2219 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member, 2220 ClassDeclared)) { 2221 // If the decl being referenced had an error, return an error for this 2222 // sub-expr without emitting another error, in order to avoid cascading 2223 // error cases. 2224 if (IV->isInvalidDecl()) 2225 return ExprError(); 2226 2227 // Check whether we can reference this field. 2228 if (DiagnoseUseOfDecl(IV, MemberLoc)) 2229 return ExprError(); 2230 if (IV->getAccessControl() != ObjCIvarDecl::Public && 2231 IV->getAccessControl() != ObjCIvarDecl::Package) { 2232 ObjCInterfaceDecl *ClassOfMethodDecl = 0; 2233 if (ObjCMethodDecl *MD = getCurMethodDecl()) 2234 ClassOfMethodDecl = MD->getClassInterface(); 2235 else if (ObjCImpDecl && getCurFunctionDecl()) { 2236 // Case of a c-function declared inside an objc implementation. 2237 // FIXME: For a c-style function nested inside an objc implementation 2238 // class, there is no implementation context available, so we pass 2239 // down the context as argument to this routine. Ideally, this context 2240 // need be passed down in the AST node and somehow calculated from the 2241 // AST for a function decl. 2242 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>(); 2243 if (ObjCImplementationDecl *IMPD = 2244 dyn_cast<ObjCImplementationDecl>(ImplDecl)) 2245 ClassOfMethodDecl = IMPD->getClassInterface(); 2246 else if (ObjCCategoryImplDecl* CatImplClass = 2247 dyn_cast<ObjCCategoryImplDecl>(ImplDecl)) 2248 ClassOfMethodDecl = CatImplClass->getClassInterface(); 2249 } 2250 2251 if (IV->getAccessControl() == ObjCIvarDecl::Private) { 2252 if (ClassDeclared != IFTy->getDecl() || 2253 ClassOfMethodDecl != ClassDeclared) 2254 Diag(MemberLoc, diag::error_private_ivar_access) << IV->getDeclName(); 2255 } 2256 // @protected 2257 else if (!IFTy->getDecl()->isSuperClassOf(ClassOfMethodDecl)) 2258 Diag(MemberLoc, diag::error_protected_ivar_access) << IV->getDeclName(); 2259 } 2260 2261 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(), 2262 MemberLoc, BaseExpr, 2263 OpKind == tok::arrow)); 2264 } 2265 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar) 2266 << IFTy->getDecl()->getDeclName() << &Member 2267 << BaseExpr->getSourceRange()); 2268 } 2269 2270 // Handle Objective-C property access, which is "Obj.property" where Obj is a 2271 // pointer to a (potentially qualified) interface type. 2272 const PointerType *PTy; 2273 const ObjCInterfaceType *IFTy; 2274 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) && 2275 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) { 2276 ObjCInterfaceDecl *IFace = IFTy->getDecl(); 2277 2278 // Search for a declared property first. 2279 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) { 2280 // Check whether we can reference this property. 2281 if (DiagnoseUseOfDecl(PD, MemberLoc)) 2282 return ExprError(); 2283 QualType ResTy = PD->getType(); 2284 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member); 2285 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel); 2286 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc)) 2287 ResTy = Getter->getResultType(); 2288 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy, 2289 MemberLoc, BaseExpr)); 2290 } 2291 2292 // Check protocols on qualified interfaces. 2293 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(), 2294 E = IFTy->qual_end(); I != E; ++I) 2295 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) { 2296 // Check whether we can reference this property. 2297 if (DiagnoseUseOfDecl(PD, MemberLoc)) 2298 return ExprError(); 2299 2300 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(), 2301 MemberLoc, BaseExpr)); 2302 } 2303 2304 // If that failed, look for an "implicit" property by seeing if the nullary 2305 // selector is implemented. 2306 2307 // FIXME: The logic for looking up nullary and unary selectors should be 2308 // shared with the code in ActOnInstanceMessage. 2309 2310 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member); 2311 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel); 2312 2313 // If this reference is in an @implementation, check for 'private' methods. 2314 if (!Getter) 2315 Getter = FindMethodInNestedImplementations(IFace, Sel); 2316 2317 // Look through local category implementations associated with the class. 2318 if (!Getter) { 2319 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) { 2320 if (ObjCCategoryImpls[i]->getClassInterface() == IFace) 2321 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel); 2322 } 2323 } 2324 if (Getter) { 2325 // Check if we can reference this property. 2326 if (DiagnoseUseOfDecl(Getter, MemberLoc)) 2327 return ExprError(); 2328 } 2329 // If we found a getter then this may be a valid dot-reference, we 2330 // will look for the matching setter, in case it is needed. 2331 Selector SetterSel = 2332 SelectorTable::constructSetterName(PP.getIdentifierTable(), 2333 PP.getSelectorTable(), &Member); 2334 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel); 2335 if (!Setter) { 2336 // If this reference is in an @implementation, also check for 'private' 2337 // methods. 2338 Setter = FindMethodInNestedImplementations(IFace, SetterSel); 2339 } 2340 // Look through local category implementations associated with the class. 2341 if (!Setter) { 2342 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) { 2343 if (ObjCCategoryImpls[i]->getClassInterface() == IFace) 2344 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel); 2345 } 2346 } 2347 2348 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc)) 2349 return ExprError(); 2350 2351 if (Getter || Setter) { 2352 QualType PType; 2353 2354 if (Getter) 2355 PType = Getter->getResultType(); 2356 else { 2357 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(), 2358 E = Setter->param_end(); PI != E; ++PI) 2359 PType = (*PI)->getType(); 2360 } 2361 // FIXME: we must check that the setter has property type. 2362 return Owned(new (Context) ObjCKVCRefExpr(Getter, PType, 2363 Setter, MemberLoc, BaseExpr)); 2364 } 2365 return ExprError(Diag(MemberLoc, diag::err_property_not_found) 2366 << &Member << BaseType); 2367 } 2368 // Handle properties on qualified "id" protocols. 2369 const ObjCObjectPointerType *QIdTy; 2370 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) { 2371 // Check protocols on qualified interfaces. 2372 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member); 2373 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) { 2374 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) { 2375 // Check the use of this declaration 2376 if (DiagnoseUseOfDecl(PD, MemberLoc)) 2377 return ExprError(); 2378 2379 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(), 2380 MemberLoc, BaseExpr)); 2381 } 2382 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) { 2383 // Check the use of this method. 2384 if (DiagnoseUseOfDecl(OMD, MemberLoc)) 2385 return ExprError(); 2386 2387 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel, 2388 OMD->getResultType(), 2389 OMD, OpLoc, MemberLoc, 2390 NULL, 0)); 2391 } 2392 } 2393 2394 return ExprError(Diag(MemberLoc, diag::err_property_not_found) 2395 << &Member << BaseType); 2396 } 2397 // Handle properties on ObjC 'Class' types. 2398 if (OpKind == tok::period && (BaseType == Context.getObjCClassType())) { 2399 // Also must look for a getter name which uses property syntax. 2400 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member); 2401 if (ObjCMethodDecl *MD = getCurMethodDecl()) { 2402 ObjCInterfaceDecl *IFace = MD->getClassInterface(); 2403 ObjCMethodDecl *Getter; 2404 // FIXME: need to also look locally in the implementation. 2405 if ((Getter = IFace->lookupClassMethod(Sel))) { 2406 // Check the use of this method. 2407 if (DiagnoseUseOfDecl(Getter, MemberLoc)) 2408 return ExprError(); 2409 } 2410 // If we found a getter then this may be a valid dot-reference, we 2411 // will look for the matching setter, in case it is needed. 2412 Selector SetterSel = 2413 SelectorTable::constructSetterName(PP.getIdentifierTable(), 2414 PP.getSelectorTable(), &Member); 2415 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel); 2416 if (!Setter) { 2417 // If this reference is in an @implementation, also check for 'private' 2418 // methods. 2419 Setter = FindMethodInNestedImplementations(IFace, SetterSel); 2420 } 2421 // Look through local category implementations associated with the class. 2422 if (!Setter) { 2423 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) { 2424 if (ObjCCategoryImpls[i]->getClassInterface() == IFace) 2425 Setter = ObjCCategoryImpls[i]->getClassMethod(SetterSel); 2426 } 2427 } 2428 2429 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc)) 2430 return ExprError(); 2431 2432 if (Getter || Setter) { 2433 QualType PType; 2434 2435 if (Getter) 2436 PType = Getter->getResultType(); 2437 else { 2438 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(), 2439 E = Setter->param_end(); PI != E; ++PI) 2440 PType = (*PI)->getType(); 2441 } 2442 // FIXME: we must check that the setter has property type. 2443 return Owned(new (Context) ObjCKVCRefExpr(Getter, PType, 2444 Setter, MemberLoc, BaseExpr)); 2445 } 2446 return ExprError(Diag(MemberLoc, diag::err_property_not_found) 2447 << &Member << BaseType); 2448 } 2449 } 2450 2451 // Handle 'field access' to vectors, such as 'V.xx'. 2452 if (BaseType->isExtVectorType()) { 2453 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc); 2454 if (ret.isNull()) 2455 return ExprError(); 2456 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member, 2457 MemberLoc)); 2458 } 2459 2460 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union) 2461 << BaseType << BaseExpr->getSourceRange(); 2462 2463 // If the user is trying to apply -> or . to a function or function 2464 // pointer, it's probably because they forgot parentheses to call 2465 // the function. Suggest the addition of those parentheses. 2466 if (BaseType == Context.OverloadTy || 2467 BaseType->isFunctionType() || 2468 (BaseType->isPointerType() && 2469 BaseType->getAsPointerType()->isFunctionType())) { 2470 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd()); 2471 Diag(Loc, diag::note_member_reference_needs_call) 2472 << CodeModificationHint::CreateInsertion(Loc, "()"); 2473 } 2474 2475 return ExprError(); 2476 } 2477 2478 /// ConvertArgumentsForCall - Converts the arguments specified in 2479 /// Args/NumArgs to the parameter types of the function FDecl with 2480 /// function prototype Proto. Call is the call expression itself, and 2481 /// Fn is the function expression. For a C++ member function, this 2482 /// routine does not attempt to convert the object argument. Returns 2483 /// true if the call is ill-formed. 2484 bool 2485 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 2486 FunctionDecl *FDecl, 2487 const FunctionProtoType *Proto, 2488 Expr **Args, unsigned NumArgs, 2489 SourceLocation RParenLoc) { 2490 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 2491 // assignment, to the types of the corresponding parameter, ... 2492 unsigned NumArgsInProto = Proto->getNumArgs(); 2493 unsigned NumArgsToCheck = NumArgs; 2494 bool Invalid = false; 2495 2496 // If too few arguments are available (and we don't have default 2497 // arguments for the remaining parameters), don't make the call. 2498 if (NumArgs < NumArgsInProto) { 2499 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments()) 2500 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args) 2501 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange(); 2502 // Use default arguments for missing arguments 2503 NumArgsToCheck = NumArgsInProto; 2504 Call->setNumArgs(Context, NumArgsInProto); 2505 } 2506 2507 // If too many are passed and not variadic, error on the extras and drop 2508 // them. 2509 if (NumArgs > NumArgsInProto) { 2510 if (!Proto->isVariadic()) { 2511 Diag(Args[NumArgsInProto]->getLocStart(), 2512 diag::err_typecheck_call_too_many_args) 2513 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange() 2514 << SourceRange(Args[NumArgsInProto]->getLocStart(), 2515 Args[NumArgs-1]->getLocEnd()); 2516 // This deletes the extra arguments. 2517 Call->setNumArgs(Context, NumArgsInProto); 2518 Invalid = true; 2519 } 2520 NumArgsToCheck = NumArgsInProto; 2521 } 2522 2523 // Continue to check argument types (even if we have too few/many args). 2524 for (unsigned i = 0; i != NumArgsToCheck; i++) { 2525 QualType ProtoArgType = Proto->getArgType(i); 2526 2527 Expr *Arg; 2528 if (i < NumArgs) { 2529 Arg = Args[i]; 2530 2531 if (RequireCompleteType(Arg->getSourceRange().getBegin(), 2532 ProtoArgType, 2533 diag::err_call_incomplete_argument, 2534 Arg->getSourceRange())) 2535 return true; 2536 2537 // Pass the argument. 2538 if (PerformCopyInitialization(Arg, ProtoArgType, "passing")) 2539 return true; 2540 } else { 2541 if (FDecl->getParamDecl(i)->hasUnparsedDefaultArg()) { 2542 Diag (Call->getSourceRange().getBegin(), 2543 diag::err_use_of_default_argument_to_function_declared_later) << 2544 FDecl << cast<CXXRecordDecl>(FDecl->getDeclContext())->getDeclName(); 2545 Diag(UnparsedDefaultArgLocs[FDecl->getParamDecl(i)], 2546 diag::note_default_argument_declared_here); 2547 } else { 2548 Expr *DefaultExpr = FDecl->getParamDecl(i)->getDefaultArg(); 2549 2550 // If the default expression creates temporaries, we need to 2551 // push them to the current stack of expression temporaries so they'll 2552 // be properly destroyed. 2553 if (CXXExprWithTemporaries *E 2554 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) { 2555 assert(!E->shouldDestroyTemporaries() && 2556 "Can't destroy temporaries in a default argument expr!"); 2557 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I) 2558 ExprTemporaries.push_back(E->getTemporary(I)); 2559 } 2560 } 2561 2562 // We already type-checked the argument, so we know it works. 2563 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i)); 2564 } 2565 2566 QualType ArgType = Arg->getType(); 2567 2568 Call->setArg(i, Arg); 2569 } 2570 2571 // If this is a variadic call, handle args passed through "...". 2572 if (Proto->isVariadic()) { 2573 VariadicCallType CallType = VariadicFunction; 2574 if (Fn->getType()->isBlockPointerType()) 2575 CallType = VariadicBlock; // Block 2576 else if (isa<MemberExpr>(Fn)) 2577 CallType = VariadicMethod; 2578 2579 // Promote the arguments (C99 6.5.2.2p7). 2580 for (unsigned i = NumArgsInProto; i != NumArgs; i++) { 2581 Expr *Arg = Args[i]; 2582 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType); 2583 Call->setArg(i, Arg); 2584 } 2585 } 2586 2587 return Invalid; 2588 } 2589 2590 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 2591 /// This provides the location of the left/right parens and a list of comma 2592 /// locations. 2593 Action::OwningExprResult 2594 Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc, 2595 MultiExprArg args, 2596 SourceLocation *CommaLocs, SourceLocation RParenLoc) { 2597 unsigned NumArgs = args.size(); 2598 Expr *Fn = fn.takeAs<Expr>(); 2599 Expr **Args = reinterpret_cast<Expr**>(args.release()); 2600 assert(Fn && "no function call expression"); 2601 FunctionDecl *FDecl = NULL; 2602 NamedDecl *NDecl = NULL; 2603 DeclarationName UnqualifiedName; 2604 2605 if (getLangOptions().CPlusPlus) { 2606 // Determine whether this is a dependent call inside a C++ template, 2607 // in which case we won't do any semantic analysis now. 2608 // FIXME: Will need to cache the results of name lookup (including ADL) in 2609 // Fn. 2610 bool Dependent = false; 2611 if (Fn->isTypeDependent()) 2612 Dependent = true; 2613 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs)) 2614 Dependent = true; 2615 2616 if (Dependent) 2617 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs, 2618 Context.DependentTy, RParenLoc)); 2619 2620 // Determine whether this is a call to an object (C++ [over.call.object]). 2621 if (Fn->getType()->isRecordType()) 2622 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs, 2623 CommaLocs, RParenLoc)); 2624 2625 // Determine whether this is a call to a member function. 2626 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) { 2627 NamedDecl *MemDecl = MemExpr->getMemberDecl(); 2628 if (isa<OverloadedFunctionDecl>(MemDecl) || 2629 isa<CXXMethodDecl>(MemDecl) || 2630 (isa<FunctionTemplateDecl>(MemDecl) && 2631 isa<CXXMethodDecl>( 2632 cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl()))) 2633 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs, 2634 CommaLocs, RParenLoc)); 2635 } 2636 } 2637 2638 // If we're directly calling a function, get the appropriate declaration. 2639 // Also, in C++, keep track of whether we should perform argument-dependent 2640 // lookup and whether there were any explicitly-specified template arguments. 2641 Expr *FnExpr = Fn; 2642 bool ADL = true; 2643 bool HasExplicitTemplateArgs = 0; 2644 const TemplateArgument *ExplicitTemplateArgs = 0; 2645 unsigned NumExplicitTemplateArgs = 0; 2646 while (true) { 2647 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr)) 2648 FnExpr = IcExpr->getSubExpr(); 2649 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) { 2650 // Parentheses around a function disable ADL 2651 // (C++0x [basic.lookup.argdep]p1). 2652 ADL = false; 2653 FnExpr = PExpr->getSubExpr(); 2654 } else if (isa<UnaryOperator>(FnExpr) && 2655 cast<UnaryOperator>(FnExpr)->getOpcode() 2656 == UnaryOperator::AddrOf) { 2657 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr(); 2658 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) { 2659 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1). 2660 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr); 2661 NDecl = dyn_cast<NamedDecl>(DRExpr->getDecl()); 2662 break; 2663 } else if (UnresolvedFunctionNameExpr *DepName 2664 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) { 2665 UnqualifiedName = DepName->getName(); 2666 break; 2667 } else if (TemplateIdRefExpr *TemplateIdRef 2668 = dyn_cast<TemplateIdRefExpr>(FnExpr)) { 2669 NDecl = TemplateIdRef->getTemplateName().getAsTemplateDecl(); 2670 HasExplicitTemplateArgs = true; 2671 ExplicitTemplateArgs = TemplateIdRef->getTemplateArgs(); 2672 NumExplicitTemplateArgs = TemplateIdRef->getNumTemplateArgs(); 2673 2674 // C++ [temp.arg.explicit]p6: 2675 // [Note: For simple function names, argument dependent lookup (3.4.2) 2676 // applies even when the function name is not visible within the 2677 // scope of the call. This is because the call still has the syntactic 2678 // form of a function call (3.4.1). But when a function template with 2679 // explicit template arguments is used, the call does not have the 2680 // correct syntactic form unless there is a function template with 2681 // that name visible at the point of the call. If no such name is 2682 // visible, the call is not syntactically well-formed and 2683 // argument-dependent lookup does not apply. If some such name is 2684 // visible, argument dependent lookup applies and additional function 2685 // templates may be found in other namespaces. 2686 // 2687 // The summary of this paragraph is that, if we get to this point and the 2688 // template-id was not a qualified name, then argument-dependent lookup 2689 // is still possible. 2690 if (TemplateIdRef->getQualifier()) 2691 ADL = false; 2692 break; 2693 } else { 2694 // Any kind of name that does not refer to a declaration (or 2695 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3). 2696 ADL = false; 2697 break; 2698 } 2699 } 2700 2701 OverloadedFunctionDecl *Ovl = 0; 2702 FunctionTemplateDecl *FunctionTemplate = 0; 2703 if (NDecl) { 2704 FDecl = dyn_cast<FunctionDecl>(NDecl); 2705 if ((FunctionTemplate = dyn_cast<FunctionTemplateDecl>(NDecl))) 2706 FDecl = FunctionTemplate->getTemplatedDecl(); 2707 else 2708 FDecl = dyn_cast<FunctionDecl>(NDecl); 2709 Ovl = dyn_cast<OverloadedFunctionDecl>(NDecl); 2710 } 2711 2712 if (Ovl || FunctionTemplate || 2713 (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) { 2714 // We don't perform ADL for implicit declarations of builtins. 2715 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit()) 2716 ADL = false; 2717 2718 // We don't perform ADL in C. 2719 if (!getLangOptions().CPlusPlus) 2720 ADL = false; 2721 2722 if (Ovl || FunctionTemplate || ADL) { 2723 FDecl = ResolveOverloadedCallFn(Fn, NDecl, UnqualifiedName, 2724 HasExplicitTemplateArgs, 2725 ExplicitTemplateArgs, 2726 NumExplicitTemplateArgs, 2727 LParenLoc, Args, NumArgs, CommaLocs, 2728 RParenLoc, ADL); 2729 if (!FDecl) 2730 return ExprError(); 2731 2732 // Update Fn to refer to the actual function selected. 2733 Expr *NewFn = 0; 2734 if (QualifiedDeclRefExpr *QDRExpr 2735 = dyn_cast<QualifiedDeclRefExpr>(FnExpr)) 2736 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(), 2737 QDRExpr->getLocation(), 2738 false, false, 2739 QDRExpr->getQualifierRange(), 2740 QDRExpr->getQualifier()); 2741 else 2742 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(), 2743 Fn->getSourceRange().getBegin()); 2744 Fn->Destroy(Context); 2745 Fn = NewFn; 2746 } 2747 } 2748 2749 // Promote the function operand. 2750 UsualUnaryConversions(Fn); 2751 2752 // Make the call expr early, before semantic checks. This guarantees cleanup 2753 // of arguments and function on error. 2754 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn, 2755 Args, NumArgs, 2756 Context.BoolTy, 2757 RParenLoc)); 2758 2759 const FunctionType *FuncT; 2760 if (!Fn->getType()->isBlockPointerType()) { 2761 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 2762 // have type pointer to function". 2763 const PointerType *PT = Fn->getType()->getAsPointerType(); 2764 if (PT == 0) 2765 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 2766 << Fn->getType() << Fn->getSourceRange()); 2767 FuncT = PT->getPointeeType()->getAsFunctionType(); 2768 } else { // This is a block call. 2769 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()-> 2770 getAsFunctionType(); 2771 } 2772 if (FuncT == 0) 2773 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 2774 << Fn->getType() << Fn->getSourceRange()); 2775 2776 // Check for a valid return type 2777 if (!FuncT->getResultType()->isVoidType() && 2778 RequireCompleteType(Fn->getSourceRange().getBegin(), 2779 FuncT->getResultType(), 2780 diag::err_call_incomplete_return, 2781 TheCall->getSourceRange())) 2782 return ExprError(); 2783 2784 // We know the result type of the call, set it. 2785 TheCall->setType(FuncT->getResultType().getNonReferenceType()); 2786 2787 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) { 2788 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs, 2789 RParenLoc)) 2790 return ExprError(); 2791 } else { 2792 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 2793 2794 if (FDecl) { 2795 // Check if we have too few/too many template arguments, based 2796 // on our knowledge of the function definition. 2797 const FunctionDecl *Def = 0; 2798 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) { 2799 const FunctionProtoType *Proto = 2800 Def->getType()->getAsFunctionProtoType(); 2801 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) { 2802 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 2803 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange(); 2804 } 2805 } 2806 } 2807 2808 // Promote the arguments (C99 6.5.2.2p6). 2809 for (unsigned i = 0; i != NumArgs; i++) { 2810 Expr *Arg = Args[i]; 2811 DefaultArgumentPromotion(Arg); 2812 if (RequireCompleteType(Arg->getSourceRange().getBegin(), 2813 Arg->getType(), 2814 diag::err_call_incomplete_argument, 2815 Arg->getSourceRange())) 2816 return ExprError(); 2817 TheCall->setArg(i, Arg); 2818 } 2819 } 2820 2821 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 2822 if (!Method->isStatic()) 2823 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 2824 << Fn->getSourceRange()); 2825 2826 // Check for sentinels 2827 if (NDecl) 2828 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs); 2829 // Do special checking on direct calls to functions. 2830 if (FDecl) 2831 return CheckFunctionCall(FDecl, TheCall.take()); 2832 if (NDecl) 2833 return CheckBlockCall(NDecl, TheCall.take()); 2834 2835 return Owned(TheCall.take()); 2836 } 2837 2838 Action::OwningExprResult 2839 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty, 2840 SourceLocation RParenLoc, ExprArg InitExpr) { 2841 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type"); 2842 QualType literalType = QualType::getFromOpaquePtr(Ty); 2843 // FIXME: put back this assert when initializers are worked out. 2844 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 2845 Expr *literalExpr = static_cast<Expr*>(InitExpr.get()); 2846 2847 if (literalType->isArrayType()) { 2848 if (literalType->isVariableArrayType()) 2849 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 2850 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())); 2851 } else if (!literalType->isDependentType() && 2852 RequireCompleteType(LParenLoc, literalType, 2853 diag::err_typecheck_decl_incomplete_type, 2854 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()))) 2855 return ExprError(); 2856 2857 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc, 2858 DeclarationName(), /*FIXME:DirectInit=*/false)) 2859 return ExprError(); 2860 2861 bool isFileScope = getCurFunctionOrMethodDecl() == 0; 2862 if (isFileScope) { // 6.5.2.5p3 2863 if (CheckForConstantInitializer(literalExpr, literalType)) 2864 return ExprError(); 2865 } 2866 InitExpr.release(); 2867 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType, 2868 literalExpr, isFileScope)); 2869 } 2870 2871 Action::OwningExprResult 2872 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist, 2873 SourceLocation RBraceLoc) { 2874 unsigned NumInit = initlist.size(); 2875 Expr **InitList = reinterpret_cast<Expr**>(initlist.release()); 2876 2877 // Semantic analysis for initializers is done by ActOnDeclarator() and 2878 // CheckInitializer() - it requires knowledge of the object being intialized. 2879 2880 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit, 2881 RBraceLoc); 2882 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 2883 return Owned(E); 2884 } 2885 2886 /// CheckCastTypes - Check type constraints for casting between types. 2887 bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) { 2888 UsualUnaryConversions(castExpr); 2889 2890 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression 2891 // type needs to be scalar. 2892 if (castType->isVoidType()) { 2893 // Cast to void allows any expr type. 2894 } else if (castType->isDependentType() || castExpr->isTypeDependent()) { 2895 // We can't check any more until template instantiation time. 2896 } else if (!castType->isScalarType() && !castType->isVectorType()) { 2897 if (Context.getCanonicalType(castType).getUnqualifiedType() == 2898 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) && 2899 (castType->isStructureType() || castType->isUnionType())) { 2900 // GCC struct/union extension: allow cast to self. 2901 // FIXME: Check that the cast destination type is complete. 2902 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar) 2903 << castType << castExpr->getSourceRange(); 2904 } else if (castType->isUnionType()) { 2905 // GCC cast to union extension 2906 RecordDecl *RD = castType->getAsRecordType()->getDecl(); 2907 RecordDecl::field_iterator Field, FieldEnd; 2908 for (Field = RD->field_begin(), FieldEnd = RD->field_end(); 2909 Field != FieldEnd; ++Field) { 2910 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() == 2911 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) { 2912 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union) 2913 << castExpr->getSourceRange(); 2914 break; 2915 } 2916 } 2917 if (Field == FieldEnd) 2918 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type) 2919 << castExpr->getType() << castExpr->getSourceRange(); 2920 } else { 2921 // Reject any other conversions to non-scalar types. 2922 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar) 2923 << castType << castExpr->getSourceRange(); 2924 } 2925 } else if (!castExpr->getType()->isScalarType() && 2926 !castExpr->getType()->isVectorType()) { 2927 return Diag(castExpr->getLocStart(), 2928 diag::err_typecheck_expect_scalar_operand) 2929 << castExpr->getType() << castExpr->getSourceRange(); 2930 } else if (castType->isExtVectorType()) { 2931 if (CheckExtVectorCast(TyR, castType, castExpr->getType())) 2932 return true; 2933 } else if (castType->isVectorType()) { 2934 if (CheckVectorCast(TyR, castType, castExpr->getType())) 2935 return true; 2936 } else if (castExpr->getType()->isVectorType()) { 2937 if (CheckVectorCast(TyR, castExpr->getType(), castType)) 2938 return true; 2939 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) { 2940 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR; 2941 } else if (!castType->isArithmeticType()) { 2942 QualType castExprType = castExpr->getType(); 2943 if (!castExprType->isIntegralType() && castExprType->isArithmeticType()) 2944 return Diag(castExpr->getLocStart(), 2945 diag::err_cast_pointer_from_non_pointer_int) 2946 << castExprType << castExpr->getSourceRange(); 2947 } else if (!castExpr->getType()->isArithmeticType()) { 2948 if (!castType->isIntegralType() && castType->isArithmeticType()) 2949 return Diag(castExpr->getLocStart(), 2950 diag::err_cast_pointer_to_non_pointer_int) 2951 << castType << castExpr->getSourceRange(); 2952 } 2953 if (isa<ObjCSelectorExpr>(castExpr)) 2954 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr); 2955 return false; 2956 } 2957 2958 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) { 2959 assert(VectorTy->isVectorType() && "Not a vector type!"); 2960 2961 if (Ty->isVectorType() || Ty->isIntegerType()) { 2962 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty)) 2963 return Diag(R.getBegin(), 2964 Ty->isVectorType() ? 2965 diag::err_invalid_conversion_between_vectors : 2966 diag::err_invalid_conversion_between_vector_and_integer) 2967 << VectorTy << Ty << R; 2968 } else 2969 return Diag(R.getBegin(), 2970 diag::err_invalid_conversion_between_vector_and_scalar) 2971 << VectorTy << Ty << R; 2972 2973 return false; 2974 } 2975 2976 bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, QualType SrcTy) { 2977 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 2978 2979 // If SrcTy is a VectorType, the total size must match to explicitly cast to 2980 // an ExtVectorType. 2981 if (SrcTy->isVectorType()) { 2982 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) 2983 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 2984 << DestTy << SrcTy << R; 2985 return false; 2986 } 2987 2988 // All non-pointer scalars can be cast to ExtVector type. The appropriate 2989 // conversion will take place first from scalar to elt type, and then 2990 // splat from elt type to vector. 2991 if (SrcTy->isPointerType()) 2992 return Diag(R.getBegin(), 2993 diag::err_invalid_conversion_between_vector_and_scalar) 2994 << DestTy << SrcTy << R; 2995 return false; 2996 } 2997 2998 Action::OwningExprResult 2999 Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty, 3000 SourceLocation RParenLoc, ExprArg Op) { 3001 assert((Ty != 0) && (Op.get() != 0) && 3002 "ActOnCastExpr(): missing type or expr"); 3003 3004 Expr *castExpr = Op.takeAs<Expr>(); 3005 QualType castType = QualType::getFromOpaquePtr(Ty); 3006 3007 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr)) 3008 return ExprError(); 3009 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType, 3010 LParenLoc, RParenLoc)); 3011 } 3012 3013 /// Note that lhs is not null here, even if this is the gnu "x ?: y" extension. 3014 /// In that case, lhs = cond. 3015 /// C99 6.5.15 3016 QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS, 3017 SourceLocation QuestionLoc) { 3018 // C++ is sufficiently different to merit its own checker. 3019 if (getLangOptions().CPlusPlus) 3020 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc); 3021 3022 UsualUnaryConversions(Cond); 3023 UsualUnaryConversions(LHS); 3024 UsualUnaryConversions(RHS); 3025 QualType CondTy = Cond->getType(); 3026 QualType LHSTy = LHS->getType(); 3027 QualType RHSTy = RHS->getType(); 3028 3029 // first, check the condition. 3030 if (!CondTy->isScalarType()) { // C99 6.5.15p2 3031 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) 3032 << CondTy; 3033 return QualType(); 3034 } 3035 3036 // Now check the two expressions. 3037 3038 // If both operands have arithmetic type, do the usual arithmetic conversions 3039 // to find a common type: C99 6.5.15p3,5. 3040 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 3041 UsualArithmeticConversions(LHS, RHS); 3042 return LHS->getType(); 3043 } 3044 3045 // If both operands are the same structure or union type, the result is that 3046 // type. 3047 if (const RecordType *LHSRT = LHSTy->getAsRecordType()) { // C99 6.5.15p3 3048 if (const RecordType *RHSRT = RHSTy->getAsRecordType()) 3049 if (LHSRT->getDecl() == RHSRT->getDecl()) 3050 // "If both the operands have structure or union type, the result has 3051 // that type." This implies that CV qualifiers are dropped. 3052 return LHSTy.getUnqualifiedType(); 3053 // FIXME: Type of conditional expression must be complete in C mode. 3054 } 3055 3056 // C99 6.5.15p5: "If both operands have void type, the result has void type." 3057 // The following || allows only one side to be void (a GCC-ism). 3058 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 3059 if (!LHSTy->isVoidType()) 3060 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void) 3061 << RHS->getSourceRange(); 3062 if (!RHSTy->isVoidType()) 3063 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void) 3064 << LHS->getSourceRange(); 3065 ImpCastExprToType(LHS, Context.VoidTy); 3066 ImpCastExprToType(RHS, Context.VoidTy); 3067 return Context.VoidTy; 3068 } 3069 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 3070 // the type of the other operand." 3071 if ((LHSTy->isPointerType() || LHSTy->isBlockPointerType() || 3072 Context.isObjCObjectPointerType(LHSTy)) && 3073 RHS->isNullPointerConstant(Context)) { 3074 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer. 3075 return LHSTy; 3076 } 3077 if ((RHSTy->isPointerType() || RHSTy->isBlockPointerType() || 3078 Context.isObjCObjectPointerType(RHSTy)) && 3079 LHS->isNullPointerConstant(Context)) { 3080 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer. 3081 return RHSTy; 3082 } 3083 // Handle block pointer types. 3084 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 3085 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 3086 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 3087 QualType destType = Context.getPointerType(Context.VoidTy); 3088 ImpCastExprToType(LHS, destType); 3089 ImpCastExprToType(RHS, destType); 3090 return destType; 3091 } 3092 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 3093 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 3094 return QualType(); 3095 } 3096 // We have 2 block pointer types. 3097 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 3098 // Two identical block pointer types are always compatible. 3099 return LHSTy; 3100 } 3101 // The block pointer types aren't identical, continue checking. 3102 QualType lhptee = LHSTy->getAsBlockPointerType()->getPointeeType(); 3103 QualType rhptee = RHSTy->getAsBlockPointerType()->getPointeeType(); 3104 3105 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(), 3106 rhptee.getUnqualifiedType())) { 3107 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers) 3108 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 3109 // In this situation, we assume void* type. No especially good 3110 // reason, but this is what gcc does, and we do have to pick 3111 // to get a consistent AST. 3112 QualType incompatTy = Context.getPointerType(Context.VoidTy); 3113 ImpCastExprToType(LHS, incompatTy); 3114 ImpCastExprToType(RHS, incompatTy); 3115 return incompatTy; 3116 } 3117 // The block pointer types are compatible. 3118 ImpCastExprToType(LHS, LHSTy); 3119 ImpCastExprToType(RHS, LHSTy); 3120 return LHSTy; 3121 } 3122 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type 3123 // evaluates to "struct objc_object *" (and is handled above when comparing 3124 // id with statically typed objects). 3125 if (LHSTy->isObjCQualifiedIdType() || RHSTy->isObjCQualifiedIdType()) { 3126 // GCC allows qualified id and any Objective-C type to devolve to 3127 // id. Currently localizing to here until clear this should be 3128 // part of ObjCQualifiedIdTypesAreCompatible. 3129 if (ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true) || 3130 (LHSTy->isObjCQualifiedIdType() && 3131 Context.isObjCObjectPointerType(RHSTy)) || 3132 (RHSTy->isObjCQualifiedIdType() && 3133 Context.isObjCObjectPointerType(LHSTy))) { 3134 // FIXME: This is not the correct composite type. This only happens to 3135 // work because id can more or less be used anywhere, however this may 3136 // change the type of method sends. 3137 3138 // FIXME: gcc adds some type-checking of the arguments and emits 3139 // (confusing) incompatible comparison warnings in some 3140 // cases. Investigate. 3141 QualType compositeType = Context.getObjCIdType(); 3142 ImpCastExprToType(LHS, compositeType); 3143 ImpCastExprToType(RHS, compositeType); 3144 return compositeType; 3145 } 3146 } 3147 // Check constraints for Objective-C object pointers types. 3148 if (Context.isObjCObjectPointerType(LHSTy) && 3149 Context.isObjCObjectPointerType(RHSTy)) { 3150 3151 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 3152 // Two identical object pointer types are always compatible. 3153 return LHSTy; 3154 } 3155 // No need to check for block pointer types or qualified id types (they 3156 // were handled above). 3157 assert((LHSTy->isPointerType() && RHSTy->isPointerType()) && 3158 "Sema::CheckConditionalOperands(): Unexpected type"); 3159 QualType lhptee = LHSTy->getAsPointerType()->getPointeeType(); 3160 QualType rhptee = RHSTy->getAsPointerType()->getPointeeType(); 3161 3162 QualType compositeType = LHSTy; 3163 3164 // If both operands are interfaces and either operand can be 3165 // assigned to the other, use that type as the composite 3166 // type. This allows 3167 // xxx ? (A*) a : (B*) b 3168 // where B is a subclass of A. 3169 // 3170 // Additionally, as for assignment, if either type is 'id' 3171 // allow silent coercion. Finally, if the types are 3172 // incompatible then make sure to use 'id' as the composite 3173 // type so the result is acceptable for sending messages to. 3174 3175 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 3176 // It could return the composite type. 3177 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType(); 3178 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType(); 3179 if (LHSIface && RHSIface && 3180 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) { 3181 compositeType = LHSTy; 3182 } else if (LHSIface && RHSIface && 3183 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) { 3184 compositeType = RHSTy; 3185 } else if (Context.isObjCIdStructType(lhptee) || 3186 Context.isObjCIdStructType(rhptee)) { 3187 compositeType = Context.getObjCIdType(); 3188 } else { 3189 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 3190 << LHSTy << RHSTy 3191 << LHS->getSourceRange() << RHS->getSourceRange(); 3192 QualType incompatTy = Context.getObjCIdType(); 3193 ImpCastExprToType(LHS, incompatTy); 3194 ImpCastExprToType(RHS, incompatTy); 3195 return incompatTy; 3196 } 3197 // The object pointer types are compatible. 3198 ImpCastExprToType(LHS, compositeType); 3199 ImpCastExprToType(RHS, compositeType); 3200 return compositeType; 3201 } 3202 // Check constraints for C object pointers types (C99 6.5.15p3,6). 3203 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 3204 // get the "pointed to" types 3205 QualType lhptee = LHSTy->getAsPointerType()->getPointeeType(); 3206 QualType rhptee = RHSTy->getAsPointerType()->getPointeeType(); 3207 3208 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 3209 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 3210 // Figure out necessary qualifiers (C99 6.5.15p6) 3211 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers()); 3212 QualType destType = Context.getPointerType(destPointee); 3213 ImpCastExprToType(LHS, destType); // add qualifiers if necessary 3214 ImpCastExprToType(RHS, destType); // promote to void* 3215 return destType; 3216 } 3217 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 3218 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers()); 3219 QualType destType = Context.getPointerType(destPointee); 3220 ImpCastExprToType(LHS, destType); // add qualifiers if necessary 3221 ImpCastExprToType(RHS, destType); // promote to void* 3222 return destType; 3223 } 3224 3225 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 3226 // Two identical pointer types are always compatible. 3227 return LHSTy; 3228 } 3229 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(), 3230 rhptee.getUnqualifiedType())) { 3231 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers) 3232 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 3233 // In this situation, we assume void* type. No especially good 3234 // reason, but this is what gcc does, and we do have to pick 3235 // to get a consistent AST. 3236 QualType incompatTy = Context.getPointerType(Context.VoidTy); 3237 ImpCastExprToType(LHS, incompatTy); 3238 ImpCastExprToType(RHS, incompatTy); 3239 return incompatTy; 3240 } 3241 // The pointer types are compatible. 3242 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to 3243 // differently qualified versions of compatible types, the result type is 3244 // a pointer to an appropriately qualified version of the *composite* 3245 // type. 3246 // FIXME: Need to calculate the composite type. 3247 // FIXME: Need to add qualifiers 3248 ImpCastExprToType(LHS, LHSTy); 3249 ImpCastExprToType(RHS, LHSTy); 3250 return LHSTy; 3251 } 3252 3253 // GCC compatibility: soften pointer/integer mismatch. 3254 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) { 3255 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch) 3256 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 3257 ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer. 3258 return RHSTy; 3259 } 3260 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) { 3261 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch) 3262 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 3263 ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer. 3264 return LHSTy; 3265 } 3266 3267 // Otherwise, the operands are not compatible. 3268 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 3269 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 3270 return QualType(); 3271 } 3272 3273 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 3274 /// in the case of a the GNU conditional expr extension. 3275 Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 3276 SourceLocation ColonLoc, 3277 ExprArg Cond, ExprArg LHS, 3278 ExprArg RHS) { 3279 Expr *CondExpr = (Expr *) Cond.get(); 3280 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get(); 3281 3282 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 3283 // was the condition. 3284 bool isLHSNull = LHSExpr == 0; 3285 if (isLHSNull) 3286 LHSExpr = CondExpr; 3287 3288 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, 3289 RHSExpr, QuestionLoc); 3290 if (result.isNull()) 3291 return ExprError(); 3292 3293 Cond.release(); 3294 LHS.release(); 3295 RHS.release(); 3296 return Owned(new (Context) ConditionalOperator(CondExpr, 3297 isLHSNull ? 0 : LHSExpr, 3298 RHSExpr, result)); 3299 } 3300 3301 3302 // CheckPointerTypesForAssignment - This is a very tricky routine (despite 3303 // being closely modeled after the C99 spec:-). The odd characteristic of this 3304 // routine is it effectively iqnores the qualifiers on the top level pointee. 3305 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 3306 // FIXME: add a couple examples in this comment. 3307 Sema::AssignConvertType 3308 Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) { 3309 QualType lhptee, rhptee; 3310 3311 // get the "pointed to" type (ignoring qualifiers at the top level) 3312 lhptee = lhsType->getAsPointerType()->getPointeeType(); 3313 rhptee = rhsType->getAsPointerType()->getPointeeType(); 3314 3315 // make sure we operate on the canonical type 3316 lhptee = Context.getCanonicalType(lhptee); 3317 rhptee = Context.getCanonicalType(rhptee); 3318 3319 AssignConvertType ConvTy = Compatible; 3320 3321 // C99 6.5.16.1p1: This following citation is common to constraints 3322 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 3323 // qualifiers of the type *pointed to* by the right; 3324 // FIXME: Handle ExtQualType 3325 if (!lhptee.isAtLeastAsQualifiedAs(rhptee)) 3326 ConvTy = CompatiblePointerDiscardsQualifiers; 3327 3328 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 3329 // incomplete type and the other is a pointer to a qualified or unqualified 3330 // version of void... 3331 if (lhptee->isVoidType()) { 3332 if (rhptee->isIncompleteOrObjectType()) 3333 return ConvTy; 3334 3335 // As an extension, we allow cast to/from void* to function pointer. 3336 assert(rhptee->isFunctionType()); 3337 return FunctionVoidPointer; 3338 } 3339 3340 if (rhptee->isVoidType()) { 3341 if (lhptee->isIncompleteOrObjectType()) 3342 return ConvTy; 3343 3344 // As an extension, we allow cast to/from void* to function pointer. 3345 assert(lhptee->isFunctionType()); 3346 return FunctionVoidPointer; 3347 } 3348 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 3349 // unqualified versions of compatible types, ... 3350 lhptee = lhptee.getUnqualifiedType(); 3351 rhptee = rhptee.getUnqualifiedType(); 3352 if (!Context.typesAreCompatible(lhptee, rhptee)) { 3353 // Check if the pointee types are compatible ignoring the sign. 3354 // We explicitly check for char so that we catch "char" vs 3355 // "unsigned char" on systems where "char" is unsigned. 3356 if (lhptee->isCharType()) { 3357 lhptee = Context.UnsignedCharTy; 3358 } else if (lhptee->isSignedIntegerType()) { 3359 lhptee = Context.getCorrespondingUnsignedType(lhptee); 3360 } 3361 if (rhptee->isCharType()) { 3362 rhptee = Context.UnsignedCharTy; 3363 } else if (rhptee->isSignedIntegerType()) { 3364 rhptee = Context.getCorrespondingUnsignedType(rhptee); 3365 } 3366 if (lhptee == rhptee) { 3367 // Types are compatible ignoring the sign. Qualifier incompatibility 3368 // takes priority over sign incompatibility because the sign 3369 // warning can be disabled. 3370 if (ConvTy != Compatible) 3371 return ConvTy; 3372 return IncompatiblePointerSign; 3373 } 3374 // General pointer incompatibility takes priority over qualifiers. 3375 return IncompatiblePointer; 3376 } 3377 return ConvTy; 3378 } 3379 3380 /// CheckBlockPointerTypesForAssignment - This routine determines whether two 3381 /// block pointer types are compatible or whether a block and normal pointer 3382 /// are compatible. It is more restrict than comparing two function pointer 3383 // types. 3384 Sema::AssignConvertType 3385 Sema::CheckBlockPointerTypesForAssignment(QualType lhsType, 3386 QualType rhsType) { 3387 QualType lhptee, rhptee; 3388 3389 // get the "pointed to" type (ignoring qualifiers at the top level) 3390 lhptee = lhsType->getAsBlockPointerType()->getPointeeType(); 3391 rhptee = rhsType->getAsBlockPointerType()->getPointeeType(); 3392 3393 // make sure we operate on the canonical type 3394 lhptee = Context.getCanonicalType(lhptee); 3395 rhptee = Context.getCanonicalType(rhptee); 3396 3397 AssignConvertType ConvTy = Compatible; 3398 3399 // For blocks we enforce that qualifiers are identical. 3400 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers()) 3401 ConvTy = CompatiblePointerDiscardsQualifiers; 3402 3403 if (!Context.typesAreCompatible(lhptee, rhptee)) 3404 return IncompatibleBlockPointer; 3405 return ConvTy; 3406 } 3407 3408 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 3409 /// has code to accommodate several GCC extensions when type checking 3410 /// pointers. Here are some objectionable examples that GCC considers warnings: 3411 /// 3412 /// int a, *pint; 3413 /// short *pshort; 3414 /// struct foo *pfoo; 3415 /// 3416 /// pint = pshort; // warning: assignment from incompatible pointer type 3417 /// a = pint; // warning: assignment makes integer from pointer without a cast 3418 /// pint = a; // warning: assignment makes pointer from integer without a cast 3419 /// pint = pfoo; // warning: assignment from incompatible pointer type 3420 /// 3421 /// As a result, the code for dealing with pointers is more complex than the 3422 /// C99 spec dictates. 3423 /// 3424 Sema::AssignConvertType 3425 Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) { 3426 // Get canonical types. We're not formatting these types, just comparing 3427 // them. 3428 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType(); 3429 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType(); 3430 3431 if (lhsType == rhsType) 3432 return Compatible; // Common case: fast path an exact match. 3433 3434 // If the left-hand side is a reference type, then we are in a 3435 // (rare!) case where we've allowed the use of references in C, 3436 // e.g., as a parameter type in a built-in function. In this case, 3437 // just make sure that the type referenced is compatible with the 3438 // right-hand side type. The caller is responsible for adjusting 3439 // lhsType so that the resulting expression does not have reference 3440 // type. 3441 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) { 3442 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) 3443 return Compatible; 3444 return Incompatible; 3445 } 3446 3447 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) { 3448 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false)) 3449 return Compatible; 3450 // Relax integer conversions like we do for pointers below. 3451 if (rhsType->isIntegerType()) 3452 return IntToPointer; 3453 if (lhsType->isIntegerType()) 3454 return PointerToInt; 3455 return IncompatibleObjCQualifiedId; 3456 } 3457 3458 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 3459 // to the same ExtVector type. 3460 if (lhsType->isExtVectorType()) { 3461 if (rhsType->isExtVectorType()) 3462 return lhsType == rhsType ? Compatible : Incompatible; 3463 if (!rhsType->isVectorType() && rhsType->isArithmeticType()) 3464 return Compatible; 3465 } 3466 3467 if (lhsType->isVectorType() || rhsType->isVectorType()) { 3468 // If we are allowing lax vector conversions, and LHS and RHS are both 3469 // vectors, the total size only needs to be the same. This is a bitcast; 3470 // no bits are changed but the result type is different. 3471 if (getLangOptions().LaxVectorConversions && 3472 lhsType->isVectorType() && rhsType->isVectorType()) { 3473 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType)) 3474 return IncompatibleVectors; 3475 } 3476 return Incompatible; 3477 } 3478 3479 if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) 3480 return Compatible; 3481 3482 if (isa<PointerType>(lhsType)) { 3483 if (rhsType->isIntegerType()) 3484 return IntToPointer; 3485 3486 if (isa<PointerType>(rhsType)) 3487 return CheckPointerTypesForAssignment(lhsType, rhsType); 3488 3489 if (rhsType->getAsBlockPointerType()) { 3490 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType()) 3491 return Compatible; 3492 3493 // Treat block pointers as objects. 3494 if (getLangOptions().ObjC1 && 3495 lhsType == Context.getCanonicalType(Context.getObjCIdType())) 3496 return Compatible; 3497 } 3498 return Incompatible; 3499 } 3500 3501 if (isa<BlockPointerType>(lhsType)) { 3502 if (rhsType->isIntegerType()) 3503 return IntToBlockPointer; 3504 3505 // Treat block pointers as objects. 3506 if (getLangOptions().ObjC1 && 3507 rhsType == Context.getCanonicalType(Context.getObjCIdType())) 3508 return Compatible; 3509 3510 if (rhsType->isBlockPointerType()) 3511 return CheckBlockPointerTypesForAssignment(lhsType, rhsType); 3512 3513 if (const PointerType *RHSPT = rhsType->getAsPointerType()) { 3514 if (RHSPT->getPointeeType()->isVoidType()) 3515 return Compatible; 3516 } 3517 return Incompatible; 3518 } 3519 3520 if (isa<PointerType>(rhsType)) { 3521 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer. 3522 if (lhsType == Context.BoolTy) 3523 return Compatible; 3524 3525 if (lhsType->isIntegerType()) 3526 return PointerToInt; 3527 3528 if (isa<PointerType>(lhsType)) 3529 return CheckPointerTypesForAssignment(lhsType, rhsType); 3530 3531 if (isa<BlockPointerType>(lhsType) && 3532 rhsType->getAsPointerType()->getPointeeType()->isVoidType()) 3533 return Compatible; 3534 return Incompatible; 3535 } 3536 3537 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) { 3538 if (Context.typesAreCompatible(lhsType, rhsType)) 3539 return Compatible; 3540 } 3541 return Incompatible; 3542 } 3543 3544 /// \brief Constructs a transparent union from an expression that is 3545 /// used to initialize the transparent union. 3546 static void ConstructTransparentUnion(ASTContext &C, Expr *&E, 3547 QualType UnionType, FieldDecl *Field) { 3548 // Build an initializer list that designates the appropriate member 3549 // of the transparent union. 3550 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(), 3551 &E, 1, 3552 SourceLocation()); 3553 Initializer->setType(UnionType); 3554 Initializer->setInitializedFieldInUnion(Field); 3555 3556 // Build a compound literal constructing a value of the transparent 3557 // union type from this initializer list. 3558 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer, 3559 false); 3560 } 3561 3562 Sema::AssignConvertType 3563 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) { 3564 QualType FromType = rExpr->getType(); 3565 3566 // If the ArgType is a Union type, we want to handle a potential 3567 // transparent_union GCC extension. 3568 const RecordType *UT = ArgType->getAsUnionType(); 3569 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 3570 return Incompatible; 3571 3572 // The field to initialize within the transparent union. 3573 RecordDecl *UD = UT->getDecl(); 3574 FieldDecl *InitField = 0; 3575 // It's compatible if the expression matches any of the fields. 3576 for (RecordDecl::field_iterator it = UD->field_begin(), 3577 itend = UD->field_end(); 3578 it != itend; ++it) { 3579 if (it->getType()->isPointerType()) { 3580 // If the transparent union contains a pointer type, we allow: 3581 // 1) void pointer 3582 // 2) null pointer constant 3583 if (FromType->isPointerType()) 3584 if (FromType->getAsPointerType()->getPointeeType()->isVoidType()) { 3585 ImpCastExprToType(rExpr, it->getType()); 3586 InitField = *it; 3587 break; 3588 } 3589 3590 if (rExpr->isNullPointerConstant(Context)) { 3591 ImpCastExprToType(rExpr, it->getType()); 3592 InitField = *it; 3593 break; 3594 } 3595 } 3596 3597 if (CheckAssignmentConstraints(it->getType(), rExpr->getType()) 3598 == Compatible) { 3599 InitField = *it; 3600 break; 3601 } 3602 } 3603 3604 if (!InitField) 3605 return Incompatible; 3606 3607 ConstructTransparentUnion(Context, rExpr, ArgType, InitField); 3608 return Compatible; 3609 } 3610 3611 Sema::AssignConvertType 3612 Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) { 3613 if (getLangOptions().CPlusPlus) { 3614 if (!lhsType->isRecordType()) { 3615 // C++ 5.17p3: If the left operand is not of class type, the 3616 // expression is implicitly converted (C++ 4) to the 3617 // cv-unqualified type of the left operand. 3618 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(), 3619 "assigning")) 3620 return Incompatible; 3621 return Compatible; 3622 } 3623 3624 // FIXME: Currently, we fall through and treat C++ classes like C 3625 // structures. 3626 } 3627 3628 // C99 6.5.16.1p1: the left operand is a pointer and the right is 3629 // a null pointer constant. 3630 if ((lhsType->isPointerType() || 3631 lhsType->isObjCQualifiedIdType() || 3632 lhsType->isBlockPointerType()) 3633 && rExpr->isNullPointerConstant(Context)) { 3634 ImpCastExprToType(rExpr, lhsType); 3635 return Compatible; 3636 } 3637 3638 // This check seems unnatural, however it is necessary to ensure the proper 3639 // conversion of functions/arrays. If the conversion were done for all 3640 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary 3641 // expressions that surpress this implicit conversion (&, sizeof). 3642 // 3643 // Suppress this for references: C++ 8.5.3p5. 3644 if (!lhsType->isReferenceType()) 3645 DefaultFunctionArrayConversion(rExpr); 3646 3647 Sema::AssignConvertType result = 3648 CheckAssignmentConstraints(lhsType, rExpr->getType()); 3649 3650 // C99 6.5.16.1p2: The value of the right operand is converted to the 3651 // type of the assignment expression. 3652 // CheckAssignmentConstraints allows the left-hand side to be a reference, 3653 // so that we can use references in built-in functions even in C. 3654 // The getNonReferenceType() call makes sure that the resulting expression 3655 // does not have reference type. 3656 if (result != Incompatible && rExpr->getType() != lhsType) 3657 ImpCastExprToType(rExpr, lhsType.getNonReferenceType()); 3658 return result; 3659 } 3660 3661 QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) { 3662 Diag(Loc, diag::err_typecheck_invalid_operands) 3663 << lex->getType() << rex->getType() 3664 << lex->getSourceRange() << rex->getSourceRange(); 3665 return QualType(); 3666 } 3667 3668 inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, 3669 Expr *&rex) { 3670 // For conversion purposes, we ignore any qualifiers. 3671 // For example, "const float" and "float" are equivalent. 3672 QualType lhsType = 3673 Context.getCanonicalType(lex->getType()).getUnqualifiedType(); 3674 QualType rhsType = 3675 Context.getCanonicalType(rex->getType()).getUnqualifiedType(); 3676 3677 // If the vector types are identical, return. 3678 if (lhsType == rhsType) 3679 return lhsType; 3680 3681 // Handle the case of a vector & extvector type of the same size and element 3682 // type. It would be nice if we only had one vector type someday. 3683 if (getLangOptions().LaxVectorConversions) { 3684 // FIXME: Should we warn here? 3685 if (const VectorType *LV = lhsType->getAsVectorType()) { 3686 if (const VectorType *RV = rhsType->getAsVectorType()) 3687 if (LV->getElementType() == RV->getElementType() && 3688 LV->getNumElements() == RV->getNumElements()) { 3689 return lhsType->isExtVectorType() ? lhsType : rhsType; 3690 } 3691 } 3692 } 3693 3694 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can 3695 // swap back (so that we don't reverse the inputs to a subtract, for instance. 3696 bool swapped = false; 3697 if (rhsType->isExtVectorType()) { 3698 swapped = true; 3699 std::swap(rex, lex); 3700 std::swap(rhsType, lhsType); 3701 } 3702 3703 // Handle the case of an ext vector and scalar. 3704 if (const ExtVectorType *LV = lhsType->getAsExtVectorType()) { 3705 QualType EltTy = LV->getElementType(); 3706 if (EltTy->isIntegralType() && rhsType->isIntegralType()) { 3707 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) { 3708 ImpCastExprToType(rex, lhsType); 3709 if (swapped) std::swap(rex, lex); 3710 return lhsType; 3711 } 3712 } 3713 if (EltTy->isRealFloatingType() && rhsType->isScalarType() && 3714 rhsType->isRealFloatingType()) { 3715 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) { 3716 ImpCastExprToType(rex, lhsType); 3717 if (swapped) std::swap(rex, lex); 3718 return lhsType; 3719 } 3720 } 3721 } 3722 3723 // Vectors of different size or scalar and non-ext-vector are errors. 3724 Diag(Loc, diag::err_typecheck_vector_not_convertable) 3725 << lex->getType() << rex->getType() 3726 << lex->getSourceRange() << rex->getSourceRange(); 3727 return QualType(); 3728 } 3729 3730 inline QualType Sema::CheckMultiplyDivideOperands( 3731 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) 3732 { 3733 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 3734 return CheckVectorOperands(Loc, lex, rex); 3735 3736 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 3737 3738 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 3739 return compType; 3740 return InvalidOperands(Loc, lex, rex); 3741 } 3742 3743 inline QualType Sema::CheckRemainderOperands( 3744 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) 3745 { 3746 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) { 3747 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType()) 3748 return CheckVectorOperands(Loc, lex, rex); 3749 return InvalidOperands(Loc, lex, rex); 3750 } 3751 3752 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 3753 3754 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType()) 3755 return compType; 3756 return InvalidOperands(Loc, lex, rex); 3757 } 3758 3759 inline QualType Sema::CheckAdditionOperands( // C99 6.5.6 3760 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) 3761 { 3762 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) { 3763 QualType compType = CheckVectorOperands(Loc, lex, rex); 3764 if (CompLHSTy) *CompLHSTy = compType; 3765 return compType; 3766 } 3767 3768 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy); 3769 3770 // handle the common case first (both operands are arithmetic). 3771 if (lex->getType()->isArithmeticType() && 3772 rex->getType()->isArithmeticType()) { 3773 if (CompLHSTy) *CompLHSTy = compType; 3774 return compType; 3775 } 3776 3777 // Put any potential pointer into PExp 3778 Expr* PExp = lex, *IExp = rex; 3779 if (IExp->getType()->isPointerType()) 3780 std::swap(PExp, IExp); 3781 3782 if (const PointerType *PTy = PExp->getType()->getAsPointerType()) { 3783 if (IExp->getType()->isIntegerType()) { 3784 QualType PointeeTy = PTy->getPointeeType(); 3785 // Check for arithmetic on pointers to incomplete types. 3786 if (PointeeTy->isVoidType()) { 3787 if (getLangOptions().CPlusPlus) { 3788 Diag(Loc, diag::err_typecheck_pointer_arith_void_type) 3789 << lex->getSourceRange() << rex->getSourceRange(); 3790 return QualType(); 3791 } 3792 3793 // GNU extension: arithmetic on pointer to void 3794 Diag(Loc, diag::ext_gnu_void_ptr) 3795 << lex->getSourceRange() << rex->getSourceRange(); 3796 } else if (PointeeTy->isFunctionType()) { 3797 if (getLangOptions().CPlusPlus) { 3798 Diag(Loc, diag::err_typecheck_pointer_arith_function_type) 3799 << lex->getType() << lex->getSourceRange(); 3800 return QualType(); 3801 } 3802 3803 // GNU extension: arithmetic on pointer to function 3804 Diag(Loc, diag::ext_gnu_ptr_func_arith) 3805 << lex->getType() << lex->getSourceRange(); 3806 } else if (!PTy->isDependentType() && 3807 RequireCompleteType(Loc, PointeeTy, 3808 diag::err_typecheck_arithmetic_incomplete_type, 3809 PExp->getSourceRange(), SourceRange(), 3810 PExp->getType())) 3811 return QualType(); 3812 3813 // Diagnose bad cases where we step over interface counts. 3814 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) { 3815 Diag(Loc, diag::err_arithmetic_nonfragile_interface) 3816 << PointeeTy << PExp->getSourceRange(); 3817 return QualType(); 3818 } 3819 3820 if (CompLHSTy) { 3821 QualType LHSTy = lex->getType(); 3822 if (LHSTy->isPromotableIntegerType()) 3823 LHSTy = Context.IntTy; 3824 else { 3825 QualType T = isPromotableBitField(lex, Context); 3826 if (!T.isNull()) 3827 LHSTy = T; 3828 } 3829 3830 *CompLHSTy = LHSTy; 3831 } 3832 return PExp->getType(); 3833 } 3834 } 3835 3836 return InvalidOperands(Loc, lex, rex); 3837 } 3838 3839 // C99 6.5.6 3840 QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex, 3841 SourceLocation Loc, QualType* CompLHSTy) { 3842 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) { 3843 QualType compType = CheckVectorOperands(Loc, lex, rex); 3844 if (CompLHSTy) *CompLHSTy = compType; 3845 return compType; 3846 } 3847 3848 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy); 3849 3850 // Enforce type constraints: C99 6.5.6p3. 3851 3852 // Handle the common case first (both operands are arithmetic). 3853 if (lex->getType()->isArithmeticType() 3854 && rex->getType()->isArithmeticType()) { 3855 if (CompLHSTy) *CompLHSTy = compType; 3856 return compType; 3857 } 3858 3859 // Either ptr - int or ptr - ptr. 3860 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) { 3861 QualType lpointee = LHSPTy->getPointeeType(); 3862 3863 // The LHS must be an completely-defined object type. 3864 3865 bool ComplainAboutVoid = false; 3866 Expr *ComplainAboutFunc = 0; 3867 if (lpointee->isVoidType()) { 3868 if (getLangOptions().CPlusPlus) { 3869 Diag(Loc, diag::err_typecheck_pointer_arith_void_type) 3870 << lex->getSourceRange() << rex->getSourceRange(); 3871 return QualType(); 3872 } 3873 3874 // GNU C extension: arithmetic on pointer to void 3875 ComplainAboutVoid = true; 3876 } else if (lpointee->isFunctionType()) { 3877 if (getLangOptions().CPlusPlus) { 3878 Diag(Loc, diag::err_typecheck_pointer_arith_function_type) 3879 << lex->getType() << lex->getSourceRange(); 3880 return QualType(); 3881 } 3882 3883 // GNU C extension: arithmetic on pointer to function 3884 ComplainAboutFunc = lex; 3885 } else if (!lpointee->isDependentType() && 3886 RequireCompleteType(Loc, lpointee, 3887 diag::err_typecheck_sub_ptr_object, 3888 lex->getSourceRange(), 3889 SourceRange(), 3890 lex->getType())) 3891 return QualType(); 3892 3893 // Diagnose bad cases where we step over interface counts. 3894 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) { 3895 Diag(Loc, diag::err_arithmetic_nonfragile_interface) 3896 << lpointee << lex->getSourceRange(); 3897 return QualType(); 3898 } 3899 3900 // The result type of a pointer-int computation is the pointer type. 3901 if (rex->getType()->isIntegerType()) { 3902 if (ComplainAboutVoid) 3903 Diag(Loc, diag::ext_gnu_void_ptr) 3904 << lex->getSourceRange() << rex->getSourceRange(); 3905 if (ComplainAboutFunc) 3906 Diag(Loc, diag::ext_gnu_ptr_func_arith) 3907 << ComplainAboutFunc->getType() 3908 << ComplainAboutFunc->getSourceRange(); 3909 3910 if (CompLHSTy) *CompLHSTy = lex->getType(); 3911 return lex->getType(); 3912 } 3913 3914 // Handle pointer-pointer subtractions. 3915 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) { 3916 QualType rpointee = RHSPTy->getPointeeType(); 3917 3918 // RHS must be a completely-type object type. 3919 // Handle the GNU void* extension. 3920 if (rpointee->isVoidType()) { 3921 if (getLangOptions().CPlusPlus) { 3922 Diag(Loc, diag::err_typecheck_pointer_arith_void_type) 3923 << lex->getSourceRange() << rex->getSourceRange(); 3924 return QualType(); 3925 } 3926 3927 ComplainAboutVoid = true; 3928 } else if (rpointee->isFunctionType()) { 3929 if (getLangOptions().CPlusPlus) { 3930 Diag(Loc, diag::err_typecheck_pointer_arith_function_type) 3931 << rex->getType() << rex->getSourceRange(); 3932 return QualType(); 3933 } 3934 3935 // GNU extension: arithmetic on pointer to function 3936 if (!ComplainAboutFunc) 3937 ComplainAboutFunc = rex; 3938 } else if (!rpointee->isDependentType() && 3939 RequireCompleteType(Loc, rpointee, 3940 diag::err_typecheck_sub_ptr_object, 3941 rex->getSourceRange(), 3942 SourceRange(), 3943 rex->getType())) 3944 return QualType(); 3945 3946 if (getLangOptions().CPlusPlus) { 3947 // Pointee types must be the same: C++ [expr.add] 3948 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 3949 Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 3950 << lex->getType() << rex->getType() 3951 << lex->getSourceRange() << rex->getSourceRange(); 3952 return QualType(); 3953 } 3954 } else { 3955 // Pointee types must be compatible C99 6.5.6p3 3956 if (!Context.typesAreCompatible( 3957 Context.getCanonicalType(lpointee).getUnqualifiedType(), 3958 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 3959 Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 3960 << lex->getType() << rex->getType() 3961 << lex->getSourceRange() << rex->getSourceRange(); 3962 return QualType(); 3963 } 3964 } 3965 3966 if (ComplainAboutVoid) 3967 Diag(Loc, diag::ext_gnu_void_ptr) 3968 << lex->getSourceRange() << rex->getSourceRange(); 3969 if (ComplainAboutFunc) 3970 Diag(Loc, diag::ext_gnu_ptr_func_arith) 3971 << ComplainAboutFunc->getType() 3972 << ComplainAboutFunc->getSourceRange(); 3973 3974 if (CompLHSTy) *CompLHSTy = lex->getType(); 3975 return Context.getPointerDiffType(); 3976 } 3977 } 3978 3979 return InvalidOperands(Loc, lex, rex); 3980 } 3981 3982 // C99 6.5.7 3983 QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc, 3984 bool isCompAssign) { 3985 // C99 6.5.7p2: Each of the operands shall have integer type. 3986 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType()) 3987 return InvalidOperands(Loc, lex, rex); 3988 3989 // Shifts don't perform usual arithmetic conversions, they just do integer 3990 // promotions on each operand. C99 6.5.7p3 3991 QualType LHSTy; 3992 if (lex->getType()->isPromotableIntegerType()) 3993 LHSTy = Context.IntTy; 3994 else { 3995 LHSTy = isPromotableBitField(lex, Context); 3996 if (LHSTy.isNull()) 3997 LHSTy = lex->getType(); 3998 } 3999 if (!isCompAssign) 4000 ImpCastExprToType(lex, LHSTy); 4001 4002 UsualUnaryConversions(rex); 4003 4004 // "The type of the result is that of the promoted left operand." 4005 return LHSTy; 4006 } 4007 4008 // C99 6.5.8, C++ [expr.rel] 4009 QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc, 4010 unsigned OpaqueOpc, bool isRelational) { 4011 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc; 4012 4013 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 4014 return CheckVectorCompareOperands(lex, rex, Loc, isRelational); 4015 4016 // C99 6.5.8p3 / C99 6.5.9p4 4017 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 4018 UsualArithmeticConversions(lex, rex); 4019 else { 4020 UsualUnaryConversions(lex); 4021 UsualUnaryConversions(rex); 4022 } 4023 QualType lType = lex->getType(); 4024 QualType rType = rex->getType(); 4025 4026 if (!lType->isFloatingType() 4027 && !(lType->isBlockPointerType() && isRelational)) { 4028 // For non-floating point types, check for self-comparisons of the form 4029 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 4030 // often indicate logic errors in the program. 4031 // NOTE: Don't warn about comparisons of enum constants. These can arise 4032 // from macro expansions, and are usually quite deliberate. 4033 Expr *LHSStripped = lex->IgnoreParens(); 4034 Expr *RHSStripped = rex->IgnoreParens(); 4035 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) 4036 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) 4037 if (DRL->getDecl() == DRR->getDecl() && 4038 !isa<EnumConstantDecl>(DRL->getDecl())) 4039 Diag(Loc, diag::warn_selfcomparison); 4040 4041 if (isa<CastExpr>(LHSStripped)) 4042 LHSStripped = LHSStripped->IgnoreParenCasts(); 4043 if (isa<CastExpr>(RHSStripped)) 4044 RHSStripped = RHSStripped->IgnoreParenCasts(); 4045 4046 // Warn about comparisons against a string constant (unless the other 4047 // operand is null), the user probably wants strcmp. 4048 Expr *literalString = 0; 4049 Expr *literalStringStripped = 0; 4050 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 4051 !RHSStripped->isNullPointerConstant(Context)) { 4052 literalString = lex; 4053 literalStringStripped = LHSStripped; 4054 } 4055 else if ((isa<StringLiteral>(RHSStripped) || 4056 isa<ObjCEncodeExpr>(RHSStripped)) && 4057 !LHSStripped->isNullPointerConstant(Context)) { 4058 literalString = rex; 4059 literalStringStripped = RHSStripped; 4060 } 4061 4062 if (literalString) { 4063 std::string resultComparison; 4064 switch (Opc) { 4065 case BinaryOperator::LT: resultComparison = ") < 0"; break; 4066 case BinaryOperator::GT: resultComparison = ") > 0"; break; 4067 case BinaryOperator::LE: resultComparison = ") <= 0"; break; 4068 case BinaryOperator::GE: resultComparison = ") >= 0"; break; 4069 case BinaryOperator::EQ: resultComparison = ") == 0"; break; 4070 case BinaryOperator::NE: resultComparison = ") != 0"; break; 4071 default: assert(false && "Invalid comparison operator"); 4072 } 4073 Diag(Loc, diag::warn_stringcompare) 4074 << isa<ObjCEncodeExpr>(literalStringStripped) 4075 << literalString->getSourceRange() 4076 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ") 4077 << CodeModificationHint::CreateInsertion(lex->getLocStart(), 4078 "strcmp(") 4079 << CodeModificationHint::CreateInsertion( 4080 PP.getLocForEndOfToken(rex->getLocEnd()), 4081 resultComparison); 4082 } 4083 } 4084 4085 // The result of comparisons is 'bool' in C++, 'int' in C. 4086 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy; 4087 4088 if (isRelational) { 4089 if (lType->isRealType() && rType->isRealType()) 4090 return ResultTy; 4091 } else { 4092 // Check for comparisons of floating point operands using != and ==. 4093 if (lType->isFloatingType()) { 4094 assert(rType->isFloatingType()); 4095 CheckFloatComparison(Loc,lex,rex); 4096 } 4097 4098 if (lType->isArithmeticType() && rType->isArithmeticType()) 4099 return ResultTy; 4100 } 4101 4102 bool LHSIsNull = lex->isNullPointerConstant(Context); 4103 bool RHSIsNull = rex->isNullPointerConstant(Context); 4104 4105 // All of the following pointer related warnings are GCC extensions, except 4106 // when handling null pointer constants. One day, we can consider making them 4107 // errors (when -pedantic-errors is enabled). 4108 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2 4109 QualType LCanPointeeTy = 4110 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType()); 4111 QualType RCanPointeeTy = 4112 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType()); 4113 4114 if (isRelational) { 4115 if (lType->isFunctionPointerType() || rType->isFunctionPointerType()) { 4116 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 4117 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 4118 } 4119 if (LCanPointeeTy->isVoidType() != RCanPointeeTy->isVoidType()) { 4120 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers) 4121 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 4122 } 4123 } else { 4124 if (lType->isFunctionPointerType() != rType->isFunctionPointerType()) { 4125 if (!LHSIsNull && !RHSIsNull) 4126 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers) 4127 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 4128 } 4129 } 4130 4131 // Simple check: if the pointee types are identical, we're done. 4132 if (LCanPointeeTy == RCanPointeeTy) 4133 return ResultTy; 4134 4135 if (getLangOptions().CPlusPlus) { 4136 // C++ [expr.rel]p2: 4137 // [...] Pointer conversions (4.10) and qualification 4138 // conversions (4.4) are performed on pointer operands (or on 4139 // a pointer operand and a null pointer constant) to bring 4140 // them to their composite pointer type. [...] 4141 // 4142 // C++ [expr.eq]p2 uses the same notion for (in)equality 4143 // comparisons of pointers. 4144 QualType T = FindCompositePointerType(lex, rex); 4145 if (T.isNull()) { 4146 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers) 4147 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 4148 return QualType(); 4149 } 4150 4151 ImpCastExprToType(lex, T); 4152 ImpCastExprToType(rex, T); 4153 return ResultTy; 4154 } 4155 4156 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2 4157 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() && 4158 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 4159 RCanPointeeTy.getUnqualifiedType()) && 4160 !Context.areComparableObjCPointerTypes(lType, rType)) { 4161 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers) 4162 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 4163 } 4164 ImpCastExprToType(rex, lType); // promote the pointer to pointer 4165 return ResultTy; 4166 } 4167 // C++ allows comparison of pointers with null pointer constants. 4168 if (getLangOptions().CPlusPlus) { 4169 if (lType->isPointerType() && RHSIsNull) { 4170 ImpCastExprToType(rex, lType); 4171 return ResultTy; 4172 } 4173 if (rType->isPointerType() && LHSIsNull) { 4174 ImpCastExprToType(lex, rType); 4175 return ResultTy; 4176 } 4177 // And comparison of nullptr_t with itself. 4178 if (lType->isNullPtrType() && rType->isNullPtrType()) 4179 return ResultTy; 4180 } 4181 // Handle block pointer types. 4182 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) { 4183 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType(); 4184 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType(); 4185 4186 if (!LHSIsNull && !RHSIsNull && 4187 !Context.typesAreCompatible(lpointee, rpointee)) { 4188 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 4189 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 4190 } 4191 ImpCastExprToType(rex, lType); // promote the pointer to pointer 4192 return ResultTy; 4193 } 4194 // Allow block pointers to be compared with null pointer constants. 4195 if (!isRelational 4196 && ((lType->isBlockPointerType() && rType->isPointerType()) 4197 || (lType->isPointerType() && rType->isBlockPointerType()))) { 4198 if (!LHSIsNull && !RHSIsNull) { 4199 if (!((rType->isPointerType() && rType->getAsPointerType() 4200 ->getPointeeType()->isVoidType()) 4201 || (lType->isPointerType() && lType->getAsPointerType() 4202 ->getPointeeType()->isVoidType()))) 4203 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 4204 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 4205 } 4206 ImpCastExprToType(rex, lType); // promote the pointer to pointer 4207 return ResultTy; 4208 } 4209 4210 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) { 4211 if (lType->isPointerType() || rType->isPointerType()) { 4212 const PointerType *LPT = lType->getAsPointerType(); 4213 const PointerType *RPT = rType->getAsPointerType(); 4214 bool LPtrToVoid = LPT ? 4215 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false; 4216 bool RPtrToVoid = RPT ? 4217 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false; 4218 4219 if (!LPtrToVoid && !RPtrToVoid && 4220 !Context.typesAreCompatible(lType, rType)) { 4221 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers) 4222 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 4223 ImpCastExprToType(rex, lType); 4224 return ResultTy; 4225 } 4226 ImpCastExprToType(rex, lType); 4227 return ResultTy; 4228 } 4229 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) { 4230 ImpCastExprToType(rex, lType); 4231 return ResultTy; 4232 } else { 4233 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) { 4234 Diag(Loc, diag::warn_incompatible_qualified_id_operands) 4235 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 4236 ImpCastExprToType(rex, lType); 4237 return ResultTy; 4238 } 4239 } 4240 } 4241 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) && 4242 rType->isIntegerType()) { 4243 if (isRelational) 4244 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_pointer_integer) 4245 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 4246 else if (!RHSIsNull) 4247 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer) 4248 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 4249 ImpCastExprToType(rex, lType); // promote the integer to pointer 4250 return ResultTy; 4251 } 4252 if (lType->isIntegerType() && 4253 (rType->isPointerType() || rType->isObjCQualifiedIdType())) { 4254 if (isRelational) 4255 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_pointer_integer) 4256 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 4257 else if (!LHSIsNull) 4258 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer) 4259 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 4260 ImpCastExprToType(lex, rType); // promote the integer to pointer 4261 return ResultTy; 4262 } 4263 // Handle block pointers. 4264 if (!isRelational && RHSIsNull 4265 && lType->isBlockPointerType() && rType->isIntegerType()) { 4266 ImpCastExprToType(rex, lType); // promote the integer to pointer 4267 return ResultTy; 4268 } 4269 if (!isRelational && LHSIsNull 4270 && lType->isIntegerType() && rType->isBlockPointerType()) { 4271 ImpCastExprToType(lex, rType); // promote the integer to pointer 4272 return ResultTy; 4273 } 4274 return InvalidOperands(Loc, lex, rex); 4275 } 4276 4277 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 4278 /// operates on extended vector types. Instead of producing an IntTy result, 4279 /// like a scalar comparison, a vector comparison produces a vector of integer 4280 /// types. 4281 QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex, 4282 SourceLocation Loc, 4283 bool isRelational) { 4284 // Check to make sure we're operating on vectors of the same type and width, 4285 // Allowing one side to be a scalar of element type. 4286 QualType vType = CheckVectorOperands(Loc, lex, rex); 4287 if (vType.isNull()) 4288 return vType; 4289 4290 QualType lType = lex->getType(); 4291 QualType rType = rex->getType(); 4292 4293 // For non-floating point types, check for self-comparisons of the form 4294 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 4295 // often indicate logic errors in the program. 4296 if (!lType->isFloatingType()) { 4297 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens())) 4298 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens())) 4299 if (DRL->getDecl() == DRR->getDecl()) 4300 Diag(Loc, diag::warn_selfcomparison); 4301 } 4302 4303 // Check for comparisons of floating point operands using != and ==. 4304 if (!isRelational && lType->isFloatingType()) { 4305 assert (rType->isFloatingType()); 4306 CheckFloatComparison(Loc,lex,rex); 4307 } 4308 4309 // Return the type for the comparison, which is the same as vector type for 4310 // integer vectors, or an integer type of identical size and number of 4311 // elements for floating point vectors. 4312 if (lType->isIntegerType()) 4313 return lType; 4314 4315 const VectorType *VTy = lType->getAsVectorType(); 4316 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 4317 if (TypeSize == Context.getTypeSize(Context.IntTy)) 4318 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 4319 if (TypeSize == Context.getTypeSize(Context.LongTy)) 4320 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 4321 4322 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 4323 "Unhandled vector element size in vector compare"); 4324 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 4325 } 4326 4327 inline QualType Sema::CheckBitwiseOperands( 4328 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) 4329 { 4330 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 4331 return CheckVectorOperands(Loc, lex, rex); 4332 4333 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 4334 4335 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType()) 4336 return compType; 4337 return InvalidOperands(Loc, lex, rex); 4338 } 4339 4340 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 4341 Expr *&lex, Expr *&rex, SourceLocation Loc) 4342 { 4343 UsualUnaryConversions(lex); 4344 UsualUnaryConversions(rex); 4345 4346 if (lex->getType()->isScalarType() && rex->getType()->isScalarType()) 4347 return Context.IntTy; 4348 return InvalidOperands(Loc, lex, rex); 4349 } 4350 4351 /// IsReadonlyProperty - Verify that otherwise a valid l-value expression 4352 /// is a read-only property; return true if so. A readonly property expression 4353 /// depends on various declarations and thus must be treated specially. 4354 /// 4355 static bool IsReadonlyProperty(Expr *E, Sema &S) 4356 { 4357 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) { 4358 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E); 4359 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) { 4360 QualType BaseType = PropExpr->getBase()->getType(); 4361 if (const PointerType *PTy = BaseType->getAsPointerType()) 4362 if (const ObjCInterfaceType *IFTy = 4363 PTy->getPointeeType()->getAsObjCInterfaceType()) 4364 if (ObjCInterfaceDecl *IFace = IFTy->getDecl()) 4365 if (S.isPropertyReadonly(PDecl, IFace)) 4366 return true; 4367 } 4368 } 4369 return false; 4370 } 4371 4372 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 4373 /// emit an error and return true. If so, return false. 4374 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 4375 SourceLocation OrigLoc = Loc; 4376 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 4377 &Loc); 4378 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S)) 4379 IsLV = Expr::MLV_ReadonlyProperty; 4380 if (IsLV == Expr::MLV_Valid) 4381 return false; 4382 4383 unsigned Diag = 0; 4384 bool NeedType = false; 4385 switch (IsLV) { // C99 6.5.16p2 4386 default: assert(0 && "Unknown result from isModifiableLvalue!"); 4387 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break; 4388 case Expr::MLV_ArrayType: 4389 Diag = diag::err_typecheck_array_not_modifiable_lvalue; 4390 NeedType = true; 4391 break; 4392 case Expr::MLV_NotObjectType: 4393 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue; 4394 NeedType = true; 4395 break; 4396 case Expr::MLV_LValueCast: 4397 Diag = diag::err_typecheck_lvalue_casts_not_supported; 4398 break; 4399 case Expr::MLV_InvalidExpression: 4400 Diag = diag::err_typecheck_expression_not_modifiable_lvalue; 4401 break; 4402 case Expr::MLV_IncompleteType: 4403 case Expr::MLV_IncompleteVoidType: 4404 return S.RequireCompleteType(Loc, E->getType(), 4405 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, 4406 E->getSourceRange()); 4407 case Expr::MLV_DuplicateVectorComponents: 4408 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 4409 break; 4410 case Expr::MLV_NotBlockQualified: 4411 Diag = diag::err_block_decl_ref_not_modifiable_lvalue; 4412 break; 4413 case Expr::MLV_ReadonlyProperty: 4414 Diag = diag::error_readonly_property_assignment; 4415 break; 4416 case Expr::MLV_NoSetterProperty: 4417 Diag = diag::error_nosetter_property_assignment; 4418 break; 4419 } 4420 4421 SourceRange Assign; 4422 if (Loc != OrigLoc) 4423 Assign = SourceRange(OrigLoc, OrigLoc); 4424 if (NeedType) 4425 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign; 4426 else 4427 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 4428 return true; 4429 } 4430 4431 4432 4433 // C99 6.5.16.1 4434 QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS, 4435 SourceLocation Loc, 4436 QualType CompoundType) { 4437 // Verify that LHS is a modifiable lvalue, and emit error if not. 4438 if (CheckForModifiableLvalue(LHS, Loc, *this)) 4439 return QualType(); 4440 4441 QualType LHSType = LHS->getType(); 4442 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType; 4443 4444 AssignConvertType ConvTy; 4445 if (CompoundType.isNull()) { 4446 // Simple assignment "x = y". 4447 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS); 4448 // Special case of NSObject attributes on c-style pointer types. 4449 if (ConvTy == IncompatiblePointer && 4450 ((Context.isObjCNSObjectType(LHSType) && 4451 Context.isObjCObjectPointerType(RHSType)) || 4452 (Context.isObjCNSObjectType(RHSType) && 4453 Context.isObjCObjectPointerType(LHSType)))) 4454 ConvTy = Compatible; 4455 4456 // If the RHS is a unary plus or minus, check to see if they = and + are 4457 // right next to each other. If so, the user may have typo'd "x =+ 4" 4458 // instead of "x += 4". 4459 Expr *RHSCheck = RHS; 4460 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 4461 RHSCheck = ICE->getSubExpr(); 4462 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 4463 if ((UO->getOpcode() == UnaryOperator::Plus || 4464 UO->getOpcode() == UnaryOperator::Minus) && 4465 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 4466 // Only if the two operators are exactly adjacent. 4467 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() && 4468 // And there is a space or other character before the subexpr of the 4469 // unary +/-. We don't want to warn on "x=-1". 4470 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 4471 UO->getSubExpr()->getLocStart().isFileID()) { 4472 Diag(Loc, diag::warn_not_compound_assign) 4473 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-") 4474 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 4475 } 4476 } 4477 } else { 4478 // Compound assignment "x += y" 4479 ConvTy = CheckAssignmentConstraints(LHSType, RHSType); 4480 } 4481 4482 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 4483 RHS, "assigning")) 4484 return QualType(); 4485 4486 // C99 6.5.16p3: The type of an assignment expression is the type of the 4487 // left operand unless the left operand has qualified type, in which case 4488 // it is the unqualified version of the type of the left operand. 4489 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 4490 // is converted to the type of the assignment expression (above). 4491 // C++ 5.17p1: the type of the assignment expression is that of its left 4492 // operand. 4493 return LHSType.getUnqualifiedType(); 4494 } 4495 4496 // C99 6.5.17 4497 QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) { 4498 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions. 4499 DefaultFunctionArrayConversion(RHS); 4500 4501 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be 4502 // incomplete in C++). 4503 4504 return RHS->getType(); 4505 } 4506 4507 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 4508 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 4509 QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc, 4510 bool isInc) { 4511 if (Op->isTypeDependent()) 4512 return Context.DependentTy; 4513 4514 QualType ResType = Op->getType(); 4515 assert(!ResType.isNull() && "no type for increment/decrement expression"); 4516 4517 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) { 4518 // Decrement of bool is not allowed. 4519 if (!isInc) { 4520 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 4521 return QualType(); 4522 } 4523 // Increment of bool sets it to true, but is deprecated. 4524 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); 4525 } else if (ResType->isRealType()) { 4526 // OK! 4527 } else if (const PointerType *PT = ResType->getAsPointerType()) { 4528 // C99 6.5.2.4p2, 6.5.6p2 4529 if (PT->getPointeeType()->isVoidType()) { 4530 if (getLangOptions().CPlusPlus) { 4531 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type) 4532 << Op->getSourceRange(); 4533 return QualType(); 4534 } 4535 4536 // Pointer to void is a GNU extension in C. 4537 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange(); 4538 } else if (PT->getPointeeType()->isFunctionType()) { 4539 if (getLangOptions().CPlusPlus) { 4540 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type) 4541 << Op->getType() << Op->getSourceRange(); 4542 return QualType(); 4543 } 4544 4545 Diag(OpLoc, diag::ext_gnu_ptr_func_arith) 4546 << ResType << Op->getSourceRange(); 4547 } else if (RequireCompleteType(OpLoc, PT->getPointeeType(), 4548 diag::err_typecheck_arithmetic_incomplete_type, 4549 Op->getSourceRange(), SourceRange(), 4550 ResType)) 4551 return QualType(); 4552 } else if (ResType->isComplexType()) { 4553 // C99 does not support ++/-- on complex types, we allow as an extension. 4554 Diag(OpLoc, diag::ext_integer_increment_complex) 4555 << ResType << Op->getSourceRange(); 4556 } else { 4557 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 4558 << ResType << Op->getSourceRange(); 4559 return QualType(); 4560 } 4561 // At this point, we know we have a real, complex or pointer type. 4562 // Now make sure the operand is a modifiable lvalue. 4563 if (CheckForModifiableLvalue(Op, OpLoc, *this)) 4564 return QualType(); 4565 return ResType; 4566 } 4567 4568 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 4569 /// This routine allows us to typecheck complex/recursive expressions 4570 /// where the declaration is needed for type checking. We only need to 4571 /// handle cases when the expression references a function designator 4572 /// or is an lvalue. Here are some examples: 4573 /// - &(x) => x 4574 /// - &*****f => f for f a function designator. 4575 /// - &s.xx => s 4576 /// - &s.zz[1].yy -> s, if zz is an array 4577 /// - *(x + 1) -> x, if x is an array 4578 /// - &"123"[2] -> 0 4579 /// - & __real__ x -> x 4580 static NamedDecl *getPrimaryDecl(Expr *E) { 4581 switch (E->getStmtClass()) { 4582 case Stmt::DeclRefExprClass: 4583 case Stmt::QualifiedDeclRefExprClass: 4584 return cast<DeclRefExpr>(E)->getDecl(); 4585 case Stmt::MemberExprClass: 4586 // If this is an arrow operator, the address is an offset from 4587 // the base's value, so the object the base refers to is 4588 // irrelevant. 4589 if (cast<MemberExpr>(E)->isArrow()) 4590 return 0; 4591 // Otherwise, the expression refers to a part of the base 4592 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 4593 case Stmt::ArraySubscriptExprClass: { 4594 // FIXME: This code shouldn't be necessary! We should catch the implicit 4595 // promotion of register arrays earlier. 4596 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 4597 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 4598 if (ICE->getSubExpr()->getType()->isArrayType()) 4599 return getPrimaryDecl(ICE->getSubExpr()); 4600 } 4601 return 0; 4602 } 4603 case Stmt::UnaryOperatorClass: { 4604 UnaryOperator *UO = cast<UnaryOperator>(E); 4605 4606 switch(UO->getOpcode()) { 4607 case UnaryOperator::Real: 4608 case UnaryOperator::Imag: 4609 case UnaryOperator::Extension: 4610 return getPrimaryDecl(UO->getSubExpr()); 4611 default: 4612 return 0; 4613 } 4614 } 4615 case Stmt::ParenExprClass: 4616 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 4617 case Stmt::ImplicitCastExprClass: 4618 // If the result of an implicit cast is an l-value, we care about 4619 // the sub-expression; otherwise, the result here doesn't matter. 4620 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 4621 default: 4622 return 0; 4623 } 4624 } 4625 4626 /// CheckAddressOfOperand - The operand of & must be either a function 4627 /// designator or an lvalue designating an object. If it is an lvalue, the 4628 /// object cannot be declared with storage class register or be a bit field. 4629 /// Note: The usual conversions are *not* applied to the operand of the & 4630 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 4631 /// In C++, the operand might be an overloaded function name, in which case 4632 /// we allow the '&' but retain the overloaded-function type. 4633 QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) { 4634 // Make sure to ignore parentheses in subsequent checks 4635 op = op->IgnoreParens(); 4636 4637 if (op->isTypeDependent()) 4638 return Context.DependentTy; 4639 4640 if (getLangOptions().C99) { 4641 // Implement C99-only parts of addressof rules. 4642 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 4643 if (uOp->getOpcode() == UnaryOperator::Deref) 4644 // Per C99 6.5.3.2, the address of a deref always returns a valid result 4645 // (assuming the deref expression is valid). 4646 return uOp->getSubExpr()->getType(); 4647 } 4648 // Technically, there should be a check for array subscript 4649 // expressions here, but the result of one is always an lvalue anyway. 4650 } 4651 NamedDecl *dcl = getPrimaryDecl(op); 4652 Expr::isLvalueResult lval = op->isLvalue(Context); 4653 4654 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 4655 // C99 6.5.3.2p1 4656 // The operand must be either an l-value or a function designator 4657 if (!op->getType()->isFunctionType()) { 4658 // FIXME: emit more specific diag... 4659 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 4660 << op->getSourceRange(); 4661 return QualType(); 4662 } 4663 } else if (op->getBitField()) { // C99 6.5.3.2p1 4664 // The operand cannot be a bit-field 4665 Diag(OpLoc, diag::err_typecheck_address_of) 4666 << "bit-field" << op->getSourceRange(); 4667 return QualType(); 4668 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) && 4669 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){ 4670 // The operand cannot be an element of a vector 4671 Diag(OpLoc, diag::err_typecheck_address_of) 4672 << "vector element" << op->getSourceRange(); 4673 return QualType(); 4674 } else if (isa<ObjCPropertyRefExpr>(op)) { 4675 // cannot take address of a property expression. 4676 Diag(OpLoc, diag::err_typecheck_address_of) 4677 << "property expression" << op->getSourceRange(); 4678 return QualType(); 4679 } else if (dcl) { // C99 6.5.3.2p1 4680 // We have an lvalue with a decl. Make sure the decl is not declared 4681 // with the register storage-class specifier. 4682 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 4683 if (vd->getStorageClass() == VarDecl::Register) { 4684 Diag(OpLoc, diag::err_typecheck_address_of) 4685 << "register variable" << op->getSourceRange(); 4686 return QualType(); 4687 } 4688 } else if (isa<OverloadedFunctionDecl>(dcl) || 4689 isa<FunctionTemplateDecl>(dcl)) { 4690 return Context.OverloadTy; 4691 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) { 4692 // Okay: we can take the address of a field. 4693 // Could be a pointer to member, though, if there is an explicit 4694 // scope qualifier for the class. 4695 if (isa<QualifiedDeclRefExpr>(op)) { 4696 DeclContext *Ctx = dcl->getDeclContext(); 4697 if (Ctx && Ctx->isRecord()) { 4698 if (FD->getType()->isReferenceType()) { 4699 Diag(OpLoc, 4700 diag::err_cannot_form_pointer_to_member_of_reference_type) 4701 << FD->getDeclName() << FD->getType(); 4702 return QualType(); 4703 } 4704 4705 return Context.getMemberPointerType(op->getType(), 4706 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 4707 } 4708 } 4709 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) { 4710 // Okay: we can take the address of a function. 4711 // As above. 4712 if (isa<QualifiedDeclRefExpr>(op) && MD->isInstance()) 4713 return Context.getMemberPointerType(op->getType(), 4714 Context.getTypeDeclType(MD->getParent()).getTypePtr()); 4715 } else if (!isa<FunctionDecl>(dcl)) 4716 assert(0 && "Unknown/unexpected decl type"); 4717 } 4718 4719 if (lval == Expr::LV_IncompleteVoidType) { 4720 // Taking the address of a void variable is technically illegal, but we 4721 // allow it in cases which are otherwise valid. 4722 // Example: "extern void x; void* y = &x;". 4723 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 4724 } 4725 4726 // If the operand has type "type", the result has type "pointer to type". 4727 return Context.getPointerType(op->getType()); 4728 } 4729 4730 QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) { 4731 if (Op->isTypeDependent()) 4732 return Context.DependentTy; 4733 4734 UsualUnaryConversions(Op); 4735 QualType Ty = Op->getType(); 4736 4737 // Note that per both C89 and C99, this is always legal, even if ptype is an 4738 // incomplete type or void. It would be possible to warn about dereferencing 4739 // a void pointer, but it's completely well-defined, and such a warning is 4740 // unlikely to catch any mistakes. 4741 if (const PointerType *PT = Ty->getAsPointerType()) 4742 return PT->getPointeeType(); 4743 4744 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 4745 << Ty << Op->getSourceRange(); 4746 return QualType(); 4747 } 4748 4749 static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode( 4750 tok::TokenKind Kind) { 4751 BinaryOperator::Opcode Opc; 4752 switch (Kind) { 4753 default: assert(0 && "Unknown binop!"); 4754 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break; 4755 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break; 4756 case tok::star: Opc = BinaryOperator::Mul; break; 4757 case tok::slash: Opc = BinaryOperator::Div; break; 4758 case tok::percent: Opc = BinaryOperator::Rem; break; 4759 case tok::plus: Opc = BinaryOperator::Add; break; 4760 case tok::minus: Opc = BinaryOperator::Sub; break; 4761 case tok::lessless: Opc = BinaryOperator::Shl; break; 4762 case tok::greatergreater: Opc = BinaryOperator::Shr; break; 4763 case tok::lessequal: Opc = BinaryOperator::LE; break; 4764 case tok::less: Opc = BinaryOperator::LT; break; 4765 case tok::greaterequal: Opc = BinaryOperator::GE; break; 4766 case tok::greater: Opc = BinaryOperator::GT; break; 4767 case tok::exclaimequal: Opc = BinaryOperator::NE; break; 4768 case tok::equalequal: Opc = BinaryOperator::EQ; break; 4769 case tok::amp: Opc = BinaryOperator::And; break; 4770 case tok::caret: Opc = BinaryOperator::Xor; break; 4771 case tok::pipe: Opc = BinaryOperator::Or; break; 4772 case tok::ampamp: Opc = BinaryOperator::LAnd; break; 4773 case tok::pipepipe: Opc = BinaryOperator::LOr; break; 4774 case tok::equal: Opc = BinaryOperator::Assign; break; 4775 case tok::starequal: Opc = BinaryOperator::MulAssign; break; 4776 case tok::slashequal: Opc = BinaryOperator::DivAssign; break; 4777 case tok::percentequal: Opc = BinaryOperator::RemAssign; break; 4778 case tok::plusequal: Opc = BinaryOperator::AddAssign; break; 4779 case tok::minusequal: Opc = BinaryOperator::SubAssign; break; 4780 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break; 4781 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break; 4782 case tok::ampequal: Opc = BinaryOperator::AndAssign; break; 4783 case tok::caretequal: Opc = BinaryOperator::XorAssign; break; 4784 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break; 4785 case tok::comma: Opc = BinaryOperator::Comma; break; 4786 } 4787 return Opc; 4788 } 4789 4790 static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode( 4791 tok::TokenKind Kind) { 4792 UnaryOperator::Opcode Opc; 4793 switch (Kind) { 4794 default: assert(0 && "Unknown unary op!"); 4795 case tok::plusplus: Opc = UnaryOperator::PreInc; break; 4796 case tok::minusminus: Opc = UnaryOperator::PreDec; break; 4797 case tok::amp: Opc = UnaryOperator::AddrOf; break; 4798 case tok::star: Opc = UnaryOperator::Deref; break; 4799 case tok::plus: Opc = UnaryOperator::Plus; break; 4800 case tok::minus: Opc = UnaryOperator::Minus; break; 4801 case tok::tilde: Opc = UnaryOperator::Not; break; 4802 case tok::exclaim: Opc = UnaryOperator::LNot; break; 4803 case tok::kw___real: Opc = UnaryOperator::Real; break; 4804 case tok::kw___imag: Opc = UnaryOperator::Imag; break; 4805 case tok::kw___extension__: Opc = UnaryOperator::Extension; break; 4806 } 4807 return Opc; 4808 } 4809 4810 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 4811 /// operator @p Opc at location @c TokLoc. This routine only supports 4812 /// built-in operations; ActOnBinOp handles overloaded operators. 4813 Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 4814 unsigned Op, 4815 Expr *lhs, Expr *rhs) { 4816 QualType ResultTy; // Result type of the binary operator. 4817 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op; 4818 // The following two variables are used for compound assignment operators 4819 QualType CompLHSTy; // Type of LHS after promotions for computation 4820 QualType CompResultTy; // Type of computation result 4821 4822 switch (Opc) { 4823 case BinaryOperator::Assign: 4824 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType()); 4825 break; 4826 case BinaryOperator::PtrMemD: 4827 case BinaryOperator::PtrMemI: 4828 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc, 4829 Opc == BinaryOperator::PtrMemI); 4830 break; 4831 case BinaryOperator::Mul: 4832 case BinaryOperator::Div: 4833 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc); 4834 break; 4835 case BinaryOperator::Rem: 4836 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc); 4837 break; 4838 case BinaryOperator::Add: 4839 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc); 4840 break; 4841 case BinaryOperator::Sub: 4842 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc); 4843 break; 4844 case BinaryOperator::Shl: 4845 case BinaryOperator::Shr: 4846 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc); 4847 break; 4848 case BinaryOperator::LE: 4849 case BinaryOperator::LT: 4850 case BinaryOperator::GE: 4851 case BinaryOperator::GT: 4852 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true); 4853 break; 4854 case BinaryOperator::EQ: 4855 case BinaryOperator::NE: 4856 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false); 4857 break; 4858 case BinaryOperator::And: 4859 case BinaryOperator::Xor: 4860 case BinaryOperator::Or: 4861 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc); 4862 break; 4863 case BinaryOperator::LAnd: 4864 case BinaryOperator::LOr: 4865 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc); 4866 break; 4867 case BinaryOperator::MulAssign: 4868 case BinaryOperator::DivAssign: 4869 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true); 4870 CompLHSTy = CompResultTy; 4871 if (!CompResultTy.isNull()) 4872 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 4873 break; 4874 case BinaryOperator::RemAssign: 4875 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true); 4876 CompLHSTy = CompResultTy; 4877 if (!CompResultTy.isNull()) 4878 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 4879 break; 4880 case BinaryOperator::AddAssign: 4881 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy); 4882 if (!CompResultTy.isNull()) 4883 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 4884 break; 4885 case BinaryOperator::SubAssign: 4886 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy); 4887 if (!CompResultTy.isNull()) 4888 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 4889 break; 4890 case BinaryOperator::ShlAssign: 4891 case BinaryOperator::ShrAssign: 4892 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true); 4893 CompLHSTy = CompResultTy; 4894 if (!CompResultTy.isNull()) 4895 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 4896 break; 4897 case BinaryOperator::AndAssign: 4898 case BinaryOperator::XorAssign: 4899 case BinaryOperator::OrAssign: 4900 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true); 4901 CompLHSTy = CompResultTy; 4902 if (!CompResultTy.isNull()) 4903 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 4904 break; 4905 case BinaryOperator::Comma: 4906 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc); 4907 break; 4908 } 4909 if (ResultTy.isNull()) 4910 return ExprError(); 4911 if (CompResultTy.isNull()) 4912 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc)); 4913 else 4914 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy, 4915 CompLHSTy, CompResultTy, 4916 OpLoc)); 4917 } 4918 4919 // Binary Operators. 'Tok' is the token for the operator. 4920 Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 4921 tok::TokenKind Kind, 4922 ExprArg LHS, ExprArg RHS) { 4923 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind); 4924 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>(); 4925 4926 assert((lhs != 0) && "ActOnBinOp(): missing left expression"); 4927 assert((rhs != 0) && "ActOnBinOp(): missing right expression"); 4928 4929 if (getLangOptions().CPlusPlus && 4930 (lhs->getType()->isOverloadableType() || 4931 rhs->getType()->isOverloadableType())) { 4932 // Find all of the overloaded operators visible from this 4933 // point. We perform both an operator-name lookup from the local 4934 // scope and an argument-dependent lookup based on the types of 4935 // the arguments. 4936 FunctionSet Functions; 4937 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 4938 if (OverOp != OO_None) { 4939 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(), 4940 Functions); 4941 Expr *Args[2] = { lhs, rhs }; 4942 DeclarationName OpName 4943 = Context.DeclarationNames.getCXXOperatorName(OverOp); 4944 ArgumentDependentLookup(OpName, Args, 2, Functions); 4945 } 4946 4947 // Build the (potentially-overloaded, potentially-dependent) 4948 // binary operation. 4949 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs); 4950 } 4951 4952 // Build a built-in binary operation. 4953 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs); 4954 } 4955 4956 Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 4957 unsigned OpcIn, 4958 ExprArg InputArg) { 4959 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 4960 4961 // FIXME: Input is modified below, but InputArg is not updated appropriately. 4962 Expr *Input = (Expr *)InputArg.get(); 4963 QualType resultType; 4964 switch (Opc) { 4965 case UnaryOperator::PostInc: 4966 case UnaryOperator::PostDec: 4967 case UnaryOperator::OffsetOf: 4968 assert(false && "Invalid unary operator"); 4969 break; 4970 4971 case UnaryOperator::PreInc: 4972 case UnaryOperator::PreDec: 4973 resultType = CheckIncrementDecrementOperand(Input, OpLoc, 4974 Opc == UnaryOperator::PreInc); 4975 break; 4976 case UnaryOperator::AddrOf: 4977 resultType = CheckAddressOfOperand(Input, OpLoc); 4978 break; 4979 case UnaryOperator::Deref: 4980 DefaultFunctionArrayConversion(Input); 4981 resultType = CheckIndirectionOperand(Input, OpLoc); 4982 break; 4983 case UnaryOperator::Plus: 4984 case UnaryOperator::Minus: 4985 UsualUnaryConversions(Input); 4986 resultType = Input->getType(); 4987 if (resultType->isDependentType()) 4988 break; 4989 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 4990 break; 4991 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7 4992 resultType->isEnumeralType()) 4993 break; 4994 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6 4995 Opc == UnaryOperator::Plus && 4996 resultType->isPointerType()) 4997 break; 4998 4999 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 5000 << resultType << Input->getSourceRange()); 5001 case UnaryOperator::Not: // bitwise complement 5002 UsualUnaryConversions(Input); 5003 resultType = Input->getType(); 5004 if (resultType->isDependentType()) 5005 break; 5006 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 5007 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 5008 // C99 does not support '~' for complex conjugation. 5009 Diag(OpLoc, diag::ext_integer_complement_complex) 5010 << resultType << Input->getSourceRange(); 5011 else if (!resultType->isIntegerType()) 5012 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 5013 << resultType << Input->getSourceRange()); 5014 break; 5015 case UnaryOperator::LNot: // logical negation 5016 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 5017 DefaultFunctionArrayConversion(Input); 5018 resultType = Input->getType(); 5019 if (resultType->isDependentType()) 5020 break; 5021 if (!resultType->isScalarType()) // C99 6.5.3.3p1 5022 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 5023 << resultType << Input->getSourceRange()); 5024 // LNot always has type int. C99 6.5.3.3p5. 5025 // In C++, it's bool. C++ 5.3.1p8 5026 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy; 5027 break; 5028 case UnaryOperator::Real: 5029 case UnaryOperator::Imag: 5030 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real); 5031 break; 5032 case UnaryOperator::Extension: 5033 resultType = Input->getType(); 5034 break; 5035 } 5036 if (resultType.isNull()) 5037 return ExprError(); 5038 5039 InputArg.release(); 5040 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc)); 5041 } 5042 5043 // Unary Operators. 'Tok' is the token for the operator. 5044 Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 5045 tok::TokenKind Op, ExprArg input) { 5046 Expr *Input = (Expr*)input.get(); 5047 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op); 5048 5049 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) { 5050 // Find all of the overloaded operators visible from this 5051 // point. We perform both an operator-name lookup from the local 5052 // scope and an argument-dependent lookup based on the types of 5053 // the arguments. 5054 FunctionSet Functions; 5055 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 5056 if (OverOp != OO_None) { 5057 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 5058 Functions); 5059 DeclarationName OpName 5060 = Context.DeclarationNames.getCXXOperatorName(OverOp); 5061 ArgumentDependentLookup(OpName, &Input, 1, Functions); 5062 } 5063 5064 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input)); 5065 } 5066 5067 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input)); 5068 } 5069 5070 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 5071 Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, 5072 SourceLocation LabLoc, 5073 IdentifierInfo *LabelII) { 5074 // Look up the record for this label identifier. 5075 LabelStmt *&LabelDecl = getLabelMap()[LabelII]; 5076 5077 // If we haven't seen this label yet, create a forward reference. It 5078 // will be validated and/or cleaned up in ActOnFinishFunctionBody. 5079 if (LabelDecl == 0) 5080 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0); 5081 5082 // Create the AST node. The address of a label always has type 'void*'. 5083 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl, 5084 Context.getPointerType(Context.VoidTy))); 5085 } 5086 5087 Sema::OwningExprResult 5088 Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt, 5089 SourceLocation RPLoc) { // "({..})" 5090 Stmt *SubStmt = static_cast<Stmt*>(substmt.get()); 5091 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 5092 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 5093 5094 bool isFileScope = getCurFunctionOrMethodDecl() == 0; 5095 if (isFileScope) 5096 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope)); 5097 5098 // FIXME: there are a variety of strange constraints to enforce here, for 5099 // example, it is not possible to goto into a stmt expression apparently. 5100 // More semantic analysis is needed. 5101 5102 // If there are sub stmts in the compound stmt, take the type of the last one 5103 // as the type of the stmtexpr. 5104 QualType Ty = Context.VoidTy; 5105 5106 if (!Compound->body_empty()) { 5107 Stmt *LastStmt = Compound->body_back(); 5108 // If LastStmt is a label, skip down through into the body. 5109 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) 5110 LastStmt = Label->getSubStmt(); 5111 5112 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) 5113 Ty = LastExpr->getType(); 5114 } 5115 5116 // FIXME: Check that expression type is complete/non-abstract; statement 5117 // expressions are not lvalues. 5118 5119 substmt.release(); 5120 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc)); 5121 } 5122 5123 Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 5124 SourceLocation BuiltinLoc, 5125 SourceLocation TypeLoc, 5126 TypeTy *argty, 5127 OffsetOfComponent *CompPtr, 5128 unsigned NumComponents, 5129 SourceLocation RPLoc) { 5130 // FIXME: This function leaks all expressions in the offset components on 5131 // error. 5132 QualType ArgTy = QualType::getFromOpaquePtr(argty); 5133 assert(!ArgTy.isNull() && "Missing type argument!"); 5134 5135 bool Dependent = ArgTy->isDependentType(); 5136 5137 // We must have at least one component that refers to the type, and the first 5138 // one is known to be a field designator. Verify that the ArgTy represents 5139 // a struct/union/class. 5140 if (!Dependent && !ArgTy->isRecordType()) 5141 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy); 5142 5143 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable 5144 // with an incomplete type would be illegal. 5145 5146 // Otherwise, create a null pointer as the base, and iteratively process 5147 // the offsetof designators. 5148 QualType ArgTyPtr = Context.getPointerType(ArgTy); 5149 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr); 5150 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref, 5151 ArgTy, SourceLocation()); 5152 5153 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 5154 // GCC extension, diagnose them. 5155 // FIXME: This diagnostic isn't actually visible because the location is in 5156 // a system header! 5157 if (NumComponents != 1) 5158 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 5159 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); 5160 5161 if (!Dependent) { 5162 bool DidWarnAboutNonPOD = false; 5163 5164 // FIXME: Dependent case loses a lot of information here. And probably 5165 // leaks like a sieve. 5166 for (unsigned i = 0; i != NumComponents; ++i) { 5167 const OffsetOfComponent &OC = CompPtr[i]; 5168 if (OC.isBrackets) { 5169 // Offset of an array sub-field. TODO: Should we allow vector elements? 5170 const ArrayType *AT = Context.getAsArrayType(Res->getType()); 5171 if (!AT) { 5172 Res->Destroy(Context); 5173 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 5174 << Res->getType()); 5175 } 5176 5177 // FIXME: C++: Verify that operator[] isn't overloaded. 5178 5179 // Promote the array so it looks more like a normal array subscript 5180 // expression. 5181 DefaultFunctionArrayConversion(Res); 5182 5183 // C99 6.5.2.1p1 5184 Expr *Idx = static_cast<Expr*>(OC.U.E); 5185 // FIXME: Leaks Res 5186 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType()) 5187 return ExprError(Diag(Idx->getLocStart(), 5188 diag::err_typecheck_subscript_not_integer) 5189 << Idx->getSourceRange()); 5190 5191 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(), 5192 OC.LocEnd); 5193 continue; 5194 } 5195 5196 const RecordType *RC = Res->getType()->getAsRecordType(); 5197 if (!RC) { 5198 Res->Destroy(Context); 5199 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 5200 << Res->getType()); 5201 } 5202 5203 // Get the decl corresponding to this. 5204 RecordDecl *RD = RC->getDecl(); 5205 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 5206 if (!CRD->isPOD() && !DidWarnAboutNonPOD) { 5207 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type) 5208 << SourceRange(CompPtr[0].LocStart, OC.LocEnd) 5209 << Res->getType()); 5210 DidWarnAboutNonPOD = true; 5211 } 5212 } 5213 5214 FieldDecl *MemberDecl 5215 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo, 5216 LookupMemberName) 5217 .getAsDecl()); 5218 // FIXME: Leaks Res 5219 if (!MemberDecl) 5220 return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member) 5221 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd)); 5222 5223 // FIXME: C++: Verify that MemberDecl isn't a static field. 5224 // FIXME: Verify that MemberDecl isn't a bitfield. 5225 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) { 5226 Res = BuildAnonymousStructUnionMemberReference( 5227 SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>(); 5228 } else { 5229 // MemberDecl->getType() doesn't get the right qualifiers, but it 5230 // doesn't matter here. 5231 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd, 5232 MemberDecl->getType().getNonReferenceType()); 5233 } 5234 } 5235 } 5236 5237 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf, 5238 Context.getSizeType(), BuiltinLoc)); 5239 } 5240 5241 5242 Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc, 5243 TypeTy *arg1,TypeTy *arg2, 5244 SourceLocation RPLoc) { 5245 QualType argT1 = QualType::getFromOpaquePtr(arg1); 5246 QualType argT2 = QualType::getFromOpaquePtr(arg2); 5247 5248 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)"); 5249 5250 if (getLangOptions().CPlusPlus) { 5251 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus) 5252 << SourceRange(BuiltinLoc, RPLoc); 5253 return ExprError(); 5254 } 5255 5256 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, 5257 argT1, argT2, RPLoc)); 5258 } 5259 5260 Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 5261 ExprArg cond, 5262 ExprArg expr1, ExprArg expr2, 5263 SourceLocation RPLoc) { 5264 Expr *CondExpr = static_cast<Expr*>(cond.get()); 5265 Expr *LHSExpr = static_cast<Expr*>(expr1.get()); 5266 Expr *RHSExpr = static_cast<Expr*>(expr2.get()); 5267 5268 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 5269 5270 QualType resType; 5271 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 5272 resType = Context.DependentTy; 5273 } else { 5274 // The conditional expression is required to be a constant expression. 5275 llvm::APSInt condEval(32); 5276 SourceLocation ExpLoc; 5277 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc)) 5278 return ExprError(Diag(ExpLoc, 5279 diag::err_typecheck_choose_expr_requires_constant) 5280 << CondExpr->getSourceRange()); 5281 5282 // If the condition is > zero, then the AST type is the same as the LSHExpr. 5283 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType(); 5284 } 5285 5286 cond.release(); expr1.release(); expr2.release(); 5287 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 5288 resType, RPLoc)); 5289 } 5290 5291 //===----------------------------------------------------------------------===// 5292 // Clang Extensions. 5293 //===----------------------------------------------------------------------===// 5294 5295 /// ActOnBlockStart - This callback is invoked when a block literal is started. 5296 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) { 5297 // Analyze block parameters. 5298 BlockSemaInfo *BSI = new BlockSemaInfo(); 5299 5300 // Add BSI to CurBlock. 5301 BSI->PrevBlockInfo = CurBlock; 5302 CurBlock = BSI; 5303 5304 BSI->ReturnType = QualType(); 5305 BSI->TheScope = BlockScope; 5306 BSI->hasBlockDeclRefExprs = false; 5307 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking; 5308 CurFunctionNeedsScopeChecking = false; 5309 5310 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc); 5311 PushDeclContext(BlockScope, BSI->TheDecl); 5312 } 5313 5314 void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) { 5315 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!"); 5316 5317 if (ParamInfo.getNumTypeObjects() == 0 5318 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) { 5319 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 5320 QualType T = GetTypeForDeclarator(ParamInfo, CurScope); 5321 5322 if (T->isArrayType()) { 5323 Diag(ParamInfo.getSourceRange().getBegin(), 5324 diag::err_block_returns_array); 5325 return; 5326 } 5327 5328 // The parameter list is optional, if there was none, assume (). 5329 if (!T->isFunctionType()) 5330 T = Context.getFunctionType(T, NULL, 0, 0, 0); 5331 5332 CurBlock->hasPrototype = true; 5333 CurBlock->isVariadic = false; 5334 // Check for a valid sentinel attribute on this block. 5335 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) { 5336 Diag(ParamInfo.getAttributes()->getLoc(), 5337 diag::warn_attribute_sentinel_not_variadic) << 1; 5338 // FIXME: remove the attribute. 5339 } 5340 QualType RetTy = T.getTypePtr()->getAsFunctionType()->getResultType(); 5341 5342 // Do not allow returning a objc interface by-value. 5343 if (RetTy->isObjCInterfaceType()) { 5344 Diag(ParamInfo.getSourceRange().getBegin(), 5345 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy; 5346 return; 5347 } 5348 return; 5349 } 5350 5351 // Analyze arguments to block. 5352 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function && 5353 "Not a function declarator!"); 5354 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun; 5355 5356 CurBlock->hasPrototype = FTI.hasPrototype; 5357 CurBlock->isVariadic = true; 5358 5359 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes 5360 // no arguments, not a function that takes a single void argument. 5361 if (FTI.hasPrototype && 5362 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 5363 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&& 5364 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) { 5365 // empty arg list, don't push any params. 5366 CurBlock->isVariadic = false; 5367 } else if (FTI.hasPrototype) { 5368 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) 5369 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>()); 5370 CurBlock->isVariadic = FTI.isVariadic; 5371 } 5372 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(), 5373 CurBlock->Params.size()); 5374 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic); 5375 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 5376 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(), 5377 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) 5378 // If this has an identifier, add it to the scope stack. 5379 if ((*AI)->getIdentifier()) 5380 PushOnScopeChains(*AI, CurBlock->TheScope); 5381 5382 // Check for a valid sentinel attribute on this block. 5383 if (!CurBlock->isVariadic && 5384 CurBlock->TheDecl->getAttr<SentinelAttr>()) { 5385 Diag(ParamInfo.getAttributes()->getLoc(), 5386 diag::warn_attribute_sentinel_not_variadic) << 1; 5387 // FIXME: remove the attribute. 5388 } 5389 5390 // Analyze the return type. 5391 QualType T = GetTypeForDeclarator(ParamInfo, CurScope); 5392 QualType RetTy = T->getAsFunctionType()->getResultType(); 5393 5394 // Do not allow returning a objc interface by-value. 5395 if (RetTy->isObjCInterfaceType()) { 5396 Diag(ParamInfo.getSourceRange().getBegin(), 5397 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy; 5398 } else if (!RetTy->isDependentType()) 5399 CurBlock->ReturnType = RetTy; 5400 } 5401 5402 /// ActOnBlockError - If there is an error parsing a block, this callback 5403 /// is invoked to pop the information about the block from the action impl. 5404 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 5405 // Ensure that CurBlock is deleted. 5406 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock); 5407 5408 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking; 5409 5410 // Pop off CurBlock, handle nested blocks. 5411 PopDeclContext(); 5412 CurBlock = CurBlock->PrevBlockInfo; 5413 // FIXME: Delete the ParmVarDecl objects as well??? 5414 } 5415 5416 /// ActOnBlockStmtExpr - This is called when the body of a block statement 5417 /// literal was successfully completed. ^(int x){...} 5418 Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 5419 StmtArg body, Scope *CurScope) { 5420 // If blocks are disabled, emit an error. 5421 if (!LangOpts.Blocks) 5422 Diag(CaretLoc, diag::err_blocks_disable); 5423 5424 // Ensure that CurBlock is deleted. 5425 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock); 5426 5427 PopDeclContext(); 5428 5429 // Pop off CurBlock, handle nested blocks. 5430 CurBlock = CurBlock->PrevBlockInfo; 5431 5432 QualType RetTy = Context.VoidTy; 5433 if (!BSI->ReturnType.isNull()) 5434 RetTy = BSI->ReturnType; 5435 5436 llvm::SmallVector<QualType, 8> ArgTypes; 5437 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i) 5438 ArgTypes.push_back(BSI->Params[i]->getType()); 5439 5440 QualType BlockTy; 5441 if (!BSI->hasPrototype) 5442 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0); 5443 else 5444 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(), 5445 BSI->isVariadic, 0); 5446 5447 // FIXME: Check that return/parameter types are complete/non-abstract 5448 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end()); 5449 BlockTy = Context.getBlockPointerType(BlockTy); 5450 5451 // If needed, diagnose invalid gotos and switches in the block. 5452 if (CurFunctionNeedsScopeChecking) 5453 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get())); 5454 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking; 5455 5456 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>()); 5457 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy, 5458 BSI->hasBlockDeclRefExprs)); 5459 } 5460 5461 Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 5462 ExprArg expr, TypeTy *type, 5463 SourceLocation RPLoc) { 5464 QualType T = QualType::getFromOpaquePtr(type); 5465 Expr *E = static_cast<Expr*>(expr.get()); 5466 Expr *OrigExpr = E; 5467 5468 InitBuiltinVaListType(); 5469 5470 // Get the va_list type 5471 QualType VaListType = Context.getBuiltinVaListType(); 5472 if (VaListType->isArrayType()) { 5473 // Deal with implicit array decay; for example, on x86-64, 5474 // va_list is an array, but it's supposed to decay to 5475 // a pointer for va_arg. 5476 VaListType = Context.getArrayDecayedType(VaListType); 5477 // Make sure the input expression also decays appropriately. 5478 UsualUnaryConversions(E); 5479 } else { 5480 // Otherwise, the va_list argument must be an l-value because 5481 // it is modified by va_arg. 5482 if (!E->isTypeDependent() && 5483 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 5484 return ExprError(); 5485 } 5486 5487 if (!E->isTypeDependent() && 5488 !Context.hasSameType(VaListType, E->getType())) { 5489 return ExprError(Diag(E->getLocStart(), 5490 diag::err_first_argument_to_va_arg_not_of_type_va_list) 5491 << OrigExpr->getType() << E->getSourceRange()); 5492 } 5493 5494 // FIXME: Check that type is complete/non-abstract 5495 // FIXME: Warn if a non-POD type is passed in. 5496 5497 expr.release(); 5498 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), 5499 RPLoc)); 5500 } 5501 5502 Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 5503 // The type of __null will be int or long, depending on the size of 5504 // pointers on the target. 5505 QualType Ty; 5506 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth()) 5507 Ty = Context.IntTy; 5508 else 5509 Ty = Context.LongTy; 5510 5511 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc)); 5512 } 5513 5514 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 5515 SourceLocation Loc, 5516 QualType DstType, QualType SrcType, 5517 Expr *SrcExpr, const char *Flavor) { 5518 // Decode the result (notice that AST's are still created for extensions). 5519 bool isInvalid = false; 5520 unsigned DiagKind; 5521 switch (ConvTy) { 5522 default: assert(0 && "Unknown conversion type"); 5523 case Compatible: return false; 5524 case PointerToInt: 5525 DiagKind = diag::ext_typecheck_convert_pointer_int; 5526 break; 5527 case IntToPointer: 5528 DiagKind = diag::ext_typecheck_convert_int_pointer; 5529 break; 5530 case IncompatiblePointer: 5531 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 5532 break; 5533 case IncompatiblePointerSign: 5534 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 5535 break; 5536 case FunctionVoidPointer: 5537 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 5538 break; 5539 case CompatiblePointerDiscardsQualifiers: 5540 // If the qualifiers lost were because we were applying the 5541 // (deprecated) C++ conversion from a string literal to a char* 5542 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 5543 // Ideally, this check would be performed in 5544 // CheckPointerTypesForAssignment. However, that would require a 5545 // bit of refactoring (so that the second argument is an 5546 // expression, rather than a type), which should be done as part 5547 // of a larger effort to fix CheckPointerTypesForAssignment for 5548 // C++ semantics. 5549 if (getLangOptions().CPlusPlus && 5550 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 5551 return false; 5552 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 5553 break; 5554 case IntToBlockPointer: 5555 DiagKind = diag::err_int_to_block_pointer; 5556 break; 5557 case IncompatibleBlockPointer: 5558 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 5559 break; 5560 case IncompatibleObjCQualifiedId: 5561 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since 5562 // it can give a more specific diagnostic. 5563 DiagKind = diag::warn_incompatible_qualified_id; 5564 break; 5565 case IncompatibleVectors: 5566 DiagKind = diag::warn_incompatible_vectors; 5567 break; 5568 case Incompatible: 5569 DiagKind = diag::err_typecheck_convert_incompatible; 5570 isInvalid = true; 5571 break; 5572 } 5573 5574 Diag(Loc, DiagKind) << DstType << SrcType << Flavor 5575 << SrcExpr->getSourceRange(); 5576 return isInvalid; 5577 } 5578 5579 bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){ 5580 llvm::APSInt ICEResult; 5581 if (E->isIntegerConstantExpr(ICEResult, Context)) { 5582 if (Result) 5583 *Result = ICEResult; 5584 return false; 5585 } 5586 5587 Expr::EvalResult EvalResult; 5588 5589 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() || 5590 EvalResult.HasSideEffects) { 5591 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange(); 5592 5593 if (EvalResult.Diag) { 5594 // We only show the note if it's not the usual "invalid subexpression" 5595 // or if it's actually in a subexpression. 5596 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice || 5597 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens()) 5598 Diag(EvalResult.DiagLoc, EvalResult.Diag); 5599 } 5600 5601 return true; 5602 } 5603 5604 Diag(E->getExprLoc(), diag::ext_expr_not_ice) << 5605 E->getSourceRange(); 5606 5607 if (EvalResult.Diag && 5608 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored) 5609 Diag(EvalResult.DiagLoc, EvalResult.Diag); 5610 5611 if (Result) 5612 *Result = EvalResult.Val.getInt(); 5613 return false; 5614 } 5615 5616 Sema::ExpressionEvaluationContext 5617 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) { 5618 // Introduce a new set of potentially referenced declarations to the stack. 5619 if (NewContext == PotentiallyPotentiallyEvaluated) 5620 PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls()); 5621 5622 std::swap(ExprEvalContext, NewContext); 5623 return NewContext; 5624 } 5625 5626 void 5627 Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext, 5628 ExpressionEvaluationContext NewContext) { 5629 ExprEvalContext = NewContext; 5630 5631 if (OldContext == PotentiallyPotentiallyEvaluated) { 5632 // Mark any remaining declarations in the current position of the stack 5633 // as "referenced". If they were not meant to be referenced, semantic 5634 // analysis would have eliminated them (e.g., in ActOnCXXTypeId). 5635 PotentiallyReferencedDecls RemainingDecls; 5636 RemainingDecls.swap(PotentiallyReferencedDeclStack.back()); 5637 PotentiallyReferencedDeclStack.pop_back(); 5638 5639 for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(), 5640 IEnd = RemainingDecls.end(); 5641 I != IEnd; ++I) 5642 MarkDeclarationReferenced(I->first, I->second); 5643 } 5644 } 5645 5646 /// \brief Note that the given declaration was referenced in the source code. 5647 /// 5648 /// This routine should be invoke whenever a given declaration is referenced 5649 /// in the source code, and where that reference occurred. If this declaration 5650 /// reference means that the the declaration is used (C++ [basic.def.odr]p2, 5651 /// C99 6.9p3), then the declaration will be marked as used. 5652 /// 5653 /// \param Loc the location where the declaration was referenced. 5654 /// 5655 /// \param D the declaration that has been referenced by the source code. 5656 void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) { 5657 assert(D && "No declaration?"); 5658 5659 if (D->isUsed()) 5660 return; 5661 5662 // Mark a parameter declaration "used", regardless of whether we're in a 5663 // template or not. 5664 if (isa<ParmVarDecl>(D)) 5665 D->setUsed(true); 5666 5667 // Do not mark anything as "used" within a dependent context; wait for 5668 // an instantiation. 5669 if (CurContext->isDependentContext()) 5670 return; 5671 5672 switch (ExprEvalContext) { 5673 case Unevaluated: 5674 // We are in an expression that is not potentially evaluated; do nothing. 5675 return; 5676 5677 case PotentiallyEvaluated: 5678 // We are in a potentially-evaluated expression, so this declaration is 5679 // "used"; handle this below. 5680 break; 5681 5682 case PotentiallyPotentiallyEvaluated: 5683 // We are in an expression that may be potentially evaluated; queue this 5684 // declaration reference until we know whether the expression is 5685 // potentially evaluated. 5686 PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D)); 5687 return; 5688 } 5689 5690 // Note that this declaration has been used. 5691 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) { 5692 unsigned TypeQuals; 5693 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) { 5694 if (!Constructor->isUsed()) 5695 DefineImplicitDefaultConstructor(Loc, Constructor); 5696 } 5697 else if (Constructor->isImplicit() && 5698 Constructor->isCopyConstructor(Context, TypeQuals)) { 5699 if (!Constructor->isUsed()) 5700 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals); 5701 } 5702 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) { 5703 if (Destructor->isImplicit() && !Destructor->isUsed()) 5704 DefineImplicitDestructor(Loc, Destructor); 5705 5706 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) { 5707 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() && 5708 MethodDecl->getOverloadedOperator() == OO_Equal) { 5709 if (!MethodDecl->isUsed()) 5710 DefineImplicitOverloadedAssign(Loc, MethodDecl); 5711 } 5712 } 5713 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 5714 // Implicit instantiation of function templates and member functions of 5715 // class templates. 5716 if (!Function->getBody()) { 5717 // FIXME: distinguish between implicit instantiations of function 5718 // templates and explicit specializations (the latter don't get 5719 // instantiated, naturally). 5720 if (Function->getInstantiatedFromMemberFunction() || 5721 Function->getPrimaryTemplate()) 5722 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc)); 5723 } 5724 5725 5726 // FIXME: keep track of references to static functions 5727 Function->setUsed(true); 5728 return; 5729 } 5730 5731 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 5732 (void)Var; 5733 // FIXME: implicit template instantiation 5734 // FIXME: keep track of references to static data? 5735 D->setUsed(true); 5736 } 5737 } 5738 5739