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