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 "clang/Sema/SemaInternal.h" 15 #include "clang/Sema/Initialization.h" 16 #include "clang/Sema/Lookup.h" 17 #include "clang/Sema/AnalysisBasedWarnings.h" 18 #include "clang/AST/ASTContext.h" 19 #include "clang/AST/ASTMutationListener.h" 20 #include "clang/AST/CXXInheritance.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/DeclTemplate.h" 23 #include "clang/AST/EvaluatedExprVisitor.h" 24 #include "clang/AST/Expr.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/ExprObjC.h" 27 #include "clang/AST/RecursiveASTVisitor.h" 28 #include "clang/AST/TypeLoc.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/LiteralSupport.h" 33 #include "clang/Lex/Preprocessor.h" 34 #include "clang/Sema/DeclSpec.h" 35 #include "clang/Sema/Designator.h" 36 #include "clang/Sema/Scope.h" 37 #include "clang/Sema/ScopeInfo.h" 38 #include "clang/Sema/ParsedTemplate.h" 39 #include "clang/Sema/SemaFixItUtils.h" 40 #include "clang/Sema/Template.h" 41 using namespace clang; 42 using namespace sema; 43 44 /// \brief Determine whether the use of this declaration is valid, without 45 /// emitting diagnostics. 46 bool Sema::CanUseDecl(NamedDecl *D) { 47 // See if this is an auto-typed variable whose initializer we are parsing. 48 if (ParsingInitForAutoVars.count(D)) 49 return false; 50 51 // See if this is a deleted function. 52 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 53 if (FD->isDeleted()) 54 return false; 55 } 56 57 // See if this function is unavailable. 58 if (D->getAvailability() == AR_Unavailable && 59 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 60 return false; 61 62 return true; 63 } 64 65 static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S, 66 NamedDecl *D, SourceLocation Loc, 67 const ObjCInterfaceDecl *UnknownObjCClass) { 68 // See if this declaration is unavailable or deprecated. 69 std::string Message; 70 AvailabilityResult Result = D->getAvailability(&Message); 71 switch (Result) { 72 case AR_Available: 73 case AR_NotYetIntroduced: 74 break; 75 76 case AR_Deprecated: 77 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass); 78 break; 79 80 case AR_Unavailable: 81 if (S.getCurContextAvailability() != AR_Unavailable) { 82 if (Message.empty()) { 83 if (!UnknownObjCClass) 84 S.Diag(Loc, diag::err_unavailable) << D->getDeclName(); 85 else 86 S.Diag(Loc, diag::warn_unavailable_fwdclass_message) 87 << D->getDeclName(); 88 } 89 else 90 S.Diag(Loc, diag::err_unavailable_message) 91 << D->getDeclName() << Message; 92 S.Diag(D->getLocation(), diag::note_unavailable_here) 93 << isa<FunctionDecl>(D) << false; 94 } 95 break; 96 } 97 return Result; 98 } 99 100 /// \brief Determine whether the use of this declaration is valid, and 101 /// emit any corresponding diagnostics. 102 /// 103 /// This routine diagnoses various problems with referencing 104 /// declarations that can occur when using a declaration. For example, 105 /// it might warn if a deprecated or unavailable declaration is being 106 /// used, or produce an error (and return true) if a C++0x deleted 107 /// function is being used. 108 /// 109 /// \returns true if there was an error (this declaration cannot be 110 /// referenced), false otherwise. 111 /// 112 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 113 const ObjCInterfaceDecl *UnknownObjCClass) { 114 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) { 115 // If there were any diagnostics suppressed by template argument deduction, 116 // emit them now. 117 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator 118 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 119 if (Pos != SuppressedDiagnostics.end()) { 120 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second; 121 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I) 122 Diag(Suppressed[I].first, Suppressed[I].second); 123 124 // Clear out the list of suppressed diagnostics, so that we don't emit 125 // them again for this specialization. However, we don't obsolete this 126 // entry from the table, because we want to avoid ever emitting these 127 // diagnostics again. 128 Suppressed.clear(); 129 } 130 } 131 132 // See if this is an auto-typed variable whose initializer we are parsing. 133 if (ParsingInitForAutoVars.count(D)) { 134 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 135 << D->getDeclName(); 136 return true; 137 } 138 139 // See if this is a deleted function. 140 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 141 if (FD->isDeleted()) { 142 Diag(Loc, diag::err_deleted_function_use); 143 Diag(D->getLocation(), diag::note_unavailable_here) << 1 << true; 144 return true; 145 } 146 } 147 AvailabilityResult Result = 148 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass); 149 150 // Warn if this is used but marked unused. 151 if (D->hasAttr<UnusedAttr>()) 152 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 153 // For available enumerator, it will become unavailable/deprecated 154 // if its enum declaration is as such. 155 if (Result == AR_Available) 156 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 157 const DeclContext *DC = ECD->getDeclContext(); 158 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC)) 159 DiagnoseAvailabilityOfDecl(*this, 160 const_cast< EnumDecl *>(TheEnumDecl), 161 Loc, UnknownObjCClass); 162 } 163 return false; 164 } 165 166 /// \brief Retrieve the message suffix that should be added to a 167 /// diagnostic complaining about the given function being deleted or 168 /// unavailable. 169 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 170 // FIXME: C++0x implicitly-deleted special member functions could be 171 // detected here so that we could improve diagnostics to say, e.g., 172 // "base class 'A' had a deleted copy constructor". 173 if (FD->isDeleted()) 174 return std::string(); 175 176 std::string Message; 177 if (FD->getAvailability(&Message)) 178 return ": " + Message; 179 180 return std::string(); 181 } 182 183 /// DiagnoseSentinelCalls - This routine checks whether a call or 184 /// message-send is to a declaration with the sentinel attribute, and 185 /// if so, it checks that the requirements of the sentinel are 186 /// satisfied. 187 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 188 Expr **args, unsigned numArgs) { 189 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 190 if (!attr) 191 return; 192 193 // The number of formal parameters of the declaration. 194 unsigned numFormalParams; 195 196 // The kind of declaration. This is also an index into a %select in 197 // the diagnostic. 198 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 199 200 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 201 numFormalParams = MD->param_size(); 202 calleeType = CT_Method; 203 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 204 numFormalParams = FD->param_size(); 205 calleeType = CT_Function; 206 } else if (isa<VarDecl>(D)) { 207 QualType type = cast<ValueDecl>(D)->getType(); 208 const FunctionType *fn = 0; 209 if (const PointerType *ptr = type->getAs<PointerType>()) { 210 fn = ptr->getPointeeType()->getAs<FunctionType>(); 211 if (!fn) return; 212 calleeType = CT_Function; 213 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 214 fn = ptr->getPointeeType()->castAs<FunctionType>(); 215 calleeType = CT_Block; 216 } else { 217 return; 218 } 219 220 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 221 numFormalParams = proto->getNumArgs(); 222 } else { 223 numFormalParams = 0; 224 } 225 } else { 226 return; 227 } 228 229 // "nullPos" is the number of formal parameters at the end which 230 // effectively count as part of the variadic arguments. This is 231 // useful if you would prefer to not have *any* formal parameters, 232 // but the language forces you to have at least one. 233 unsigned nullPos = attr->getNullPos(); 234 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 235 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 236 237 // The number of arguments which should follow the sentinel. 238 unsigned numArgsAfterSentinel = attr->getSentinel(); 239 240 // If there aren't enough arguments for all the formal parameters, 241 // the sentinel, and the args after the sentinel, complain. 242 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) { 243 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 244 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType; 245 return; 246 } 247 248 // Otherwise, find the sentinel expression. 249 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1]; 250 if (!sentinelExpr) return; 251 if (sentinelExpr->isValueDependent()) return; 252 253 // nullptr_t is always treated as null. 254 if (sentinelExpr->getType()->isNullPtrType()) return; 255 256 if (sentinelExpr->getType()->isAnyPointerType() && 257 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context, 258 Expr::NPC_ValueDependentIsNull)) 259 return; 260 261 // Unfortunately, __null has type 'int'. 262 if (isa<GNUNullExpr>(sentinelExpr)) return; 263 264 // Pick a reasonable string to insert. Optimistically use 'nil' or 265 // 'NULL' if those are actually defined in the context. Only use 266 // 'nil' for ObjC methods, where it's much more likely that the 267 // variadic arguments form a list of object pointers. 268 SourceLocation MissingNilLoc 269 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd()); 270 std::string NullValue; 271 if (calleeType == CT_Method && 272 PP.getIdentifierInfo("nil")->hasMacroDefinition()) 273 NullValue = "nil"; 274 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition()) 275 NullValue = "NULL"; 276 else 277 NullValue = "(void*) 0"; 278 279 if (MissingNilLoc.isInvalid()) 280 Diag(Loc, diag::warn_missing_sentinel) << calleeType; 281 else 282 Diag(MissingNilLoc, diag::warn_missing_sentinel) 283 << calleeType 284 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 285 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType; 286 } 287 288 SourceRange Sema::getExprRange(Expr *E) const { 289 return E ? E->getSourceRange() : SourceRange(); 290 } 291 292 //===----------------------------------------------------------------------===// 293 // Standard Promotions and Conversions 294 //===----------------------------------------------------------------------===// 295 296 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 297 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) { 298 // Handle any placeholder expressions which made it here. 299 if (E->getType()->isPlaceholderType()) { 300 ExprResult result = CheckPlaceholderExpr(E); 301 if (result.isInvalid()) return ExprError(); 302 E = result.take(); 303 } 304 305 QualType Ty = E->getType(); 306 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 307 308 if (Ty->isFunctionType()) 309 E = ImpCastExprToType(E, Context.getPointerType(Ty), 310 CK_FunctionToPointerDecay).take(); 311 else if (Ty->isArrayType()) { 312 // In C90 mode, arrays only promote to pointers if the array expression is 313 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 314 // type 'array of type' is converted to an expression that has type 'pointer 315 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 316 // that has type 'array of type' ...". The relevant change is "an lvalue" 317 // (C90) to "an expression" (C99). 318 // 319 // C++ 4.2p1: 320 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 321 // T" can be converted to an rvalue of type "pointer to T". 322 // 323 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue()) 324 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 325 CK_ArrayToPointerDecay).take(); 326 } 327 return Owned(E); 328 } 329 330 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 331 // Check to see if we are dereferencing a null pointer. If so, 332 // and if not volatile-qualified, this is undefined behavior that the 333 // optimizer will delete, so warn about it. People sometimes try to use this 334 // to get a deterministic trap and are surprised by clang's behavior. This 335 // only handles the pattern "*null", which is a very syntactic check. 336 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 337 if (UO->getOpcode() == UO_Deref && 338 UO->getSubExpr()->IgnoreParenCasts()-> 339 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 340 !UO->getType().isVolatileQualified()) { 341 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 342 S.PDiag(diag::warn_indirection_through_null) 343 << UO->getSubExpr()->getSourceRange()); 344 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 345 S.PDiag(diag::note_indirection_through_null)); 346 } 347 } 348 349 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 350 // Handle any placeholder expressions which made it here. 351 if (E->getType()->isPlaceholderType()) { 352 ExprResult result = CheckPlaceholderExpr(E); 353 if (result.isInvalid()) return ExprError(); 354 E = result.take(); 355 } 356 357 // C++ [conv.lval]p1: 358 // A glvalue of a non-function, non-array type T can be 359 // converted to a prvalue. 360 if (!E->isGLValue()) return Owned(E); 361 362 QualType T = E->getType(); 363 assert(!T.isNull() && "r-value conversion on typeless expression?"); 364 365 // We can't do lvalue-to-rvalue on atomics yet. 366 if (T->isAtomicType()) 367 return Owned(E); 368 369 // We don't want to throw lvalue-to-rvalue casts on top of 370 // expressions of certain types in C++. 371 if (getLangOptions().CPlusPlus && 372 (E->getType() == Context.OverloadTy || 373 T->isDependentType() || 374 T->isRecordType())) 375 return Owned(E); 376 377 // The C standard is actually really unclear on this point, and 378 // DR106 tells us what the result should be but not why. It's 379 // generally best to say that void types just doesn't undergo 380 // lvalue-to-rvalue at all. Note that expressions of unqualified 381 // 'void' type are never l-values, but qualified void can be. 382 if (T->isVoidType()) 383 return Owned(E); 384 385 CheckForNullPointerDereference(*this, E); 386 387 // C++ [conv.lval]p1: 388 // [...] If T is a non-class type, the type of the prvalue is the 389 // cv-unqualified version of T. Otherwise, the type of the 390 // rvalue is T. 391 // 392 // C99 6.3.2.1p2: 393 // If the lvalue has qualified type, the value has the unqualified 394 // version of the type of the lvalue; otherwise, the value has the 395 // type of the lvalue. 396 if (T.hasQualifiers()) 397 T = T.getUnqualifiedType(); 398 399 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, 400 E, 0, VK_RValue)); 401 402 return Res; 403 } 404 405 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) { 406 ExprResult Res = DefaultFunctionArrayConversion(E); 407 if (Res.isInvalid()) 408 return ExprError(); 409 Res = DefaultLvalueConversion(Res.take()); 410 if (Res.isInvalid()) 411 return ExprError(); 412 return move(Res); 413 } 414 415 416 /// UsualUnaryConversions - Performs various conversions that are common to most 417 /// operators (C99 6.3). The conversions of array and function types are 418 /// sometimes suppressed. For example, the array->pointer conversion doesn't 419 /// apply if the array is an argument to the sizeof or address (&) operators. 420 /// In these instances, this routine should *not* be called. 421 ExprResult Sema::UsualUnaryConversions(Expr *E) { 422 // First, convert to an r-value. 423 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 424 if (Res.isInvalid()) 425 return Owned(E); 426 E = Res.take(); 427 428 QualType Ty = E->getType(); 429 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 430 431 // Half FP is a bit different: it's a storage-only type, meaning that any 432 // "use" of it should be promoted to float. 433 if (Ty->isHalfType()) 434 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast); 435 436 // Try to perform integral promotions if the object has a theoretically 437 // promotable type. 438 if (Ty->isIntegralOrUnscopedEnumerationType()) { 439 // C99 6.3.1.1p2: 440 // 441 // The following may be used in an expression wherever an int or 442 // unsigned int may be used: 443 // - an object or expression with an integer type whose integer 444 // conversion rank is less than or equal to the rank of int 445 // and unsigned int. 446 // - A bit-field of type _Bool, int, signed int, or unsigned int. 447 // 448 // If an int can represent all values of the original type, the 449 // value is converted to an int; otherwise, it is converted to an 450 // unsigned int. These are called the integer promotions. All 451 // other types are unchanged by the integer promotions. 452 453 QualType PTy = Context.isPromotableBitField(E); 454 if (!PTy.isNull()) { 455 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take(); 456 return Owned(E); 457 } 458 if (Ty->isPromotableIntegerType()) { 459 QualType PT = Context.getPromotedIntegerType(Ty); 460 E = ImpCastExprToType(E, PT, CK_IntegralCast).take(); 461 return Owned(E); 462 } 463 } 464 return Owned(E); 465 } 466 467 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 468 /// do not have a prototype. Arguments that have type float are promoted to 469 /// double. All other argument types are converted by UsualUnaryConversions(). 470 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 471 QualType Ty = E->getType(); 472 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 473 474 ExprResult Res = UsualUnaryConversions(E); 475 if (Res.isInvalid()) 476 return Owned(E); 477 E = Res.take(); 478 479 // If this is a 'float' (CVR qualified or typedef) promote to double. 480 if (Ty->isSpecificBuiltinType(BuiltinType::Float)) 481 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take(); 482 483 // C++ performs lvalue-to-rvalue conversion as a default argument 484 // promotion, even on class types, but note: 485 // C++11 [conv.lval]p2: 486 // When an lvalue-to-rvalue conversion occurs in an unevaluated 487 // operand or a subexpression thereof the value contained in the 488 // referenced object is not accessed. Otherwise, if the glvalue 489 // has a class type, the conversion copy-initializes a temporary 490 // of type T from the glvalue and the result of the conversion 491 // is a prvalue for the temporary. 492 // FIXME: add some way to gate this entire thing for correctness in 493 // potentially potentially evaluated contexts. 494 if (getLangOptions().CPlusPlus && E->isGLValue() && 495 ExprEvalContexts.back().Context != Unevaluated) { 496 ExprResult Temp = PerformCopyInitialization( 497 InitializedEntity::InitializeTemporary(E->getType()), 498 E->getExprLoc(), 499 Owned(E)); 500 if (Temp.isInvalid()) 501 return ExprError(); 502 E = Temp.get(); 503 } 504 505 return Owned(E); 506 } 507 508 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 509 /// will warn if the resulting type is not a POD type, and rejects ObjC 510 /// interfaces passed by value. 511 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 512 FunctionDecl *FDecl) { 513 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 514 // Strip the unbridged-cast placeholder expression off, if applicable. 515 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 516 (CT == VariadicMethod || 517 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 518 E = stripARCUnbridgedCast(E); 519 520 // Otherwise, do normal placeholder checking. 521 } else { 522 ExprResult ExprRes = CheckPlaceholderExpr(E); 523 if (ExprRes.isInvalid()) 524 return ExprError(); 525 E = ExprRes.take(); 526 } 527 } 528 529 ExprResult ExprRes = DefaultArgumentPromotion(E); 530 if (ExprRes.isInvalid()) 531 return ExprError(); 532 E = ExprRes.take(); 533 534 // Don't allow one to pass an Objective-C interface to a vararg. 535 if (E->getType()->isObjCObjectType() && 536 DiagRuntimeBehavior(E->getLocStart(), 0, 537 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 538 << E->getType() << CT)) 539 return ExprError(); 540 541 // Complain about passing non-POD types through varargs. However, don't 542 // perform this check for incomplete types, which we can get here when we're 543 // in an unevaluated context. 544 if (!E->getType()->isIncompleteType() && !E->getType().isPODType(Context)) { 545 // C++0x [expr.call]p7: 546 // Passing a potentially-evaluated argument of class type (Clause 9) 547 // having a non-trivial copy constructor, a non-trivial move constructor, 548 // or a non-trivial destructor, with no corresponding parameter, 549 // is conditionally-supported with implementation-defined semantics. 550 bool TrivialEnough = false; 551 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) { 552 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) { 553 if (Record->hasTrivialCopyConstructor() && 554 Record->hasTrivialMoveConstructor() && 555 Record->hasTrivialDestructor()) { 556 DiagRuntimeBehavior(E->getLocStart(), 0, 557 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 558 << E->getType() << CT); 559 TrivialEnough = true; 560 } 561 } 562 } 563 564 if (!TrivialEnough && 565 getLangOptions().ObjCAutoRefCount && 566 E->getType()->isObjCLifetimeType()) 567 TrivialEnough = true; 568 569 if (TrivialEnough) { 570 // Nothing to diagnose. This is okay. 571 } else if (DiagRuntimeBehavior(E->getLocStart(), 0, 572 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 573 << getLangOptions().CPlusPlus0x << E->getType() 574 << CT)) { 575 // Turn this into a trap. 576 CXXScopeSpec SS; 577 UnqualifiedId Name; 578 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 579 E->getLocStart()); 580 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false); 581 if (TrapFn.isInvalid()) 582 return ExprError(); 583 584 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(), 585 MultiExprArg(), E->getLocEnd()); 586 if (Call.isInvalid()) 587 return ExprError(); 588 589 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 590 Call.get(), E); 591 if (Comma.isInvalid()) 592 return ExprError(); 593 E = Comma.get(); 594 } 595 } 596 597 return Owned(E); 598 } 599 600 /// \brief Converts an integer to complex float type. Helper function of 601 /// UsualArithmeticConversions() 602 /// 603 /// \return false if the integer expression is an integer type and is 604 /// successfully converted to the complex type. 605 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 606 ExprResult &ComplexExpr, 607 QualType IntTy, 608 QualType ComplexTy, 609 bool SkipCast) { 610 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 611 if (SkipCast) return false; 612 if (IntTy->isIntegerType()) { 613 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 614 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating); 615 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy, 616 CK_FloatingRealToComplex); 617 } else { 618 assert(IntTy->isComplexIntegerType()); 619 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy, 620 CK_IntegralComplexToFloatingComplex); 621 } 622 return false; 623 } 624 625 /// \brief Takes two complex float types and converts them to the same type. 626 /// Helper function of UsualArithmeticConversions() 627 static QualType 628 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS, 629 ExprResult &RHS, QualType LHSType, 630 QualType RHSType, 631 bool IsCompAssign) { 632 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 633 634 if (order < 0) { 635 // _Complex float -> _Complex double 636 if (!IsCompAssign) 637 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast); 638 return RHSType; 639 } 640 if (order > 0) 641 // _Complex float -> _Complex double 642 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast); 643 return LHSType; 644 } 645 646 /// \brief Converts otherExpr to complex float and promotes complexExpr if 647 /// necessary. Helper function of UsualArithmeticConversions() 648 static QualType handleOtherComplexFloatConversion(Sema &S, 649 ExprResult &ComplexExpr, 650 ExprResult &OtherExpr, 651 QualType ComplexTy, 652 QualType OtherTy, 653 bool ConvertComplexExpr, 654 bool ConvertOtherExpr) { 655 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy); 656 657 // If just the complexExpr is complex, the otherExpr needs to be converted, 658 // and the complexExpr might need to be promoted. 659 if (order > 0) { // complexExpr is wider 660 // float -> _Complex double 661 if (ConvertOtherExpr) { 662 QualType fp = cast<ComplexType>(ComplexTy)->getElementType(); 663 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast); 664 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy, 665 CK_FloatingRealToComplex); 666 } 667 return ComplexTy; 668 } 669 670 // otherTy is at least as wide. Find its corresponding complex type. 671 QualType result = (order == 0 ? ComplexTy : 672 S.Context.getComplexType(OtherTy)); 673 674 // double -> _Complex double 675 if (ConvertOtherExpr) 676 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result, 677 CK_FloatingRealToComplex); 678 679 // _Complex float -> _Complex double 680 if (ConvertComplexExpr && order < 0) 681 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result, 682 CK_FloatingComplexCast); 683 684 return result; 685 } 686 687 /// \brief Handle arithmetic conversion with complex types. Helper function of 688 /// UsualArithmeticConversions() 689 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 690 ExprResult &RHS, QualType LHSType, 691 QualType RHSType, 692 bool IsCompAssign) { 693 // if we have an integer operand, the result is the complex type. 694 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 695 /*skipCast*/false)) 696 return LHSType; 697 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 698 /*skipCast*/IsCompAssign)) 699 return RHSType; 700 701 // This handles complex/complex, complex/float, or float/complex. 702 // When both operands are complex, the shorter operand is converted to the 703 // type of the longer, and that is the type of the result. This corresponds 704 // to what is done when combining two real floating-point operands. 705 // The fun begins when size promotion occur across type domains. 706 // From H&S 6.3.4: When one operand is complex and the other is a real 707 // floating-point type, the less precise type is converted, within it's 708 // real or complex domain, to the precision of the other type. For example, 709 // when combining a "long double" with a "double _Complex", the 710 // "double _Complex" is promoted to "long double _Complex". 711 712 bool LHSComplexFloat = LHSType->isComplexType(); 713 bool RHSComplexFloat = RHSType->isComplexType(); 714 715 // If both are complex, just cast to the more precise type. 716 if (LHSComplexFloat && RHSComplexFloat) 717 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS, 718 LHSType, RHSType, 719 IsCompAssign); 720 721 // If only one operand is complex, promote it if necessary and convert the 722 // other operand to complex. 723 if (LHSComplexFloat) 724 return handleOtherComplexFloatConversion( 725 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign, 726 /*convertOtherExpr*/ true); 727 728 assert(RHSComplexFloat); 729 return handleOtherComplexFloatConversion( 730 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true, 731 /*convertOtherExpr*/ !IsCompAssign); 732 } 733 734 /// \brief Hande arithmetic conversion from integer to float. Helper function 735 /// of UsualArithmeticConversions() 736 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 737 ExprResult &IntExpr, 738 QualType FloatTy, QualType IntTy, 739 bool ConvertFloat, bool ConvertInt) { 740 if (IntTy->isIntegerType()) { 741 if (ConvertInt) 742 // Convert intExpr to the lhs floating point type. 743 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy, 744 CK_IntegralToFloating); 745 return FloatTy; 746 } 747 748 // Convert both sides to the appropriate complex float. 749 assert(IntTy->isComplexIntegerType()); 750 QualType result = S.Context.getComplexType(FloatTy); 751 752 // _Complex int -> _Complex float 753 if (ConvertInt) 754 IntExpr = S.ImpCastExprToType(IntExpr.take(), result, 755 CK_IntegralComplexToFloatingComplex); 756 757 // float -> _Complex float 758 if (ConvertFloat) 759 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result, 760 CK_FloatingRealToComplex); 761 762 return result; 763 } 764 765 /// \brief Handle arithmethic conversion with floating point types. Helper 766 /// function of UsualArithmeticConversions() 767 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 768 ExprResult &RHS, QualType LHSType, 769 QualType RHSType, bool IsCompAssign) { 770 bool LHSFloat = LHSType->isRealFloatingType(); 771 bool RHSFloat = RHSType->isRealFloatingType(); 772 773 // If we have two real floating types, convert the smaller operand 774 // to the bigger result. 775 if (LHSFloat && RHSFloat) { 776 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 777 if (order > 0) { 778 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast); 779 return LHSType; 780 } 781 782 assert(order < 0 && "illegal float comparison"); 783 if (!IsCompAssign) 784 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast); 785 return RHSType; 786 } 787 788 if (LHSFloat) 789 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 790 /*convertFloat=*/!IsCompAssign, 791 /*convertInt=*/ true); 792 assert(RHSFloat); 793 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 794 /*convertInt=*/ true, 795 /*convertFloat=*/!IsCompAssign); 796 } 797 798 /// \brief Handle conversions with GCC complex int extension. Helper function 799 /// of UsualArithmeticConversions() 800 // FIXME: if the operands are (int, _Complex long), we currently 801 // don't promote the complex. Also, signedness? 802 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 803 ExprResult &RHS, QualType LHSType, 804 QualType RHSType, 805 bool IsCompAssign) { 806 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 807 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 808 809 if (LHSComplexInt && RHSComplexInt) { 810 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(), 811 RHSComplexInt->getElementType()); 812 assert(order && "inequal types with equal element ordering"); 813 if (order > 0) { 814 // _Complex int -> _Complex long 815 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast); 816 return LHSType; 817 } 818 819 if (!IsCompAssign) 820 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast); 821 return RHSType; 822 } 823 824 if (LHSComplexInt) { 825 // int -> _Complex int 826 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex); 827 return LHSType; 828 } 829 830 assert(RHSComplexInt); 831 // int -> _Complex int 832 if (!IsCompAssign) 833 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex); 834 return RHSType; 835 } 836 837 /// \brief Handle integer arithmetic conversions. Helper function of 838 /// UsualArithmeticConversions() 839 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 840 ExprResult &RHS, QualType LHSType, 841 QualType RHSType, bool IsCompAssign) { 842 // The rules for this case are in C99 6.3.1.8 843 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 844 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 845 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 846 if (LHSSigned == RHSSigned) { 847 // Same signedness; use the higher-ranked type 848 if (order >= 0) { 849 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast); 850 return LHSType; 851 } else if (!IsCompAssign) 852 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast); 853 return RHSType; 854 } else if (order != (LHSSigned ? 1 : -1)) { 855 // The unsigned type has greater than or equal rank to the 856 // signed type, so use the unsigned type 857 if (RHSSigned) { 858 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast); 859 return LHSType; 860 } else if (!IsCompAssign) 861 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast); 862 return RHSType; 863 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 864 // The two types are different widths; if we are here, that 865 // means the signed type is larger than the unsigned type, so 866 // use the signed type. 867 if (LHSSigned) { 868 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast); 869 return LHSType; 870 } else if (!IsCompAssign) 871 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast); 872 return RHSType; 873 } else { 874 // The signed type is higher-ranked than the unsigned type, 875 // but isn't actually any bigger (like unsigned int and long 876 // on most 32-bit systems). Use the unsigned type corresponding 877 // to the signed type. 878 QualType result = 879 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 880 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast); 881 if (!IsCompAssign) 882 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast); 883 return result; 884 } 885 } 886 887 /// UsualArithmeticConversions - Performs various conversions that are common to 888 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 889 /// routine returns the first non-arithmetic type found. The client is 890 /// responsible for emitting appropriate error diagnostics. 891 /// FIXME: verify the conversion rules for "complex int" are consistent with 892 /// GCC. 893 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 894 bool IsCompAssign) { 895 if (!IsCompAssign) { 896 LHS = UsualUnaryConversions(LHS.take()); 897 if (LHS.isInvalid()) 898 return QualType(); 899 } 900 901 RHS = UsualUnaryConversions(RHS.take()); 902 if (RHS.isInvalid()) 903 return QualType(); 904 905 // For conversion purposes, we ignore any qualifiers. 906 // For example, "const float" and "float" are equivalent. 907 QualType LHSType = 908 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 909 QualType RHSType = 910 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 911 912 // If both types are identical, no conversion is needed. 913 if (LHSType == RHSType) 914 return LHSType; 915 916 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 917 // The caller can deal with this (e.g. pointer + int). 918 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 919 return LHSType; 920 921 // Apply unary and bitfield promotions to the LHS's type. 922 QualType LHSUnpromotedType = LHSType; 923 if (LHSType->isPromotableIntegerType()) 924 LHSType = Context.getPromotedIntegerType(LHSType); 925 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 926 if (!LHSBitfieldPromoteTy.isNull()) 927 LHSType = LHSBitfieldPromoteTy; 928 if (LHSType != LHSUnpromotedType && !IsCompAssign) 929 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast); 930 931 // If both types are identical, no conversion is needed. 932 if (LHSType == RHSType) 933 return LHSType; 934 935 // At this point, we have two different arithmetic types. 936 937 // Handle complex types first (C99 6.3.1.8p1). 938 if (LHSType->isComplexType() || RHSType->isComplexType()) 939 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 940 IsCompAssign); 941 942 // Now handle "real" floating types (i.e. float, double, long double). 943 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 944 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 945 IsCompAssign); 946 947 // Handle GCC complex int extension. 948 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 949 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 950 IsCompAssign); 951 952 // Finally, we have two differing integer types. 953 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType, 954 IsCompAssign); 955 } 956 957 //===----------------------------------------------------------------------===// 958 // Semantic Analysis for various Expression Types 959 //===----------------------------------------------------------------------===// 960 961 962 ExprResult 963 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 964 SourceLocation DefaultLoc, 965 SourceLocation RParenLoc, 966 Expr *ControllingExpr, 967 MultiTypeArg ArgTypes, 968 MultiExprArg ArgExprs) { 969 unsigned NumAssocs = ArgTypes.size(); 970 assert(NumAssocs == ArgExprs.size()); 971 972 ParsedType *ParsedTypes = ArgTypes.release(); 973 Expr **Exprs = ArgExprs.release(); 974 975 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 976 for (unsigned i = 0; i < NumAssocs; ++i) { 977 if (ParsedTypes[i]) 978 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]); 979 else 980 Types[i] = 0; 981 } 982 983 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 984 ControllingExpr, Types, Exprs, 985 NumAssocs); 986 delete [] Types; 987 return ER; 988 } 989 990 ExprResult 991 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 992 SourceLocation DefaultLoc, 993 SourceLocation RParenLoc, 994 Expr *ControllingExpr, 995 TypeSourceInfo **Types, 996 Expr **Exprs, 997 unsigned NumAssocs) { 998 bool TypeErrorFound = false, 999 IsResultDependent = ControllingExpr->isTypeDependent(), 1000 ContainsUnexpandedParameterPack 1001 = ControllingExpr->containsUnexpandedParameterPack(); 1002 1003 for (unsigned i = 0; i < NumAssocs; ++i) { 1004 if (Exprs[i]->containsUnexpandedParameterPack()) 1005 ContainsUnexpandedParameterPack = true; 1006 1007 if (Types[i]) { 1008 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1009 ContainsUnexpandedParameterPack = true; 1010 1011 if (Types[i]->getType()->isDependentType()) { 1012 IsResultDependent = true; 1013 } else { 1014 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a 1015 // complete object type other than a variably modified type." 1016 unsigned D = 0; 1017 if (Types[i]->getType()->isIncompleteType()) 1018 D = diag::err_assoc_type_incomplete; 1019 else if (!Types[i]->getType()->isObjectType()) 1020 D = diag::err_assoc_type_nonobject; 1021 else if (Types[i]->getType()->isVariablyModifiedType()) 1022 D = diag::err_assoc_type_variably_modified; 1023 1024 if (D != 0) { 1025 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1026 << Types[i]->getTypeLoc().getSourceRange() 1027 << Types[i]->getType(); 1028 TypeErrorFound = true; 1029 } 1030 1031 // C1X 6.5.1.1p2 "No two generic associations in the same generic 1032 // selection shall specify compatible types." 1033 for (unsigned j = i+1; j < NumAssocs; ++j) 1034 if (Types[j] && !Types[j]->getType()->isDependentType() && 1035 Context.typesAreCompatible(Types[i]->getType(), 1036 Types[j]->getType())) { 1037 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1038 diag::err_assoc_compatible_types) 1039 << Types[j]->getTypeLoc().getSourceRange() 1040 << Types[j]->getType() 1041 << Types[i]->getType(); 1042 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1043 diag::note_compat_assoc) 1044 << Types[i]->getTypeLoc().getSourceRange() 1045 << Types[i]->getType(); 1046 TypeErrorFound = true; 1047 } 1048 } 1049 } 1050 } 1051 if (TypeErrorFound) 1052 return ExprError(); 1053 1054 // If we determined that the generic selection is result-dependent, don't 1055 // try to compute the result expression. 1056 if (IsResultDependent) 1057 return Owned(new (Context) GenericSelectionExpr( 1058 Context, KeyLoc, ControllingExpr, 1059 Types, Exprs, NumAssocs, DefaultLoc, 1060 RParenLoc, ContainsUnexpandedParameterPack)); 1061 1062 SmallVector<unsigned, 1> CompatIndices; 1063 unsigned DefaultIndex = -1U; 1064 for (unsigned i = 0; i < NumAssocs; ++i) { 1065 if (!Types[i]) 1066 DefaultIndex = i; 1067 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1068 Types[i]->getType())) 1069 CompatIndices.push_back(i); 1070 } 1071 1072 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have 1073 // type compatible with at most one of the types named in its generic 1074 // association list." 1075 if (CompatIndices.size() > 1) { 1076 // We strip parens here because the controlling expression is typically 1077 // parenthesized in macro definitions. 1078 ControllingExpr = ControllingExpr->IgnoreParens(); 1079 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1080 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1081 << (unsigned) CompatIndices.size(); 1082 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(), 1083 E = CompatIndices.end(); I != E; ++I) { 1084 Diag(Types[*I]->getTypeLoc().getBeginLoc(), 1085 diag::note_compat_assoc) 1086 << Types[*I]->getTypeLoc().getSourceRange() 1087 << Types[*I]->getType(); 1088 } 1089 return ExprError(); 1090 } 1091 1092 // C1X 6.5.1.1p2 "If a generic selection has no default generic association, 1093 // its controlling expression shall have type compatible with exactly one of 1094 // the types named in its generic association list." 1095 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1096 // We strip parens here because the controlling expression is typically 1097 // parenthesized in macro definitions. 1098 ControllingExpr = ControllingExpr->IgnoreParens(); 1099 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1100 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1101 return ExprError(); 1102 } 1103 1104 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a 1105 // type name that is compatible with the type of the controlling expression, 1106 // then the result expression of the generic selection is the expression 1107 // in that generic association. Otherwise, the result expression of the 1108 // generic selection is the expression in the default generic association." 1109 unsigned ResultIndex = 1110 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1111 1112 return Owned(new (Context) GenericSelectionExpr( 1113 Context, KeyLoc, ControllingExpr, 1114 Types, Exprs, NumAssocs, DefaultLoc, 1115 RParenLoc, ContainsUnexpandedParameterPack, 1116 ResultIndex)); 1117 } 1118 1119 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1120 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1121 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1122 /// multiple tokens. However, the common case is that StringToks points to one 1123 /// string. 1124 /// 1125 ExprResult 1126 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) { 1127 assert(NumStringToks && "Must have at least one string!"); 1128 1129 StringLiteralParser Literal(StringToks, NumStringToks, PP); 1130 if (Literal.hadError) 1131 return ExprError(); 1132 1133 SmallVector<SourceLocation, 4> StringTokLocs; 1134 for (unsigned i = 0; i != NumStringToks; ++i) 1135 StringTokLocs.push_back(StringToks[i].getLocation()); 1136 1137 QualType StrTy = Context.CharTy; 1138 if (Literal.isWide()) 1139 StrTy = Context.getWCharType(); 1140 else if (Literal.isUTF16()) 1141 StrTy = Context.Char16Ty; 1142 else if (Literal.isUTF32()) 1143 StrTy = Context.Char32Ty; 1144 else if (Literal.isPascal()) 1145 StrTy = Context.UnsignedCharTy; 1146 1147 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1148 if (Literal.isWide()) 1149 Kind = StringLiteral::Wide; 1150 else if (Literal.isUTF8()) 1151 Kind = StringLiteral::UTF8; 1152 else if (Literal.isUTF16()) 1153 Kind = StringLiteral::UTF16; 1154 else if (Literal.isUTF32()) 1155 Kind = StringLiteral::UTF32; 1156 1157 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1158 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings) 1159 StrTy.addConst(); 1160 1161 // Get an array type for the string, according to C99 6.4.5. This includes 1162 // the nul terminator character as well as the string length for pascal 1163 // strings. 1164 StrTy = Context.getConstantArrayType(StrTy, 1165 llvm::APInt(32, Literal.GetNumStringChars()+1), 1166 ArrayType::Normal, 0); 1167 1168 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1169 return Owned(StringLiteral::Create(Context, Literal.GetString(), 1170 Kind, Literal.Pascal, StrTy, 1171 &StringTokLocs[0], 1172 StringTokLocs.size())); 1173 } 1174 1175 enum CaptureResult { 1176 /// No capture is required. 1177 CR_NoCapture, 1178 1179 /// A capture is required. 1180 CR_Capture, 1181 1182 /// A by-ref capture is required. 1183 CR_CaptureByRef, 1184 1185 /// An error occurred when trying to capture the given variable. 1186 CR_Error 1187 }; 1188 1189 /// Diagnose an uncapturable value reference. 1190 /// 1191 /// \param var - the variable referenced 1192 /// \param DC - the context which we couldn't capture through 1193 static CaptureResult 1194 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 1195 VarDecl *var, DeclContext *DC) { 1196 switch (S.ExprEvalContexts.back().Context) { 1197 case Sema::Unevaluated: 1198 // The argument will never be evaluated, so don't complain. 1199 return CR_NoCapture; 1200 1201 case Sema::PotentiallyEvaluated: 1202 case Sema::PotentiallyEvaluatedIfUsed: 1203 break; 1204 1205 case Sema::PotentiallyPotentiallyEvaluated: 1206 // FIXME: delay these! 1207 break; 1208 } 1209 1210 // Don't diagnose about capture if we're not actually in code right 1211 // now; in general, there are more appropriate places that will 1212 // diagnose this. 1213 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture; 1214 1215 // Certain madnesses can happen with parameter declarations, which 1216 // we want to ignore. 1217 if (isa<ParmVarDecl>(var)) { 1218 // - If the parameter still belongs to the translation unit, then 1219 // we're actually just using one parameter in the declaration of 1220 // the next. This is useful in e.g. VLAs. 1221 if (isa<TranslationUnitDecl>(var->getDeclContext())) 1222 return CR_NoCapture; 1223 1224 // - This particular madness can happen in ill-formed default 1225 // arguments; claim it's okay and let downstream code handle it. 1226 if (S.CurContext == var->getDeclContext()->getParent()) 1227 return CR_NoCapture; 1228 } 1229 1230 DeclarationName functionName; 1231 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext())) 1232 functionName = fn->getDeclName(); 1233 // FIXME: variable from enclosing block that we couldn't capture from! 1234 1235 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 1236 << var->getIdentifier() << functionName; 1237 S.Diag(var->getLocation(), diag::note_local_variable_declared_here) 1238 << var->getIdentifier(); 1239 1240 return CR_Error; 1241 } 1242 1243 /// There is a well-formed capture at a particular scope level; 1244 /// propagate it through all the nested blocks. 1245 static CaptureResult propagateCapture(Sema &S, unsigned ValidScopeIndex, 1246 const BlockDecl::Capture &Capture) { 1247 VarDecl *var = Capture.getVariable(); 1248 1249 // Update all the inner blocks with the capture information. 1250 for (unsigned i = ValidScopeIndex + 1, e = S.FunctionScopes.size(); 1251 i != e; ++i) { 1252 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]); 1253 innerBlock->Captures.push_back( 1254 BlockDecl::Capture(Capture.getVariable(), Capture.isByRef(), 1255 /*nested*/ true, Capture.getCopyExpr())); 1256 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1 1257 } 1258 1259 return Capture.isByRef() ? CR_CaptureByRef : CR_Capture; 1260 } 1261 1262 /// shouldCaptureValueReference - Determine if a reference to the 1263 /// given value in the current context requires a variable capture. 1264 /// 1265 /// This also keeps the captures set in the BlockScopeInfo records 1266 /// up-to-date. 1267 static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc, 1268 ValueDecl *Value) { 1269 // Only variables ever require capture. 1270 VarDecl *var = dyn_cast<VarDecl>(Value); 1271 if (!var) return CR_NoCapture; 1272 1273 // Fast path: variables from the current context never require capture. 1274 DeclContext *DC = S.CurContext; 1275 if (var->getDeclContext() == DC) return CR_NoCapture; 1276 1277 // Only variables with local storage require capture. 1278 // FIXME: What about 'const' variables in C++? 1279 if (!var->hasLocalStorage()) return CR_NoCapture; 1280 1281 // Otherwise, we need to capture. 1282 1283 unsigned functionScopesIndex = S.FunctionScopes.size() - 1; 1284 do { 1285 // Only blocks (and eventually C++0x closures) can capture; other 1286 // scopes don't work. 1287 if (!isa<BlockDecl>(DC)) 1288 return diagnoseUncapturableValueReference(S, loc, var, DC); 1289 1290 BlockScopeInfo *blockScope = 1291 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]); 1292 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC)); 1293 1294 // Check whether we've already captured it in this block. If so, 1295 // we're done. 1296 if (unsigned indexPlus1 = blockScope->CaptureMap[var]) 1297 return propagateCapture(S, functionScopesIndex, 1298 blockScope->Captures[indexPlus1 - 1]); 1299 1300 functionScopesIndex--; 1301 DC = cast<BlockDecl>(DC)->getDeclContext(); 1302 } while (var->getDeclContext() != DC); 1303 1304 // Okay, we descended all the way to the block that defines the variable. 1305 // Actually try to capture it. 1306 QualType type = var->getType(); 1307 1308 // Prohibit variably-modified types. 1309 if (type->isVariablyModifiedType()) { 1310 S.Diag(loc, diag::err_ref_vm_type); 1311 S.Diag(var->getLocation(), diag::note_declared_at); 1312 return CR_Error; 1313 } 1314 1315 // Prohibit arrays, even in __block variables, but not references to 1316 // them. 1317 if (type->isArrayType()) { 1318 S.Diag(loc, diag::err_ref_array_type); 1319 S.Diag(var->getLocation(), diag::note_declared_at); 1320 return CR_Error; 1321 } 1322 1323 S.MarkDeclarationReferenced(loc, var); 1324 1325 // The BlocksAttr indicates the variable is bound by-reference. 1326 bool byRef = var->hasAttr<BlocksAttr>(); 1327 1328 // Build a copy expression. 1329 Expr *copyExpr = 0; 1330 const RecordType *rtype; 1331 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() && 1332 (rtype = type->getAs<RecordType>())) { 1333 1334 // The capture logic needs the destructor, so make sure we mark it. 1335 // Usually this is unnecessary because most local variables have 1336 // their destructors marked at declaration time, but parameters are 1337 // an exception because it's technically only the call site that 1338 // actually requires the destructor. 1339 if (isa<ParmVarDecl>(var)) 1340 S.FinalizeVarWithDestructor(var, rtype); 1341 1342 // According to the blocks spec, the capture of a variable from 1343 // the stack requires a const copy constructor. This is not true 1344 // of the copy/move done to move a __block variable to the heap. 1345 type.addConst(); 1346 1347 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc); 1348 ExprResult result = 1349 S.PerformCopyInitialization( 1350 InitializedEntity::InitializeBlock(var->getLocation(), 1351 type, false), 1352 loc, S.Owned(declRef)); 1353 1354 // Build a full-expression copy expression if initialization 1355 // succeeded and used a non-trivial constructor. Recover from 1356 // errors by pretending that the copy isn't necessary. 1357 if (!result.isInvalid() && 1358 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) { 1359 result = S.MaybeCreateExprWithCleanups(result); 1360 copyExpr = result.take(); 1361 } 1362 } 1363 1364 // We're currently at the declarer; go back to the closure. 1365 functionScopesIndex++; 1366 BlockScopeInfo *blockScope = 1367 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]); 1368 1369 // Build a valid capture in this scope. 1370 blockScope->Captures.push_back( 1371 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr)); 1372 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1 1373 1374 // Propagate that to inner captures if necessary. 1375 return propagateCapture(S, functionScopesIndex, 1376 blockScope->Captures.back()); 1377 } 1378 1379 static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *VD, 1380 const DeclarationNameInfo &NameInfo, 1381 bool ByRef) { 1382 assert(isa<VarDecl>(VD) && "capturing non-variable"); 1383 1384 VarDecl *var = cast<VarDecl>(VD); 1385 assert(var->hasLocalStorage() && "capturing non-local"); 1386 assert(ByRef == var->hasAttr<BlocksAttr>() && "byref set wrong"); 1387 1388 QualType exprType = var->getType().getNonReferenceType(); 1389 1390 BlockDeclRefExpr *BDRE; 1391 if (!ByRef) { 1392 // The variable will be bound by copy; make it const within the 1393 // closure, but record that this was done in the expression. 1394 bool constAdded = !exprType.isConstQualified(); 1395 exprType.addConst(); 1396 1397 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue, 1398 NameInfo.getLoc(), false, 1399 constAdded); 1400 } else { 1401 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue, 1402 NameInfo.getLoc(), true); 1403 } 1404 1405 return S.Owned(BDRE); 1406 } 1407 1408 ExprResult 1409 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1410 SourceLocation Loc, 1411 const CXXScopeSpec *SS) { 1412 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1413 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1414 } 1415 1416 /// BuildDeclRefExpr - Build an expression that references a 1417 /// declaration that does not require a closure capture. 1418 ExprResult 1419 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1420 const DeclarationNameInfo &NameInfo, 1421 const CXXScopeSpec *SS) { 1422 if (getLangOptions().CUDA) 1423 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 1424 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) { 1425 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller), 1426 CalleeTarget = IdentifyCUDATarget(Callee); 1427 if (CheckCUDATarget(CallerTarget, CalleeTarget)) { 1428 Diag(NameInfo.getLoc(), diag::err_ref_bad_target) 1429 << CalleeTarget << D->getIdentifier() << CallerTarget; 1430 Diag(D->getLocation(), diag::note_previous_decl) 1431 << D->getIdentifier(); 1432 return ExprError(); 1433 } 1434 } 1435 1436 MarkDeclarationReferenced(NameInfo.getLoc(), D); 1437 1438 Expr *E = DeclRefExpr::Create(Context, 1439 SS? SS->getWithLocInContext(Context) 1440 : NestedNameSpecifierLoc(), 1441 D, NameInfo, Ty, VK); 1442 1443 // Just in case we're building an illegal pointer-to-member. 1444 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1445 if (FD && FD->isBitField()) 1446 E->setObjectKind(OK_BitField); 1447 1448 return Owned(E); 1449 } 1450 1451 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1452 /// possibly a list of template arguments. 1453 /// 1454 /// If this produces template arguments, it is permitted to call 1455 /// DecomposeTemplateName. 1456 /// 1457 /// This actually loses a lot of source location information for 1458 /// non-standard name kinds; we should consider preserving that in 1459 /// some way. 1460 void 1461 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1462 TemplateArgumentListInfo &Buffer, 1463 DeclarationNameInfo &NameInfo, 1464 const TemplateArgumentListInfo *&TemplateArgs) { 1465 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1466 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1467 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1468 1469 ASTTemplateArgsPtr TemplateArgsPtr(*this, 1470 Id.TemplateId->getTemplateArgs(), 1471 Id.TemplateId->NumArgs); 1472 translateTemplateArguments(TemplateArgsPtr, Buffer); 1473 TemplateArgsPtr.release(); 1474 1475 TemplateName TName = Id.TemplateId->Template.get(); 1476 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1477 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1478 TemplateArgs = &Buffer; 1479 } else { 1480 NameInfo = GetNameFromUnqualifiedId(Id); 1481 TemplateArgs = 0; 1482 } 1483 } 1484 1485 /// Diagnose an empty lookup. 1486 /// 1487 /// \return false if new lookup candidates were found 1488 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1489 CorrectTypoContext CTC, 1490 TemplateArgumentListInfo *ExplicitTemplateArgs, 1491 Expr **Args, unsigned NumArgs) { 1492 DeclarationName Name = R.getLookupName(); 1493 1494 unsigned diagnostic = diag::err_undeclared_var_use; 1495 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1496 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1497 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1498 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1499 diagnostic = diag::err_undeclared_use; 1500 diagnostic_suggest = diag::err_undeclared_use_suggest; 1501 } 1502 1503 // If the original lookup was an unqualified lookup, fake an 1504 // unqualified lookup. This is useful when (for example) the 1505 // original lookup would not have found something because it was a 1506 // dependent name. 1507 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0; 1508 DC; DC = DC->getParent()) { 1509 if (isa<CXXRecordDecl>(DC)) { 1510 LookupQualifiedName(R, DC); 1511 1512 if (!R.empty()) { 1513 // Don't give errors about ambiguities in this lookup. 1514 R.suppressDiagnostics(); 1515 1516 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1517 bool isInstance = CurMethod && 1518 CurMethod->isInstance() && 1519 DC == CurMethod->getParent(); 1520 1521 // Give a code modification hint to insert 'this->'. 1522 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1523 // Actually quite difficult! 1524 if (isInstance) { 1525 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>( 1526 CallsUndergoingInstantiation.back()->getCallee()); 1527 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>( 1528 CurMethod->getInstantiatedFromMemberFunction()); 1529 if (DepMethod) { 1530 if (getLangOptions().MicrosoftExt) 1531 diagnostic = diag::warn_found_via_dependent_bases_lookup; 1532 Diag(R.getNameLoc(), diagnostic) << Name 1533 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1534 QualType DepThisType = DepMethod->getThisType(Context); 1535 CXXThisExpr *DepThis = new (Context) CXXThisExpr( 1536 R.getNameLoc(), DepThisType, false); 1537 TemplateArgumentListInfo TList; 1538 if (ULE->hasExplicitTemplateArgs()) 1539 ULE->copyTemplateArgumentsInto(TList); 1540 1541 CXXScopeSpec SS; 1542 SS.Adopt(ULE->getQualifierLoc()); 1543 CXXDependentScopeMemberExpr *DepExpr = 1544 CXXDependentScopeMemberExpr::Create( 1545 Context, DepThis, DepThisType, true, SourceLocation(), 1546 SS.getWithLocInContext(Context), NULL, 1547 R.getLookupNameInfo(), 1548 ULE->hasExplicitTemplateArgs() ? &TList : 0); 1549 CallsUndergoingInstantiation.back()->setCallee(DepExpr); 1550 } else { 1551 // FIXME: we should be able to handle this case too. It is correct 1552 // to add this-> here. This is a workaround for PR7947. 1553 Diag(R.getNameLoc(), diagnostic) << Name; 1554 } 1555 } else { 1556 Diag(R.getNameLoc(), diagnostic) << Name; 1557 } 1558 1559 // Do we really want to note all of these? 1560 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 1561 Diag((*I)->getLocation(), diag::note_dependent_var_use); 1562 1563 // Tell the callee to try to recover. 1564 return false; 1565 } 1566 1567 R.clear(); 1568 } 1569 } 1570 1571 // We didn't find anything, so try to correct for a typo. 1572 TypoCorrection Corrected; 1573 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 1574 S, &SS, NULL, false, CTC))) { 1575 std::string CorrectedStr(Corrected.getAsString(getLangOptions())); 1576 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions())); 1577 R.setLookupName(Corrected.getCorrection()); 1578 1579 if (NamedDecl *ND = Corrected.getCorrectionDecl()) { 1580 if (Corrected.isOverloaded()) { 1581 OverloadCandidateSet OCS(R.getNameLoc()); 1582 OverloadCandidateSet::iterator Best; 1583 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 1584 CDEnd = Corrected.end(); 1585 CD != CDEnd; ++CD) { 1586 if (FunctionTemplateDecl *FTD = 1587 dyn_cast<FunctionTemplateDecl>(*CD)) 1588 AddTemplateOverloadCandidate( 1589 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1590 Args, NumArgs, OCS); 1591 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 1592 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1593 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1594 Args, NumArgs, OCS); 1595 } 1596 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1597 case OR_Success: 1598 ND = Best->Function; 1599 break; 1600 default: 1601 break; 1602 } 1603 } 1604 R.addDecl(ND); 1605 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) { 1606 if (SS.isEmpty()) 1607 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr 1608 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 1609 else 1610 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1611 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 1612 << SS.getRange() 1613 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 1614 if (ND) 1615 Diag(ND->getLocation(), diag::note_previous_decl) 1616 << CorrectedQuotedStr; 1617 1618 // Tell the callee to try to recover. 1619 return false; 1620 } 1621 1622 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) { 1623 // FIXME: If we ended up with a typo for a type name or 1624 // Objective-C class name, we're in trouble because the parser 1625 // is in the wrong place to recover. Suggest the typo 1626 // correction, but don't make it a fix-it since we're not going 1627 // to recover well anyway. 1628 if (SS.isEmpty()) 1629 Diag(R.getNameLoc(), diagnostic_suggest) 1630 << Name << CorrectedQuotedStr; 1631 else 1632 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1633 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 1634 << SS.getRange(); 1635 1636 // Don't try to recover; it won't work. 1637 return true; 1638 } 1639 } else { 1640 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1641 // because we aren't able to recover. 1642 if (SS.isEmpty()) 1643 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr; 1644 else 1645 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1646 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 1647 << SS.getRange(); 1648 return true; 1649 } 1650 } 1651 R.clear(); 1652 1653 // Emit a special diagnostic for failed member lookups. 1654 // FIXME: computing the declaration context might fail here (?) 1655 if (!SS.isEmpty()) { 1656 Diag(R.getNameLoc(), diag::err_no_member) 1657 << Name << computeDeclContext(SS, false) 1658 << SS.getRange(); 1659 return true; 1660 } 1661 1662 // Give up, we can't recover. 1663 Diag(R.getNameLoc(), diagnostic) << Name; 1664 return true; 1665 } 1666 1667 ExprResult Sema::ActOnIdExpression(Scope *S, 1668 CXXScopeSpec &SS, 1669 UnqualifiedId &Id, 1670 bool HasTrailingLParen, 1671 bool IsAddressOfOperand) { 1672 assert(!(IsAddressOfOperand && HasTrailingLParen) && 1673 "cannot be direct & operand and have a trailing lparen"); 1674 1675 if (SS.isInvalid()) 1676 return ExprError(); 1677 1678 TemplateArgumentListInfo TemplateArgsBuffer; 1679 1680 // Decompose the UnqualifiedId into the following data. 1681 DeclarationNameInfo NameInfo; 1682 const TemplateArgumentListInfo *TemplateArgs; 1683 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 1684 1685 DeclarationName Name = NameInfo.getName(); 1686 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1687 SourceLocation NameLoc = NameInfo.getLoc(); 1688 1689 // C++ [temp.dep.expr]p3: 1690 // An id-expression is type-dependent if it contains: 1691 // -- an identifier that was declared with a dependent type, 1692 // (note: handled after lookup) 1693 // -- a template-id that is dependent, 1694 // (note: handled in BuildTemplateIdExpr) 1695 // -- a conversion-function-id that specifies a dependent type, 1696 // -- a nested-name-specifier that contains a class-name that 1697 // names a dependent type. 1698 // Determine whether this is a member of an unknown specialization; 1699 // we need to handle these differently. 1700 bool DependentID = false; 1701 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 1702 Name.getCXXNameType()->isDependentType()) { 1703 DependentID = true; 1704 } else if (SS.isSet()) { 1705 if (DeclContext *DC = computeDeclContext(SS, false)) { 1706 if (RequireCompleteDeclContext(SS, DC)) 1707 return ExprError(); 1708 } else { 1709 DependentID = true; 1710 } 1711 } 1712 1713 if (DependentID) 1714 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand, 1715 TemplateArgs); 1716 1717 bool IvarLookupFollowUp = false; 1718 // Perform the required lookup. 1719 LookupResult R(*this, NameInfo, 1720 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 1721 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 1722 if (TemplateArgs) { 1723 // Lookup the template name again to correctly establish the context in 1724 // which it was found. This is really unfortunate as we already did the 1725 // lookup to determine that it was a template name in the first place. If 1726 // this becomes a performance hit, we can work harder to preserve those 1727 // results until we get here but it's likely not worth it. 1728 bool MemberOfUnknownSpecialization; 1729 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 1730 MemberOfUnknownSpecialization); 1731 1732 if (MemberOfUnknownSpecialization || 1733 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 1734 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand, 1735 TemplateArgs); 1736 } else { 1737 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl()); 1738 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 1739 1740 // If the result might be in a dependent base class, this is a dependent 1741 // id-expression. 1742 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 1743 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand, 1744 TemplateArgs); 1745 1746 // If this reference is in an Objective-C method, then we need to do 1747 // some special Objective-C lookup, too. 1748 if (IvarLookupFollowUp) { 1749 ExprResult E(LookupInObjCMethod(R, S, II, true)); 1750 if (E.isInvalid()) 1751 return ExprError(); 1752 1753 if (Expr *Ex = E.takeAs<Expr>()) 1754 return Owned(Ex); 1755 1756 // for further use, this must be set to false if in class method. 1757 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod(); 1758 } 1759 } 1760 1761 if (R.isAmbiguous()) 1762 return ExprError(); 1763 1764 // Determine whether this name might be a candidate for 1765 // argument-dependent lookup. 1766 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 1767 1768 if (R.empty() && !ADL) { 1769 // Otherwise, this could be an implicitly declared function reference (legal 1770 // in C90, extension in C99, forbidden in C++). 1771 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) { 1772 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 1773 if (D) R.addDecl(D); 1774 } 1775 1776 // If this name wasn't predeclared and if this is not a function 1777 // call, diagnose the problem. 1778 if (R.empty()) { 1779 1780 // In Microsoft mode, if we are inside a template class member function 1781 // and we can't resolve an identifier then assume the identifier is type 1782 // dependent. The goal is to postpone name lookup to instantiation time 1783 // to be able to search into type dependent base classes. 1784 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() && 1785 isa<CXXMethodDecl>(CurContext)) 1786 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand, 1787 TemplateArgs); 1788 1789 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown)) 1790 return ExprError(); 1791 1792 assert(!R.empty() && 1793 "DiagnoseEmptyLookup returned false but added no results"); 1794 1795 // If we found an Objective-C instance variable, let 1796 // LookupInObjCMethod build the appropriate expression to 1797 // reference the ivar. 1798 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 1799 R.clear(); 1800 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 1801 // In a hopelessly buggy code, Objective-C instance variable 1802 // lookup fails and no expression will be built to reference it. 1803 if (!E.isInvalid() && !E.get()) 1804 return ExprError(); 1805 return move(E); 1806 } 1807 } 1808 } 1809 1810 // This is guaranteed from this point on. 1811 assert(!R.empty() || ADL); 1812 1813 // Check whether this might be a C++ implicit instance member access. 1814 // C++ [class.mfct.non-static]p3: 1815 // When an id-expression that is not part of a class member access 1816 // syntax and not used to form a pointer to member is used in the 1817 // body of a non-static member function of class X, if name lookup 1818 // resolves the name in the id-expression to a non-static non-type 1819 // member of some class C, the id-expression is transformed into a 1820 // class member access expression using (*this) as the 1821 // postfix-expression to the left of the . operator. 1822 // 1823 // But we don't actually need to do this for '&' operands if R 1824 // resolved to a function or overloaded function set, because the 1825 // expression is ill-formed if it actually works out to be a 1826 // non-static member function: 1827 // 1828 // C++ [expr.ref]p4: 1829 // Otherwise, if E1.E2 refers to a non-static member function. . . 1830 // [t]he expression can be used only as the left-hand operand of a 1831 // member function call. 1832 // 1833 // There are other safeguards against such uses, but it's important 1834 // to get this right here so that we don't end up making a 1835 // spuriously dependent expression if we're inside a dependent 1836 // instance method. 1837 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 1838 bool MightBeImplicitMember; 1839 if (!IsAddressOfOperand) 1840 MightBeImplicitMember = true; 1841 else if (!SS.isEmpty()) 1842 MightBeImplicitMember = false; 1843 else if (R.isOverloadedResult()) 1844 MightBeImplicitMember = false; 1845 else if (R.isUnresolvableResult()) 1846 MightBeImplicitMember = true; 1847 else 1848 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 1849 isa<IndirectFieldDecl>(R.getFoundDecl()); 1850 1851 if (MightBeImplicitMember) 1852 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs); 1853 } 1854 1855 if (TemplateArgs) 1856 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs); 1857 1858 return BuildDeclarationNameExpr(SS, R, ADL); 1859 } 1860 1861 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 1862 /// declaration name, generally during template instantiation. 1863 /// There's a large number of things which don't need to be done along 1864 /// this path. 1865 ExprResult 1866 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 1867 const DeclarationNameInfo &NameInfo) { 1868 DeclContext *DC; 1869 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext()) 1870 return BuildDependentDeclRefExpr(SS, NameInfo, 0); 1871 1872 if (RequireCompleteDeclContext(SS, DC)) 1873 return ExprError(); 1874 1875 LookupResult R(*this, NameInfo, LookupOrdinaryName); 1876 LookupQualifiedName(R, DC); 1877 1878 if (R.isAmbiguous()) 1879 return ExprError(); 1880 1881 if (R.empty()) { 1882 Diag(NameInfo.getLoc(), diag::err_no_member) 1883 << NameInfo.getName() << DC << SS.getRange(); 1884 return ExprError(); 1885 } 1886 1887 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false); 1888 } 1889 1890 /// LookupInObjCMethod - The parser has read a name in, and Sema has 1891 /// detected that we're currently inside an ObjC method. Perform some 1892 /// additional lookup. 1893 /// 1894 /// Ideally, most of this would be done by lookup, but there's 1895 /// actually quite a lot of extra work involved. 1896 /// 1897 /// Returns a null sentinel to indicate trivial success. 1898 ExprResult 1899 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 1900 IdentifierInfo *II, bool AllowBuiltinCreation) { 1901 SourceLocation Loc = Lookup.getNameLoc(); 1902 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 1903 1904 // There are two cases to handle here. 1) scoped lookup could have failed, 1905 // in which case we should look for an ivar. 2) scoped lookup could have 1906 // found a decl, but that decl is outside the current instance method (i.e. 1907 // a global variable). In these two cases, we do a lookup for an ivar with 1908 // this name, if the lookup sucedes, we replace it our current decl. 1909 1910 // If we're in a class method, we don't normally want to look for 1911 // ivars. But if we don't find anything else, and there's an 1912 // ivar, that's an error. 1913 bool IsClassMethod = CurMethod->isClassMethod(); 1914 1915 bool LookForIvars; 1916 if (Lookup.empty()) 1917 LookForIvars = true; 1918 else if (IsClassMethod) 1919 LookForIvars = false; 1920 else 1921 LookForIvars = (Lookup.isSingleResult() && 1922 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 1923 ObjCInterfaceDecl *IFace = 0; 1924 if (LookForIvars) { 1925 IFace = CurMethod->getClassInterface(); 1926 ObjCInterfaceDecl *ClassDeclared; 1927 ObjCIvarDecl *IV = 0; 1928 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 1929 // Diagnose using an ivar in a class method. 1930 if (IsClassMethod) 1931 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 1932 << IV->getDeclName()); 1933 1934 // If we're referencing an invalid decl, just return this as a silent 1935 // error node. The error diagnostic was already emitted on the decl. 1936 if (IV->isInvalidDecl()) 1937 return ExprError(); 1938 1939 // Check if referencing a field with __attribute__((deprecated)). 1940 if (DiagnoseUseOfDecl(IV, Loc)) 1941 return ExprError(); 1942 1943 // Diagnose the use of an ivar outside of the declaring class. 1944 if (IV->getAccessControl() == ObjCIvarDecl::Private && 1945 ClassDeclared != IFace) 1946 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 1947 1948 // FIXME: This should use a new expr for a direct reference, don't 1949 // turn this into Self->ivar, just return a BareIVarExpr or something. 1950 IdentifierInfo &II = Context.Idents.get("self"); 1951 UnqualifiedId SelfName; 1952 SelfName.setIdentifier(&II, SourceLocation()); 1953 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 1954 CXXScopeSpec SelfScopeSpec; 1955 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, 1956 SelfName, false, false); 1957 if (SelfExpr.isInvalid()) 1958 return ExprError(); 1959 1960 SelfExpr = DefaultLvalueConversion(SelfExpr.take()); 1961 if (SelfExpr.isInvalid()) 1962 return ExprError(); 1963 1964 MarkDeclarationReferenced(Loc, IV); 1965 return Owned(new (Context) 1966 ObjCIvarRefExpr(IV, IV->getType(), Loc, 1967 SelfExpr.take(), true, true)); 1968 } 1969 } else if (CurMethod->isInstanceMethod()) { 1970 // We should warn if a local variable hides an ivar. 1971 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 1972 ObjCInterfaceDecl *ClassDeclared; 1973 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 1974 if (IV->getAccessControl() != ObjCIvarDecl::Private || 1975 IFace == ClassDeclared) 1976 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 1977 } 1978 } 1979 } 1980 1981 if (Lookup.empty() && II && AllowBuiltinCreation) { 1982 // FIXME. Consolidate this with similar code in LookupName. 1983 if (unsigned BuiltinID = II->getBuiltinID()) { 1984 if (!(getLangOptions().CPlusPlus && 1985 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 1986 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 1987 S, Lookup.isForRedeclaration(), 1988 Lookup.getNameLoc()); 1989 if (D) Lookup.addDecl(D); 1990 } 1991 } 1992 } 1993 // Sentinel value saying that we didn't do anything special. 1994 return Owned((Expr*) 0); 1995 } 1996 1997 /// \brief Cast a base object to a member's actual type. 1998 /// 1999 /// Logically this happens in three phases: 2000 /// 2001 /// * First we cast from the base type to the naming class. 2002 /// The naming class is the class into which we were looking 2003 /// when we found the member; it's the qualifier type if a 2004 /// qualifier was provided, and otherwise it's the base type. 2005 /// 2006 /// * Next we cast from the naming class to the declaring class. 2007 /// If the member we found was brought into a class's scope by 2008 /// a using declaration, this is that class; otherwise it's 2009 /// the class declaring the member. 2010 /// 2011 /// * Finally we cast from the declaring class to the "true" 2012 /// declaring class of the member. This conversion does not 2013 /// obey access control. 2014 ExprResult 2015 Sema::PerformObjectMemberConversion(Expr *From, 2016 NestedNameSpecifier *Qualifier, 2017 NamedDecl *FoundDecl, 2018 NamedDecl *Member) { 2019 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2020 if (!RD) 2021 return Owned(From); 2022 2023 QualType DestRecordType; 2024 QualType DestType; 2025 QualType FromRecordType; 2026 QualType FromType = From->getType(); 2027 bool PointerConversions = false; 2028 if (isa<FieldDecl>(Member)) { 2029 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2030 2031 if (FromType->getAs<PointerType>()) { 2032 DestType = Context.getPointerType(DestRecordType); 2033 FromRecordType = FromType->getPointeeType(); 2034 PointerConversions = true; 2035 } else { 2036 DestType = DestRecordType; 2037 FromRecordType = FromType; 2038 } 2039 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2040 if (Method->isStatic()) 2041 return Owned(From); 2042 2043 DestType = Method->getThisType(Context); 2044 DestRecordType = DestType->getPointeeType(); 2045 2046 if (FromType->getAs<PointerType>()) { 2047 FromRecordType = FromType->getPointeeType(); 2048 PointerConversions = true; 2049 } else { 2050 FromRecordType = FromType; 2051 DestType = DestRecordType; 2052 } 2053 } else { 2054 // No conversion necessary. 2055 return Owned(From); 2056 } 2057 2058 if (DestType->isDependentType() || FromType->isDependentType()) 2059 return Owned(From); 2060 2061 // If the unqualified types are the same, no conversion is necessary. 2062 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2063 return Owned(From); 2064 2065 SourceRange FromRange = From->getSourceRange(); 2066 SourceLocation FromLoc = FromRange.getBegin(); 2067 2068 ExprValueKind VK = From->getValueKind(); 2069 2070 // C++ [class.member.lookup]p8: 2071 // [...] Ambiguities can often be resolved by qualifying a name with its 2072 // class name. 2073 // 2074 // If the member was a qualified name and the qualified referred to a 2075 // specific base subobject type, we'll cast to that intermediate type 2076 // first and then to the object in which the member is declared. That allows 2077 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2078 // 2079 // class Base { public: int x; }; 2080 // class Derived1 : public Base { }; 2081 // class Derived2 : public Base { }; 2082 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2083 // 2084 // void VeryDerived::f() { 2085 // x = 17; // error: ambiguous base subobjects 2086 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2087 // } 2088 if (Qualifier) { 2089 QualType QType = QualType(Qualifier->getAsType(), 0); 2090 assert(!QType.isNull() && "lookup done with dependent qualifier?"); 2091 assert(QType->isRecordType() && "lookup done with non-record type"); 2092 2093 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2094 2095 // In C++98, the qualifier type doesn't actually have to be a base 2096 // type of the object type, in which case we just ignore it. 2097 // Otherwise build the appropriate casts. 2098 if (IsDerivedFrom(FromRecordType, QRecordType)) { 2099 CXXCastPath BasePath; 2100 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2101 FromLoc, FromRange, &BasePath)) 2102 return ExprError(); 2103 2104 if (PointerConversions) 2105 QType = Context.getPointerType(QType); 2106 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2107 VK, &BasePath).take(); 2108 2109 FromType = QType; 2110 FromRecordType = QRecordType; 2111 2112 // If the qualifier type was the same as the destination type, 2113 // we're done. 2114 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2115 return Owned(From); 2116 } 2117 } 2118 2119 bool IgnoreAccess = false; 2120 2121 // If we actually found the member through a using declaration, cast 2122 // down to the using declaration's type. 2123 // 2124 // Pointer equality is fine here because only one declaration of a 2125 // class ever has member declarations. 2126 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2127 assert(isa<UsingShadowDecl>(FoundDecl)); 2128 QualType URecordType = Context.getTypeDeclType( 2129 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2130 2131 // We only need to do this if the naming-class to declaring-class 2132 // conversion is non-trivial. 2133 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2134 assert(IsDerivedFrom(FromRecordType, URecordType)); 2135 CXXCastPath BasePath; 2136 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2137 FromLoc, FromRange, &BasePath)) 2138 return ExprError(); 2139 2140 QualType UType = URecordType; 2141 if (PointerConversions) 2142 UType = Context.getPointerType(UType); 2143 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2144 VK, &BasePath).take(); 2145 FromType = UType; 2146 FromRecordType = URecordType; 2147 } 2148 2149 // We don't do access control for the conversion from the 2150 // declaring class to the true declaring class. 2151 IgnoreAccess = true; 2152 } 2153 2154 CXXCastPath BasePath; 2155 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2156 FromLoc, FromRange, &BasePath, 2157 IgnoreAccess)) 2158 return ExprError(); 2159 2160 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2161 VK, &BasePath); 2162 } 2163 2164 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2165 const LookupResult &R, 2166 bool HasTrailingLParen) { 2167 // Only when used directly as the postfix-expression of a call. 2168 if (!HasTrailingLParen) 2169 return false; 2170 2171 // Never if a scope specifier was provided. 2172 if (SS.isSet()) 2173 return false; 2174 2175 // Only in C++ or ObjC++. 2176 if (!getLangOptions().CPlusPlus) 2177 return false; 2178 2179 // Turn off ADL when we find certain kinds of declarations during 2180 // normal lookup: 2181 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2182 NamedDecl *D = *I; 2183 2184 // C++0x [basic.lookup.argdep]p3: 2185 // -- a declaration of a class member 2186 // Since using decls preserve this property, we check this on the 2187 // original decl. 2188 if (D->isCXXClassMember()) 2189 return false; 2190 2191 // C++0x [basic.lookup.argdep]p3: 2192 // -- a block-scope function declaration that is not a 2193 // using-declaration 2194 // NOTE: we also trigger this for function templates (in fact, we 2195 // don't check the decl type at all, since all other decl types 2196 // turn off ADL anyway). 2197 if (isa<UsingShadowDecl>(D)) 2198 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2199 else if (D->getDeclContext()->isFunctionOrMethod()) 2200 return false; 2201 2202 // C++0x [basic.lookup.argdep]p3: 2203 // -- a declaration that is neither a function or a function 2204 // template 2205 // And also for builtin functions. 2206 if (isa<FunctionDecl>(D)) { 2207 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2208 2209 // But also builtin functions. 2210 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2211 return false; 2212 } else if (!isa<FunctionTemplateDecl>(D)) 2213 return false; 2214 } 2215 2216 return true; 2217 } 2218 2219 2220 /// Diagnoses obvious problems with the use of the given declaration 2221 /// as an expression. This is only actually called for lookups that 2222 /// were not overloaded, and it doesn't promise that the declaration 2223 /// will in fact be used. 2224 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2225 if (isa<TypedefNameDecl>(D)) { 2226 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2227 return true; 2228 } 2229 2230 if (isa<ObjCInterfaceDecl>(D)) { 2231 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2232 return true; 2233 } 2234 2235 if (isa<NamespaceDecl>(D)) { 2236 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2237 return true; 2238 } 2239 2240 return false; 2241 } 2242 2243 ExprResult 2244 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2245 LookupResult &R, 2246 bool NeedsADL) { 2247 // If this is a single, fully-resolved result and we don't need ADL, 2248 // just build an ordinary singleton decl ref. 2249 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2250 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), 2251 R.getFoundDecl()); 2252 2253 // We only need to check the declaration if there's exactly one 2254 // result, because in the overloaded case the results can only be 2255 // functions and function templates. 2256 if (R.isSingleResult() && 2257 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2258 return ExprError(); 2259 2260 // Otherwise, just build an unresolved lookup expression. Suppress 2261 // any lookup-related diagnostics; we'll hash these out later, when 2262 // we've picked a target. 2263 R.suppressDiagnostics(); 2264 2265 UnresolvedLookupExpr *ULE 2266 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2267 SS.getWithLocInContext(Context), 2268 R.getLookupNameInfo(), 2269 NeedsADL, R.isOverloadedResult(), 2270 R.begin(), R.end()); 2271 2272 return Owned(ULE); 2273 } 2274 2275 /// \brief Complete semantic analysis for a reference to the given declaration. 2276 ExprResult 2277 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2278 const DeclarationNameInfo &NameInfo, 2279 NamedDecl *D) { 2280 assert(D && "Cannot refer to a NULL declaration"); 2281 assert(!isa<FunctionTemplateDecl>(D) && 2282 "Cannot refer unambiguously to a function template"); 2283 2284 SourceLocation Loc = NameInfo.getLoc(); 2285 if (CheckDeclInExpr(*this, Loc, D)) 2286 return ExprError(); 2287 2288 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2289 // Specifically diagnose references to class templates that are missing 2290 // a template argument list. 2291 Diag(Loc, diag::err_template_decl_ref) 2292 << Template << SS.getRange(); 2293 Diag(Template->getLocation(), diag::note_template_decl_here); 2294 return ExprError(); 2295 } 2296 2297 // Make sure that we're referring to a value. 2298 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2299 if (!VD) { 2300 Diag(Loc, diag::err_ref_non_value) 2301 << D << SS.getRange(); 2302 Diag(D->getLocation(), diag::note_declared_at); 2303 return ExprError(); 2304 } 2305 2306 // Check whether this declaration can be used. Note that we suppress 2307 // this check when we're going to perform argument-dependent lookup 2308 // on this function name, because this might not be the function 2309 // that overload resolution actually selects. 2310 if (DiagnoseUseOfDecl(VD, Loc)) 2311 return ExprError(); 2312 2313 // Only create DeclRefExpr's for valid Decl's. 2314 if (VD->isInvalidDecl()) 2315 return ExprError(); 2316 2317 // Handle members of anonymous structs and unions. If we got here, 2318 // and the reference is to a class member indirect field, then this 2319 // must be the subject of a pointer-to-member expression. 2320 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2321 if (!indirectField->isCXXClassMember()) 2322 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2323 indirectField); 2324 2325 // If the identifier reference is inside a block, and it refers to a value 2326 // that is outside the block, create a BlockDeclRefExpr instead of a 2327 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when 2328 // the block is formed. 2329 // 2330 // We do not do this for things like enum constants, global variables, etc, 2331 // as they do not get snapshotted. 2332 // 2333 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) { 2334 case CR_Error: 2335 return ExprError(); 2336 2337 case CR_Capture: 2338 assert(!SS.isSet() && "referenced local variable with scope specifier?"); 2339 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false); 2340 2341 case CR_CaptureByRef: 2342 assert(!SS.isSet() && "referenced local variable with scope specifier?"); 2343 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true); 2344 2345 case CR_NoCapture: { 2346 // If this reference is not in a block or if the referenced 2347 // variable is within the block, create a normal DeclRefExpr. 2348 2349 QualType type = VD->getType(); 2350 ExprValueKind valueKind = VK_RValue; 2351 2352 switch (D->getKind()) { 2353 // Ignore all the non-ValueDecl kinds. 2354 #define ABSTRACT_DECL(kind) 2355 #define VALUE(type, base) 2356 #define DECL(type, base) \ 2357 case Decl::type: 2358 #include "clang/AST/DeclNodes.inc" 2359 llvm_unreachable("invalid value decl kind"); 2360 return ExprError(); 2361 2362 // These shouldn't make it here. 2363 case Decl::ObjCAtDefsField: 2364 case Decl::ObjCIvar: 2365 llvm_unreachable("forming non-member reference to ivar?"); 2366 return ExprError(); 2367 2368 // Enum constants are always r-values and never references. 2369 // Unresolved using declarations are dependent. 2370 case Decl::EnumConstant: 2371 case Decl::UnresolvedUsingValue: 2372 valueKind = VK_RValue; 2373 break; 2374 2375 // Fields and indirect fields that got here must be for 2376 // pointer-to-member expressions; we just call them l-values for 2377 // internal consistency, because this subexpression doesn't really 2378 // exist in the high-level semantics. 2379 case Decl::Field: 2380 case Decl::IndirectField: 2381 assert(getLangOptions().CPlusPlus && 2382 "building reference to field in C?"); 2383 2384 // These can't have reference type in well-formed programs, but 2385 // for internal consistency we do this anyway. 2386 type = type.getNonReferenceType(); 2387 valueKind = VK_LValue; 2388 break; 2389 2390 // Non-type template parameters are either l-values or r-values 2391 // depending on the type. 2392 case Decl::NonTypeTemplateParm: { 2393 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2394 type = reftype->getPointeeType(); 2395 valueKind = VK_LValue; // even if the parameter is an r-value reference 2396 break; 2397 } 2398 2399 // For non-references, we need to strip qualifiers just in case 2400 // the template parameter was declared as 'const int' or whatever. 2401 valueKind = VK_RValue; 2402 type = type.getUnqualifiedType(); 2403 break; 2404 } 2405 2406 case Decl::Var: 2407 // In C, "extern void blah;" is valid and is an r-value. 2408 if (!getLangOptions().CPlusPlus && 2409 !type.hasQualifiers() && 2410 type->isVoidType()) { 2411 valueKind = VK_RValue; 2412 break; 2413 } 2414 // fallthrough 2415 2416 case Decl::ImplicitParam: 2417 case Decl::ParmVar: 2418 // These are always l-values. 2419 valueKind = VK_LValue; 2420 type = type.getNonReferenceType(); 2421 break; 2422 2423 case Decl::Function: { 2424 const FunctionType *fty = type->castAs<FunctionType>(); 2425 2426 // If we're referring to a function with an __unknown_anytype 2427 // result type, make the entire expression __unknown_anytype. 2428 if (fty->getResultType() == Context.UnknownAnyTy) { 2429 type = Context.UnknownAnyTy; 2430 valueKind = VK_RValue; 2431 break; 2432 } 2433 2434 // Functions are l-values in C++. 2435 if (getLangOptions().CPlusPlus) { 2436 valueKind = VK_LValue; 2437 break; 2438 } 2439 2440 // C99 DR 316 says that, if a function type comes from a 2441 // function definition (without a prototype), that type is only 2442 // used for checking compatibility. Therefore, when referencing 2443 // the function, we pretend that we don't have the full function 2444 // type. 2445 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2446 isa<FunctionProtoType>(fty)) 2447 type = Context.getFunctionNoProtoType(fty->getResultType(), 2448 fty->getExtInfo()); 2449 2450 // Functions are r-values in C. 2451 valueKind = VK_RValue; 2452 break; 2453 } 2454 2455 case Decl::CXXMethod: 2456 // If we're referring to a method with an __unknown_anytype 2457 // result type, make the entire expression __unknown_anytype. 2458 // This should only be possible with a type written directly. 2459 if (const FunctionProtoType *proto 2460 = dyn_cast<FunctionProtoType>(VD->getType())) 2461 if (proto->getResultType() == Context.UnknownAnyTy) { 2462 type = Context.UnknownAnyTy; 2463 valueKind = VK_RValue; 2464 break; 2465 } 2466 2467 // C++ methods are l-values if static, r-values if non-static. 2468 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2469 valueKind = VK_LValue; 2470 break; 2471 } 2472 // fallthrough 2473 2474 case Decl::CXXConversion: 2475 case Decl::CXXDestructor: 2476 case Decl::CXXConstructor: 2477 valueKind = VK_RValue; 2478 break; 2479 } 2480 2481 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS); 2482 } 2483 2484 } 2485 2486 llvm_unreachable("unknown capture result"); 2487 return ExprError(); 2488 } 2489 2490 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 2491 PredefinedExpr::IdentType IT; 2492 2493 switch (Kind) { 2494 default: llvm_unreachable("Unknown simple primary expr!"); 2495 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 2496 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 2497 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 2498 } 2499 2500 // Pre-defined identifiers are of type char[x], where x is the length of the 2501 // string. 2502 2503 Decl *currentDecl = getCurFunctionOrMethodDecl(); 2504 if (!currentDecl && getCurBlock()) 2505 currentDecl = getCurBlock()->TheDecl; 2506 if (!currentDecl) { 2507 Diag(Loc, diag::ext_predef_outside_function); 2508 currentDecl = Context.getTranslationUnitDecl(); 2509 } 2510 2511 QualType ResTy; 2512 if (cast<DeclContext>(currentDecl)->isDependentContext()) { 2513 ResTy = Context.DependentTy; 2514 } else { 2515 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length(); 2516 2517 llvm::APInt LengthI(32, Length + 1); 2518 ResTy = Context.CharTy.withConst(); 2519 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); 2520 } 2521 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT)); 2522 } 2523 2524 ExprResult Sema::ActOnCharacterConstant(const Token &Tok) { 2525 llvm::SmallString<16> CharBuffer; 2526 bool Invalid = false; 2527 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 2528 if (Invalid) 2529 return ExprError(); 2530 2531 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 2532 PP, Tok.getKind()); 2533 if (Literal.hadError()) 2534 return ExprError(); 2535 2536 QualType Ty; 2537 if (!getLangOptions().CPlusPlus) 2538 Ty = Context.IntTy; // 'x' and L'x' -> int in C. 2539 else if (Literal.isWide()) 2540 Ty = Context.WCharTy; // L'x' -> wchar_t in C++. 2541 else if (Literal.isUTF16()) 2542 Ty = Context.Char16Ty; // u'x' -> char16_t in C++0x. 2543 else if (Literal.isUTF32()) 2544 Ty = Context.Char32Ty; // U'x' -> char32_t in C++0x. 2545 else if (Literal.isMultiChar()) 2546 Ty = Context.IntTy; // 'wxyz' -> int in C++. 2547 else 2548 Ty = Context.CharTy; // 'x' -> char in C++ 2549 2550 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 2551 if (Literal.isWide()) 2552 Kind = CharacterLiteral::Wide; 2553 else if (Literal.isUTF16()) 2554 Kind = CharacterLiteral::UTF16; 2555 else if (Literal.isUTF32()) 2556 Kind = CharacterLiteral::UTF32; 2557 2558 return Owned(new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 2559 Tok.getLocation())); 2560 } 2561 2562 ExprResult Sema::ActOnNumericConstant(const Token &Tok) { 2563 // Fast path for a single digit (which is quite common). A single digit 2564 // cannot have a trigraph, escaped newline, radix prefix, or type suffix. 2565 if (Tok.getLength() == 1) { 2566 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 2567 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 2568 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'), 2569 Context.IntTy, Tok.getLocation())); 2570 } 2571 2572 llvm::SmallString<512> IntegerBuffer; 2573 // Add padding so that NumericLiteralParser can overread by one character. 2574 IntegerBuffer.resize(Tok.getLength()+1); 2575 const char *ThisTokBegin = &IntegerBuffer[0]; 2576 2577 // Get the spelling of the token, which eliminates trigraphs, etc. 2578 bool Invalid = false; 2579 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid); 2580 if (Invalid) 2581 return ExprError(); 2582 2583 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength, 2584 Tok.getLocation(), PP); 2585 if (Literal.hadError) 2586 return ExprError(); 2587 2588 Expr *Res; 2589 2590 if (Literal.isFloatingLiteral()) { 2591 QualType Ty; 2592 if (Literal.isFloat) 2593 Ty = Context.FloatTy; 2594 else if (!Literal.isLong) 2595 Ty = Context.DoubleTy; 2596 else 2597 Ty = Context.LongDoubleTy; 2598 2599 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty); 2600 2601 using llvm::APFloat; 2602 APFloat Val(Format); 2603 2604 APFloat::opStatus result = Literal.GetFloatValue(Val); 2605 2606 // Overflow is always an error, but underflow is only an error if 2607 // we underflowed to zero (APFloat reports denormals as underflow). 2608 if ((result & APFloat::opOverflow) || 2609 ((result & APFloat::opUnderflow) && Val.isZero())) { 2610 unsigned diagnostic; 2611 llvm::SmallString<20> buffer; 2612 if (result & APFloat::opOverflow) { 2613 diagnostic = diag::warn_float_overflow; 2614 APFloat::getLargest(Format).toString(buffer); 2615 } else { 2616 diagnostic = diag::warn_float_underflow; 2617 APFloat::getSmallest(Format).toString(buffer); 2618 } 2619 2620 Diag(Tok.getLocation(), diagnostic) 2621 << Ty 2622 << StringRef(buffer.data(), buffer.size()); 2623 } 2624 2625 bool isExact = (result == APFloat::opOK); 2626 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation()); 2627 2628 if (Ty == Context.DoubleTy) { 2629 if (getLangOptions().SinglePrecisionConstants) { 2630 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 2631 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) { 2632 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 2633 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 2634 } 2635 } 2636 } else if (!Literal.isIntegerLiteral()) { 2637 return ExprError(); 2638 } else { 2639 QualType Ty; 2640 2641 // long long is a C99 feature. 2642 if (!getLangOptions().C99 && Literal.isLongLong) 2643 Diag(Tok.getLocation(), 2644 getLangOptions().CPlusPlus0x ? 2645 diag::warn_cxx98_compat_longlong : diag::ext_longlong); 2646 2647 // Get the value in the widest-possible width. 2648 llvm::APInt ResultVal(Context.getTargetInfo().getIntMaxTWidth(), 0); 2649 2650 if (Literal.GetIntegerValue(ResultVal)) { 2651 // If this value didn't fit into uintmax_t, warn and force to ull. 2652 Diag(Tok.getLocation(), diag::warn_integer_too_large); 2653 Ty = Context.UnsignedLongLongTy; 2654 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 2655 "long long is not intmax_t?"); 2656 } else { 2657 // If this value fits into a ULL, try to figure out what else it fits into 2658 // according to the rules of C99 6.4.4.1p5. 2659 2660 // Octal, Hexadecimal, and integers with a U suffix are allowed to 2661 // be an unsigned int. 2662 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 2663 2664 // Check from smallest to largest, picking the smallest type we can. 2665 unsigned Width = 0; 2666 if (!Literal.isLong && !Literal.isLongLong) { 2667 // Are int/unsigned possibilities? 2668 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 2669 2670 // Does it fit in a unsigned int? 2671 if (ResultVal.isIntN(IntSize)) { 2672 // Does it fit in a signed int? 2673 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 2674 Ty = Context.IntTy; 2675 else if (AllowUnsigned) 2676 Ty = Context.UnsignedIntTy; 2677 Width = IntSize; 2678 } 2679 } 2680 2681 // Are long/unsigned long possibilities? 2682 if (Ty.isNull() && !Literal.isLongLong) { 2683 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 2684 2685 // Does it fit in a unsigned long? 2686 if (ResultVal.isIntN(LongSize)) { 2687 // Does it fit in a signed long? 2688 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 2689 Ty = Context.LongTy; 2690 else if (AllowUnsigned) 2691 Ty = Context.UnsignedLongTy; 2692 Width = LongSize; 2693 } 2694 } 2695 2696 // Finally, check long long if needed. 2697 if (Ty.isNull()) { 2698 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 2699 2700 // Does it fit in a unsigned long long? 2701 if (ResultVal.isIntN(LongLongSize)) { 2702 // Does it fit in a signed long long? 2703 // To be compatible with MSVC, hex integer literals ending with the 2704 // LL or i64 suffix are always signed in Microsoft mode. 2705 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 2706 (getLangOptions().MicrosoftExt && Literal.isLongLong))) 2707 Ty = Context.LongLongTy; 2708 else if (AllowUnsigned) 2709 Ty = Context.UnsignedLongLongTy; 2710 Width = LongLongSize; 2711 } 2712 } 2713 2714 // If we still couldn't decide a type, we probably have something that 2715 // does not fit in a signed long long, but has no U suffix. 2716 if (Ty.isNull()) { 2717 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed); 2718 Ty = Context.UnsignedLongLongTy; 2719 Width = Context.getTargetInfo().getLongLongWidth(); 2720 } 2721 2722 if (ResultVal.getBitWidth() != Width) 2723 ResultVal = ResultVal.trunc(Width); 2724 } 2725 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 2726 } 2727 2728 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 2729 if (Literal.isImaginary) 2730 Res = new (Context) ImaginaryLiteral(Res, 2731 Context.getComplexType(Res->getType())); 2732 2733 return Owned(Res); 2734 } 2735 2736 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 2737 assert((E != 0) && "ActOnParenExpr() missing expr"); 2738 return Owned(new (Context) ParenExpr(L, R, E)); 2739 } 2740 2741 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 2742 SourceLocation Loc, 2743 SourceRange ArgRange) { 2744 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 2745 // scalar or vector data type argument..." 2746 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 2747 // type (C99 6.2.5p18) or void. 2748 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 2749 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 2750 << T << ArgRange; 2751 return true; 2752 } 2753 2754 assert((T->isVoidType() || !T->isIncompleteType()) && 2755 "Scalar types should always be complete"); 2756 return false; 2757 } 2758 2759 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 2760 SourceLocation Loc, 2761 SourceRange ArgRange, 2762 UnaryExprOrTypeTrait TraitKind) { 2763 // C99 6.5.3.4p1: 2764 if (T->isFunctionType()) { 2765 // alignof(function) is allowed as an extension. 2766 if (TraitKind == UETT_SizeOf) 2767 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange; 2768 return false; 2769 } 2770 2771 // Allow sizeof(void)/alignof(void) as an extension. 2772 if (T->isVoidType()) { 2773 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange; 2774 return false; 2775 } 2776 2777 return true; 2778 } 2779 2780 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 2781 SourceLocation Loc, 2782 SourceRange ArgRange, 2783 UnaryExprOrTypeTrait TraitKind) { 2784 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode. 2785 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) { 2786 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 2787 << T << (TraitKind == UETT_SizeOf) 2788 << ArgRange; 2789 return true; 2790 } 2791 2792 return false; 2793 } 2794 2795 /// \brief Check the constrains on expression operands to unary type expression 2796 /// and type traits. 2797 /// 2798 /// Completes any types necessary and validates the constraints on the operand 2799 /// expression. The logic mostly mirrors the type-based overload, but may modify 2800 /// the expression as it completes the type for that expression through template 2801 /// instantiation, etc. 2802 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 2803 UnaryExprOrTypeTrait ExprKind) { 2804 QualType ExprTy = E->getType(); 2805 2806 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 2807 // the result is the size of the referenced type." 2808 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 2809 // result shall be the alignment of the referenced type." 2810 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>()) 2811 ExprTy = Ref->getPointeeType(); 2812 2813 if (ExprKind == UETT_VecStep) 2814 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 2815 E->getSourceRange()); 2816 2817 // Whitelist some types as extensions 2818 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 2819 E->getSourceRange(), ExprKind)) 2820 return false; 2821 2822 if (RequireCompleteExprType(E, 2823 PDiag(diag::err_sizeof_alignof_incomplete_type) 2824 << ExprKind << E->getSourceRange(), 2825 std::make_pair(SourceLocation(), PDiag(0)))) 2826 return true; 2827 2828 // Completeing the expression's type may have changed it. 2829 ExprTy = E->getType(); 2830 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>()) 2831 ExprTy = Ref->getPointeeType(); 2832 2833 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 2834 E->getSourceRange(), ExprKind)) 2835 return true; 2836 2837 if (ExprKind == UETT_SizeOf) { 2838 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 2839 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 2840 QualType OType = PVD->getOriginalType(); 2841 QualType Type = PVD->getType(); 2842 if (Type->isPointerType() && OType->isArrayType()) { 2843 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 2844 << Type << OType; 2845 Diag(PVD->getLocation(), diag::note_declared_at); 2846 } 2847 } 2848 } 2849 } 2850 2851 return false; 2852 } 2853 2854 /// \brief Check the constraints on operands to unary expression and type 2855 /// traits. 2856 /// 2857 /// This will complete any types necessary, and validate the various constraints 2858 /// on those operands. 2859 /// 2860 /// The UsualUnaryConversions() function is *not* called by this routine. 2861 /// C99 6.3.2.1p[2-4] all state: 2862 /// Except when it is the operand of the sizeof operator ... 2863 /// 2864 /// C++ [expr.sizeof]p4 2865 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 2866 /// standard conversions are not applied to the operand of sizeof. 2867 /// 2868 /// This policy is followed for all of the unary trait expressions. 2869 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 2870 SourceLocation OpLoc, 2871 SourceRange ExprRange, 2872 UnaryExprOrTypeTrait ExprKind) { 2873 if (ExprType->isDependentType()) 2874 return false; 2875 2876 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 2877 // the result is the size of the referenced type." 2878 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 2879 // result shall be the alignment of the referenced type." 2880 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 2881 ExprType = Ref->getPointeeType(); 2882 2883 if (ExprKind == UETT_VecStep) 2884 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 2885 2886 // Whitelist some types as extensions 2887 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 2888 ExprKind)) 2889 return false; 2890 2891 if (RequireCompleteType(OpLoc, ExprType, 2892 PDiag(diag::err_sizeof_alignof_incomplete_type) 2893 << ExprKind << ExprRange)) 2894 return true; 2895 2896 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 2897 ExprKind)) 2898 return true; 2899 2900 return false; 2901 } 2902 2903 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 2904 E = E->IgnoreParens(); 2905 2906 // alignof decl is always ok. 2907 if (isa<DeclRefExpr>(E)) 2908 return false; 2909 2910 // Cannot know anything else if the expression is dependent. 2911 if (E->isTypeDependent()) 2912 return false; 2913 2914 if (E->getBitField()) { 2915 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) 2916 << 1 << E->getSourceRange(); 2917 return true; 2918 } 2919 2920 // Alignment of a field access is always okay, so long as it isn't a 2921 // bit-field. 2922 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) 2923 if (isa<FieldDecl>(ME->getMemberDecl())) 2924 return false; 2925 2926 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 2927 } 2928 2929 bool Sema::CheckVecStepExpr(Expr *E) { 2930 E = E->IgnoreParens(); 2931 2932 // Cannot know anything else if the expression is dependent. 2933 if (E->isTypeDependent()) 2934 return false; 2935 2936 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 2937 } 2938 2939 /// \brief Build a sizeof or alignof expression given a type operand. 2940 ExprResult 2941 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 2942 SourceLocation OpLoc, 2943 UnaryExprOrTypeTrait ExprKind, 2944 SourceRange R) { 2945 if (!TInfo) 2946 return ExprError(); 2947 2948 QualType T = TInfo->getType(); 2949 2950 if (!T->isDependentType() && 2951 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 2952 return ExprError(); 2953 2954 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 2955 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo, 2956 Context.getSizeType(), 2957 OpLoc, R.getEnd())); 2958 } 2959 2960 /// \brief Build a sizeof or alignof expression given an expression 2961 /// operand. 2962 ExprResult 2963 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 2964 UnaryExprOrTypeTrait ExprKind) { 2965 ExprResult PE = CheckPlaceholderExpr(E); 2966 if (PE.isInvalid()) 2967 return ExprError(); 2968 2969 E = PE.get(); 2970 2971 // Verify that the operand is valid. 2972 bool isInvalid = false; 2973 if (E->isTypeDependent()) { 2974 // Delay type-checking for type-dependent expressions. 2975 } else if (ExprKind == UETT_AlignOf) { 2976 isInvalid = CheckAlignOfExpr(*this, E); 2977 } else if (ExprKind == UETT_VecStep) { 2978 isInvalid = CheckVecStepExpr(E); 2979 } else if (E->getBitField()) { // C99 6.5.3.4p1. 2980 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0; 2981 isInvalid = true; 2982 } else { 2983 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 2984 } 2985 2986 if (isInvalid) 2987 return ExprError(); 2988 2989 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 2990 return Owned(new (Context) UnaryExprOrTypeTraitExpr( 2991 ExprKind, E, Context.getSizeType(), OpLoc, 2992 E->getSourceRange().getEnd())); 2993 } 2994 2995 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 2996 /// expr and the same for @c alignof and @c __alignof 2997 /// Note that the ArgRange is invalid if isType is false. 2998 ExprResult 2999 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 3000 UnaryExprOrTypeTrait ExprKind, bool IsType, 3001 void *TyOrEx, const SourceRange &ArgRange) { 3002 // If error parsing type, ignore. 3003 if (TyOrEx == 0) return ExprError(); 3004 3005 if (IsType) { 3006 TypeSourceInfo *TInfo; 3007 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 3008 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 3009 } 3010 3011 Expr *ArgEx = (Expr *)TyOrEx; 3012 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 3013 return move(Result); 3014 } 3015 3016 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 3017 bool IsReal) { 3018 if (V.get()->isTypeDependent()) 3019 return S.Context.DependentTy; 3020 3021 // _Real and _Imag are only l-values for normal l-values. 3022 if (V.get()->getObjectKind() != OK_Ordinary) { 3023 V = S.DefaultLvalueConversion(V.take()); 3024 if (V.isInvalid()) 3025 return QualType(); 3026 } 3027 3028 // These operators return the element type of a complex type. 3029 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 3030 return CT->getElementType(); 3031 3032 // Otherwise they pass through real integer and floating point types here. 3033 if (V.get()->getType()->isArithmeticType()) 3034 return V.get()->getType(); 3035 3036 // Test for placeholders. 3037 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 3038 if (PR.isInvalid()) return QualType(); 3039 if (PR.get() != V.get()) { 3040 V = move(PR); 3041 return CheckRealImagOperand(S, V, Loc, IsReal); 3042 } 3043 3044 // Reject anything else. 3045 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 3046 << (IsReal ? "__real" : "__imag"); 3047 return QualType(); 3048 } 3049 3050 3051 3052 ExprResult 3053 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 3054 tok::TokenKind Kind, Expr *Input) { 3055 UnaryOperatorKind Opc; 3056 switch (Kind) { 3057 default: llvm_unreachable("Unknown unary op!"); 3058 case tok::plusplus: Opc = UO_PostInc; break; 3059 case tok::minusminus: Opc = UO_PostDec; break; 3060 } 3061 3062 return BuildUnaryOp(S, OpLoc, Opc, Input); 3063 } 3064 3065 ExprResult 3066 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, 3067 Expr *Idx, SourceLocation RLoc) { 3068 // Since this might be a postfix expression, get rid of ParenListExprs. 3069 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base); 3070 if (Result.isInvalid()) return ExprError(); 3071 Base = Result.take(); 3072 3073 Expr *LHSExp = Base, *RHSExp = Idx; 3074 3075 if (getLangOptions().CPlusPlus && 3076 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) { 3077 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 3078 Context.DependentTy, 3079 VK_LValue, OK_Ordinary, 3080 RLoc)); 3081 } 3082 3083 if (getLangOptions().CPlusPlus && 3084 (LHSExp->getType()->isRecordType() || 3085 LHSExp->getType()->isEnumeralType() || 3086 RHSExp->getType()->isRecordType() || 3087 RHSExp->getType()->isEnumeralType())) { 3088 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx); 3089 } 3090 3091 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc); 3092 } 3093 3094 3095 ExprResult 3096 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 3097 Expr *Idx, SourceLocation RLoc) { 3098 Expr *LHSExp = Base; 3099 Expr *RHSExp = Idx; 3100 3101 // Perform default conversions. 3102 if (!LHSExp->getType()->getAs<VectorType>()) { 3103 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 3104 if (Result.isInvalid()) 3105 return ExprError(); 3106 LHSExp = Result.take(); 3107 } 3108 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 3109 if (Result.isInvalid()) 3110 return ExprError(); 3111 RHSExp = Result.take(); 3112 3113 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 3114 ExprValueKind VK = VK_LValue; 3115 ExprObjectKind OK = OK_Ordinary; 3116 3117 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 3118 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 3119 // in the subscript position. As a result, we need to derive the array base 3120 // and index from the expression types. 3121 Expr *BaseExpr, *IndexExpr; 3122 QualType ResultType; 3123 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 3124 BaseExpr = LHSExp; 3125 IndexExpr = RHSExp; 3126 ResultType = Context.DependentTy; 3127 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 3128 BaseExpr = LHSExp; 3129 IndexExpr = RHSExp; 3130 ResultType = PTy->getPointeeType(); 3131 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 3132 // Handle the uncommon case of "123[Ptr]". 3133 BaseExpr = RHSExp; 3134 IndexExpr = LHSExp; 3135 ResultType = PTy->getPointeeType(); 3136 } else if (const ObjCObjectPointerType *PTy = 3137 LHSTy->getAs<ObjCObjectPointerType>()) { 3138 BaseExpr = LHSExp; 3139 IndexExpr = RHSExp; 3140 ResultType = PTy->getPointeeType(); 3141 } else if (const ObjCObjectPointerType *PTy = 3142 RHSTy->getAs<ObjCObjectPointerType>()) { 3143 // Handle the uncommon case of "123[Ptr]". 3144 BaseExpr = RHSExp; 3145 IndexExpr = LHSExp; 3146 ResultType = PTy->getPointeeType(); 3147 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 3148 BaseExpr = LHSExp; // vectors: V[123] 3149 IndexExpr = RHSExp; 3150 VK = LHSExp->getValueKind(); 3151 if (VK != VK_RValue) 3152 OK = OK_VectorComponent; 3153 3154 // FIXME: need to deal with const... 3155 ResultType = VTy->getElementType(); 3156 } else if (LHSTy->isArrayType()) { 3157 // If we see an array that wasn't promoted by 3158 // DefaultFunctionArrayLvalueConversion, it must be an array that 3159 // wasn't promoted because of the C90 rule that doesn't 3160 // allow promoting non-lvalue arrays. Warn, then 3161 // force the promotion here. 3162 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3163 LHSExp->getSourceRange(); 3164 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 3165 CK_ArrayToPointerDecay).take(); 3166 LHSTy = LHSExp->getType(); 3167 3168 BaseExpr = LHSExp; 3169 IndexExpr = RHSExp; 3170 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 3171 } else if (RHSTy->isArrayType()) { 3172 // Same as previous, except for 123[f().a] case 3173 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3174 RHSExp->getSourceRange(); 3175 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 3176 CK_ArrayToPointerDecay).take(); 3177 RHSTy = RHSExp->getType(); 3178 3179 BaseExpr = RHSExp; 3180 IndexExpr = LHSExp; 3181 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 3182 } else { 3183 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 3184 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 3185 } 3186 // C99 6.5.2.1p1 3187 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 3188 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 3189 << IndexExpr->getSourceRange()); 3190 3191 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 3192 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 3193 && !IndexExpr->isTypeDependent()) 3194 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 3195 3196 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 3197 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 3198 // type. Note that Functions are not objects, and that (in C99 parlance) 3199 // incomplete types are not object types. 3200 if (ResultType->isFunctionType()) { 3201 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 3202 << ResultType << BaseExpr->getSourceRange(); 3203 return ExprError(); 3204 } 3205 3206 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) { 3207 // GNU extension: subscripting on pointer to void 3208 Diag(LLoc, diag::ext_gnu_subscript_void_type) 3209 << BaseExpr->getSourceRange(); 3210 3211 // C forbids expressions of unqualified void type from being l-values. 3212 // See IsCForbiddenLValueType. 3213 if (!ResultType.hasQualifiers()) VK = VK_RValue; 3214 } else if (!ResultType->isDependentType() && 3215 RequireCompleteType(LLoc, ResultType, 3216 PDiag(diag::err_subscript_incomplete_type) 3217 << BaseExpr->getSourceRange())) 3218 return ExprError(); 3219 3220 // Diagnose bad cases where we step over interface counts. 3221 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) { 3222 Diag(LLoc, diag::err_subscript_nonfragile_interface) 3223 << ResultType << BaseExpr->getSourceRange(); 3224 return ExprError(); 3225 } 3226 3227 assert(VK == VK_RValue || LangOpts.CPlusPlus || 3228 !ResultType.isCForbiddenLValueType()); 3229 3230 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 3231 ResultType, VK, OK, RLoc)); 3232 } 3233 3234 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 3235 FunctionDecl *FD, 3236 ParmVarDecl *Param) { 3237 if (Param->hasUnparsedDefaultArg()) { 3238 Diag(CallLoc, 3239 diag::err_use_of_default_argument_to_function_declared_later) << 3240 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 3241 Diag(UnparsedDefaultArgLocs[Param], 3242 diag::note_default_argument_declared_here); 3243 return ExprError(); 3244 } 3245 3246 if (Param->hasUninstantiatedDefaultArg()) { 3247 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 3248 3249 // Instantiate the expression. 3250 MultiLevelTemplateArgumentList ArgList 3251 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true); 3252 3253 std::pair<const TemplateArgument *, unsigned> Innermost 3254 = ArgList.getInnermost(); 3255 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first, 3256 Innermost.second); 3257 3258 ExprResult Result; 3259 { 3260 // C++ [dcl.fct.default]p5: 3261 // The names in the [default argument] expression are bound, and 3262 // the semantic constraints are checked, at the point where the 3263 // default argument expression appears. 3264 ContextRAII SavedContext(*this, FD); 3265 Result = SubstExpr(UninstExpr, ArgList); 3266 } 3267 if (Result.isInvalid()) 3268 return ExprError(); 3269 3270 // Check the expression as an initializer for the parameter. 3271 InitializedEntity Entity 3272 = InitializedEntity::InitializeParameter(Context, Param); 3273 InitializationKind Kind 3274 = InitializationKind::CreateCopy(Param->getLocation(), 3275 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin()); 3276 Expr *ResultE = Result.takeAs<Expr>(); 3277 3278 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1); 3279 Result = InitSeq.Perform(*this, Entity, Kind, 3280 MultiExprArg(*this, &ResultE, 1)); 3281 if (Result.isInvalid()) 3282 return ExprError(); 3283 3284 // Build the default argument expression. 3285 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, 3286 Result.takeAs<Expr>())); 3287 } 3288 3289 // If the default expression creates temporaries, we need to 3290 // push them to the current stack of expression temporaries so they'll 3291 // be properly destroyed. 3292 // FIXME: We should really be rebuilding the default argument with new 3293 // bound temporaries; see the comment in PR5810. 3294 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) { 3295 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i); 3296 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(), 3297 const_cast<CXXDestructorDecl*>(Temporary->getDestructor())); 3298 ExprTemporaries.push_back(Temporary); 3299 ExprNeedsCleanups = true; 3300 } 3301 3302 // We already type-checked the argument, so we know it works. 3303 // Just mark all of the declarations in this potentially-evaluated expression 3304 // as being "referenced". 3305 MarkDeclarationsReferencedInExpr(Param->getDefaultArg()); 3306 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param)); 3307 } 3308 3309 /// ConvertArgumentsForCall - Converts the arguments specified in 3310 /// Args/NumArgs to the parameter types of the function FDecl with 3311 /// function prototype Proto. Call is the call expression itself, and 3312 /// Fn is the function expression. For a C++ member function, this 3313 /// routine does not attempt to convert the object argument. Returns 3314 /// true if the call is ill-formed. 3315 bool 3316 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 3317 FunctionDecl *FDecl, 3318 const FunctionProtoType *Proto, 3319 Expr **Args, unsigned NumArgs, 3320 SourceLocation RParenLoc, 3321 bool IsExecConfig) { 3322 // Bail out early if calling a builtin with custom typechecking. 3323 // We don't need to do this in the 3324 if (FDecl) 3325 if (unsigned ID = FDecl->getBuiltinID()) 3326 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 3327 return false; 3328 3329 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 3330 // assignment, to the types of the corresponding parameter, ... 3331 unsigned NumArgsInProto = Proto->getNumArgs(); 3332 bool Invalid = false; 3333 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto; 3334 unsigned FnKind = Fn->getType()->isBlockPointerType() 3335 ? 1 /* block */ 3336 : (IsExecConfig ? 3 /* kernel function (exec config) */ 3337 : 0 /* function */); 3338 3339 // If too few arguments are available (and we don't have default 3340 // arguments for the remaining parameters), don't make the call. 3341 if (NumArgs < NumArgsInProto) { 3342 if (NumArgs < MinArgs) { 3343 Diag(RParenLoc, MinArgs == NumArgsInProto 3344 ? diag::err_typecheck_call_too_few_args 3345 : diag::err_typecheck_call_too_few_args_at_least) 3346 << FnKind 3347 << MinArgs << NumArgs << Fn->getSourceRange(); 3348 3349 // Emit the location of the prototype. 3350 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 3351 Diag(FDecl->getLocStart(), diag::note_callee_decl) 3352 << FDecl; 3353 3354 return true; 3355 } 3356 Call->setNumArgs(Context, NumArgsInProto); 3357 } 3358 3359 // If too many are passed and not variadic, error on the extras and drop 3360 // them. 3361 if (NumArgs > NumArgsInProto) { 3362 if (!Proto->isVariadic()) { 3363 Diag(Args[NumArgsInProto]->getLocStart(), 3364 MinArgs == NumArgsInProto 3365 ? diag::err_typecheck_call_too_many_args 3366 : diag::err_typecheck_call_too_many_args_at_most) 3367 << FnKind 3368 << NumArgsInProto << NumArgs << Fn->getSourceRange() 3369 << SourceRange(Args[NumArgsInProto]->getLocStart(), 3370 Args[NumArgs-1]->getLocEnd()); 3371 3372 // Emit the location of the prototype. 3373 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 3374 Diag(FDecl->getLocStart(), diag::note_callee_decl) 3375 << FDecl; 3376 3377 // This deletes the extra arguments. 3378 Call->setNumArgs(Context, NumArgsInProto); 3379 return true; 3380 } 3381 } 3382 SmallVector<Expr *, 8> AllArgs; 3383 VariadicCallType CallType = 3384 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply; 3385 if (Fn->getType()->isBlockPointerType()) 3386 CallType = VariadicBlock; // Block 3387 else if (isa<MemberExpr>(Fn)) 3388 CallType = VariadicMethod; 3389 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl, 3390 Proto, 0, Args, NumArgs, AllArgs, CallType); 3391 if (Invalid) 3392 return true; 3393 unsigned TotalNumArgs = AllArgs.size(); 3394 for (unsigned i = 0; i < TotalNumArgs; ++i) 3395 Call->setArg(i, AllArgs[i]); 3396 3397 return false; 3398 } 3399 3400 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, 3401 FunctionDecl *FDecl, 3402 const FunctionProtoType *Proto, 3403 unsigned FirstProtoArg, 3404 Expr **Args, unsigned NumArgs, 3405 SmallVector<Expr *, 8> &AllArgs, 3406 VariadicCallType CallType) { 3407 unsigned NumArgsInProto = Proto->getNumArgs(); 3408 unsigned NumArgsToCheck = NumArgs; 3409 bool Invalid = false; 3410 if (NumArgs != NumArgsInProto) 3411 // Use default arguments for missing arguments 3412 NumArgsToCheck = NumArgsInProto; 3413 unsigned ArgIx = 0; 3414 // Continue to check argument types (even if we have too few/many args). 3415 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) { 3416 QualType ProtoArgType = Proto->getArgType(i); 3417 3418 Expr *Arg; 3419 ParmVarDecl *Param; 3420 if (ArgIx < NumArgs) { 3421 Arg = Args[ArgIx++]; 3422 3423 if (RequireCompleteType(Arg->getSourceRange().getBegin(), 3424 ProtoArgType, 3425 PDiag(diag::err_call_incomplete_argument) 3426 << Arg->getSourceRange())) 3427 return true; 3428 3429 // Pass the argument 3430 Param = 0; 3431 if (FDecl && i < FDecl->getNumParams()) 3432 Param = FDecl->getParamDecl(i); 3433 3434 // Strip the unbridged-cast placeholder expression off, if applicable. 3435 if (Arg->getType() == Context.ARCUnbridgedCastTy && 3436 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 3437 (!Param || !Param->hasAttr<CFConsumedAttr>())) 3438 Arg = stripARCUnbridgedCast(Arg); 3439 3440 InitializedEntity Entity = 3441 Param? InitializedEntity::InitializeParameter(Context, Param) 3442 : InitializedEntity::InitializeParameter(Context, ProtoArgType, 3443 Proto->isArgConsumed(i)); 3444 ExprResult ArgE = PerformCopyInitialization(Entity, 3445 SourceLocation(), 3446 Owned(Arg)); 3447 if (ArgE.isInvalid()) 3448 return true; 3449 3450 Arg = ArgE.takeAs<Expr>(); 3451 } else { 3452 Param = FDecl->getParamDecl(i); 3453 3454 ExprResult ArgExpr = 3455 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 3456 if (ArgExpr.isInvalid()) 3457 return true; 3458 3459 Arg = ArgExpr.takeAs<Expr>(); 3460 } 3461 3462 // Check for array bounds violations for each argument to the call. This 3463 // check only triggers warnings when the argument isn't a more complex Expr 3464 // with its own checking, such as a BinaryOperator. 3465 CheckArrayAccess(Arg); 3466 3467 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 3468 CheckStaticArrayArgument(CallLoc, Param, Arg); 3469 3470 AllArgs.push_back(Arg); 3471 } 3472 3473 // If this is a variadic call, handle args passed through "...". 3474 if (CallType != VariadicDoesNotApply) { 3475 3476 // Assume that extern "C" functions with variadic arguments that 3477 // return __unknown_anytype aren't *really* variadic. 3478 if (Proto->getResultType() == Context.UnknownAnyTy && 3479 FDecl && FDecl->isExternC()) { 3480 for (unsigned i = ArgIx; i != NumArgs; ++i) { 3481 ExprResult arg; 3482 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens())) 3483 arg = DefaultFunctionArrayLvalueConversion(Args[i]); 3484 else 3485 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl); 3486 Invalid |= arg.isInvalid(); 3487 AllArgs.push_back(arg.take()); 3488 } 3489 3490 // Otherwise do argument promotion, (C99 6.5.2.2p7). 3491 } else { 3492 for (unsigned i = ArgIx; i != NumArgs; ++i) { 3493 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, 3494 FDecl); 3495 Invalid |= Arg.isInvalid(); 3496 AllArgs.push_back(Arg.take()); 3497 } 3498 } 3499 3500 // Check for array bounds violations. 3501 for (unsigned i = ArgIx; i != NumArgs; ++i) 3502 CheckArrayAccess(Args[i]); 3503 } 3504 return Invalid; 3505 } 3506 3507 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 3508 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 3509 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL)) 3510 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 3511 << ATL->getLocalSourceRange(); 3512 } 3513 3514 /// CheckStaticArrayArgument - If the given argument corresponds to a static 3515 /// array parameter, check that it is non-null, and that if it is formed by 3516 /// array-to-pointer decay, the underlying array is sufficiently large. 3517 /// 3518 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 3519 /// array type derivation, then for each call to the function, the value of the 3520 /// corresponding actual argument shall provide access to the first element of 3521 /// an array with at least as many elements as specified by the size expression. 3522 void 3523 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 3524 ParmVarDecl *Param, 3525 const Expr *ArgExpr) { 3526 // Static array parameters are not supported in C++. 3527 if (!Param || getLangOptions().CPlusPlus) 3528 return; 3529 3530 QualType OrigTy = Param->getOriginalType(); 3531 3532 const ArrayType *AT = Context.getAsArrayType(OrigTy); 3533 if (!AT || AT->getSizeModifier() != ArrayType::Static) 3534 return; 3535 3536 if (ArgExpr->isNullPointerConstant(Context, 3537 Expr::NPC_NeverValueDependent)) { 3538 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 3539 DiagnoseCalleeStaticArrayParam(*this, Param); 3540 return; 3541 } 3542 3543 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 3544 if (!CAT) 3545 return; 3546 3547 const ConstantArrayType *ArgCAT = 3548 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 3549 if (!ArgCAT) 3550 return; 3551 3552 if (ArgCAT->getSize().ult(CAT->getSize())) { 3553 Diag(CallLoc, diag::warn_static_array_too_small) 3554 << ArgExpr->getSourceRange() 3555 << (unsigned) ArgCAT->getSize().getZExtValue() 3556 << (unsigned) CAT->getSize().getZExtValue(); 3557 DiagnoseCalleeStaticArrayParam(*this, Param); 3558 } 3559 } 3560 3561 /// Given a function expression of unknown-any type, try to rebuild it 3562 /// to have a function type. 3563 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 3564 3565 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 3566 /// This provides the location of the left/right parens and a list of comma 3567 /// locations. 3568 ExprResult 3569 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 3570 MultiExprArg ArgExprs, SourceLocation RParenLoc, 3571 Expr *ExecConfig, bool IsExecConfig) { 3572 unsigned NumArgs = ArgExprs.size(); 3573 3574 // Since this might be a postfix expression, get rid of ParenListExprs. 3575 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 3576 if (Result.isInvalid()) return ExprError(); 3577 Fn = Result.take(); 3578 3579 Expr **Args = ArgExprs.release(); 3580 3581 if (getLangOptions().CPlusPlus) { 3582 // If this is a pseudo-destructor expression, build the call immediately. 3583 if (isa<CXXPseudoDestructorExpr>(Fn)) { 3584 if (NumArgs > 0) { 3585 // Pseudo-destructor calls should not have any arguments. 3586 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 3587 << FixItHint::CreateRemoval( 3588 SourceRange(Args[0]->getLocStart(), 3589 Args[NumArgs-1]->getLocEnd())); 3590 3591 NumArgs = 0; 3592 } 3593 3594 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy, 3595 VK_RValue, RParenLoc)); 3596 } 3597 3598 // Determine whether this is a dependent call inside a C++ template, 3599 // in which case we won't do any semantic analysis now. 3600 // FIXME: Will need to cache the results of name lookup (including ADL) in 3601 // Fn. 3602 bool Dependent = false; 3603 if (Fn->isTypeDependent()) 3604 Dependent = true; 3605 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs)) 3606 Dependent = true; 3607 3608 if (Dependent) { 3609 if (ExecConfig) { 3610 return Owned(new (Context) CUDAKernelCallExpr( 3611 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs, 3612 Context.DependentTy, VK_RValue, RParenLoc)); 3613 } else { 3614 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs, 3615 Context.DependentTy, VK_RValue, 3616 RParenLoc)); 3617 } 3618 } 3619 3620 // Determine whether this is a call to an object (C++ [over.call.object]). 3621 if (Fn->getType()->isRecordType()) 3622 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs, 3623 RParenLoc)); 3624 3625 if (Fn->getType() == Context.UnknownAnyTy) { 3626 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 3627 if (result.isInvalid()) return ExprError(); 3628 Fn = result.take(); 3629 } 3630 3631 if (Fn->getType() == Context.BoundMemberTy) { 3632 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs, 3633 RParenLoc); 3634 } 3635 } 3636 3637 // Check for overloaded calls. This can happen even in C due to extensions. 3638 if (Fn->getType() == Context.OverloadTy) { 3639 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 3640 3641 // We aren't supposed to apply this logic for if there's an '&' involved. 3642 if (!find.HasFormOfMemberPointer) { 3643 OverloadExpr *ovl = find.Expression; 3644 if (isa<UnresolvedLookupExpr>(ovl)) { 3645 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl); 3646 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs, 3647 RParenLoc, ExecConfig); 3648 } else { 3649 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs, 3650 RParenLoc); 3651 } 3652 } 3653 } 3654 3655 // If we're directly calling a function, get the appropriate declaration. 3656 3657 Expr *NakedFn = Fn->IgnoreParens(); 3658 3659 NamedDecl *NDecl = 0; 3660 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) 3661 if (UnOp->getOpcode() == UO_AddrOf) 3662 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 3663 3664 if (isa<DeclRefExpr>(NakedFn)) 3665 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 3666 else if (isa<MemberExpr>(NakedFn)) 3667 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 3668 3669 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc, 3670 ExecConfig, IsExecConfig); 3671 } 3672 3673 ExprResult 3674 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 3675 MultiExprArg ExecConfig, SourceLocation GGGLoc) { 3676 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl(); 3677 if (!ConfigDecl) 3678 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use) 3679 << "cudaConfigureCall"); 3680 QualType ConfigQTy = ConfigDecl->getType(); 3681 3682 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr( 3683 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc); 3684 3685 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0, 3686 /*IsExecConfig=*/true); 3687 } 3688 3689 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 3690 /// 3691 /// __builtin_astype( value, dst type ) 3692 /// 3693 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 3694 SourceLocation BuiltinLoc, 3695 SourceLocation RParenLoc) { 3696 ExprValueKind VK = VK_RValue; 3697 ExprObjectKind OK = OK_Ordinary; 3698 QualType DstTy = GetTypeFromParser(ParsedDestTy); 3699 QualType SrcTy = E->getType(); 3700 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 3701 return ExprError(Diag(BuiltinLoc, 3702 diag::err_invalid_astype_of_different_size) 3703 << DstTy 3704 << SrcTy 3705 << E->getSourceRange()); 3706 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, 3707 RParenLoc)); 3708 } 3709 3710 /// BuildResolvedCallExpr - Build a call to a resolved expression, 3711 /// i.e. an expression not of \p OverloadTy. The expression should 3712 /// unary-convert to an expression of function-pointer or 3713 /// block-pointer type. 3714 /// 3715 /// \param NDecl the declaration being called, if available 3716 ExprResult 3717 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 3718 SourceLocation LParenLoc, 3719 Expr **Args, unsigned NumArgs, 3720 SourceLocation RParenLoc, 3721 Expr *Config, bool IsExecConfig) { 3722 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 3723 3724 // Promote the function operand. 3725 ExprResult Result = UsualUnaryConversions(Fn); 3726 if (Result.isInvalid()) 3727 return ExprError(); 3728 Fn = Result.take(); 3729 3730 // Make the call expr early, before semantic checks. This guarantees cleanup 3731 // of arguments and function on error. 3732 CallExpr *TheCall; 3733 if (Config) { 3734 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 3735 cast<CallExpr>(Config), 3736 Args, NumArgs, 3737 Context.BoolTy, 3738 VK_RValue, 3739 RParenLoc); 3740 } else { 3741 TheCall = new (Context) CallExpr(Context, Fn, 3742 Args, NumArgs, 3743 Context.BoolTy, 3744 VK_RValue, 3745 RParenLoc); 3746 } 3747 3748 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 3749 3750 // Bail out early if calling a builtin with custom typechecking. 3751 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 3752 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 3753 3754 retry: 3755 const FunctionType *FuncT; 3756 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 3757 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 3758 // have type pointer to function". 3759 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 3760 if (FuncT == 0) 3761 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 3762 << Fn->getType() << Fn->getSourceRange()); 3763 } else if (const BlockPointerType *BPT = 3764 Fn->getType()->getAs<BlockPointerType>()) { 3765 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 3766 } else { 3767 // Handle calls to expressions of unknown-any type. 3768 if (Fn->getType() == Context.UnknownAnyTy) { 3769 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 3770 if (rewrite.isInvalid()) return ExprError(); 3771 Fn = rewrite.take(); 3772 TheCall->setCallee(Fn); 3773 goto retry; 3774 } 3775 3776 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 3777 << Fn->getType() << Fn->getSourceRange()); 3778 } 3779 3780 if (getLangOptions().CUDA) { 3781 if (Config) { 3782 // CUDA: Kernel calls must be to global functions 3783 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 3784 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 3785 << FDecl->getName() << Fn->getSourceRange()); 3786 3787 // CUDA: Kernel function must have 'void' return type 3788 if (!FuncT->getResultType()->isVoidType()) 3789 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 3790 << Fn->getType() << Fn->getSourceRange()); 3791 } else { 3792 // CUDA: Calls to global functions must be configured 3793 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 3794 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 3795 << FDecl->getName() << Fn->getSourceRange()); 3796 } 3797 } 3798 3799 // Check for a valid return type 3800 if (CheckCallReturnType(FuncT->getResultType(), 3801 Fn->getSourceRange().getBegin(), TheCall, 3802 FDecl)) 3803 return ExprError(); 3804 3805 // We know the result type of the call, set it. 3806 TheCall->setType(FuncT->getCallResultType(Context)); 3807 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType())); 3808 3809 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) { 3810 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs, 3811 RParenLoc, IsExecConfig)) 3812 return ExprError(); 3813 } else { 3814 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 3815 3816 if (FDecl) { 3817 // Check if we have too few/too many template arguments, based 3818 // on our knowledge of the function definition. 3819 const FunctionDecl *Def = 0; 3820 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) { 3821 const FunctionProtoType *Proto 3822 = Def->getType()->getAs<FunctionProtoType>(); 3823 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) 3824 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 3825 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange(); 3826 } 3827 3828 // If the function we're calling isn't a function prototype, but we have 3829 // a function prototype from a prior declaratiom, use that prototype. 3830 if (!FDecl->hasPrototype()) 3831 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 3832 } 3833 3834 // Promote the arguments (C99 6.5.2.2p6). 3835 for (unsigned i = 0; i != NumArgs; i++) { 3836 Expr *Arg = Args[i]; 3837 3838 if (Proto && i < Proto->getNumArgs()) { 3839 InitializedEntity Entity 3840 = InitializedEntity::InitializeParameter(Context, 3841 Proto->getArgType(i), 3842 Proto->isArgConsumed(i)); 3843 ExprResult ArgE = PerformCopyInitialization(Entity, 3844 SourceLocation(), 3845 Owned(Arg)); 3846 if (ArgE.isInvalid()) 3847 return true; 3848 3849 Arg = ArgE.takeAs<Expr>(); 3850 3851 } else { 3852 ExprResult ArgE = DefaultArgumentPromotion(Arg); 3853 3854 if (ArgE.isInvalid()) 3855 return true; 3856 3857 Arg = ArgE.takeAs<Expr>(); 3858 } 3859 3860 if (RequireCompleteType(Arg->getSourceRange().getBegin(), 3861 Arg->getType(), 3862 PDiag(diag::err_call_incomplete_argument) 3863 << Arg->getSourceRange())) 3864 return ExprError(); 3865 3866 TheCall->setArg(i, Arg); 3867 } 3868 } 3869 3870 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 3871 if (!Method->isStatic()) 3872 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 3873 << Fn->getSourceRange()); 3874 3875 // Check for sentinels 3876 if (NDecl) 3877 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs); 3878 3879 // Do special checking on direct calls to functions. 3880 if (FDecl) { 3881 if (CheckFunctionCall(FDecl, TheCall)) 3882 return ExprError(); 3883 3884 if (BuiltinID) 3885 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 3886 } else if (NDecl) { 3887 if (CheckBlockCall(NDecl, TheCall)) 3888 return ExprError(); 3889 } 3890 3891 return MaybeBindToTemporary(TheCall); 3892 } 3893 3894 ExprResult 3895 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 3896 SourceLocation RParenLoc, Expr *InitExpr) { 3897 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type"); 3898 // FIXME: put back this assert when initializers are worked out. 3899 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 3900 3901 TypeSourceInfo *TInfo; 3902 QualType literalType = GetTypeFromParser(Ty, &TInfo); 3903 if (!TInfo) 3904 TInfo = Context.getTrivialTypeSourceInfo(literalType); 3905 3906 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 3907 } 3908 3909 ExprResult 3910 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 3911 SourceLocation RParenLoc, Expr *LiteralExpr) { 3912 QualType literalType = TInfo->getType(); 3913 3914 if (literalType->isArrayType()) { 3915 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 3916 PDiag(diag::err_illegal_decl_array_incomplete_type) 3917 << SourceRange(LParenLoc, 3918 LiteralExpr->getSourceRange().getEnd()))) 3919 return ExprError(); 3920 if (literalType->isVariableArrayType()) 3921 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 3922 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 3923 } else if (!literalType->isDependentType() && 3924 RequireCompleteType(LParenLoc, literalType, 3925 PDiag(diag::err_typecheck_decl_incomplete_type) 3926 << SourceRange(LParenLoc, 3927 LiteralExpr->getSourceRange().getEnd()))) 3928 return ExprError(); 3929 3930 InitializedEntity Entity 3931 = InitializedEntity::InitializeTemporary(literalType); 3932 InitializationKind Kind 3933 = InitializationKind::CreateCStyleCast(LParenLoc, 3934 SourceRange(LParenLoc, RParenLoc)); 3935 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1); 3936 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 3937 MultiExprArg(*this, &LiteralExpr, 1), 3938 &literalType); 3939 if (Result.isInvalid()) 3940 return ExprError(); 3941 LiteralExpr = Result.get(); 3942 3943 bool isFileScope = getCurFunctionOrMethodDecl() == 0; 3944 if (isFileScope) { // 6.5.2.5p3 3945 if (CheckForConstantInitializer(LiteralExpr, literalType)) 3946 return ExprError(); 3947 } 3948 3949 // In C, compound literals are l-values for some reason. 3950 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue; 3951 3952 return MaybeBindToTemporary( 3953 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 3954 VK, LiteralExpr, isFileScope)); 3955 } 3956 3957 ExprResult 3958 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 3959 SourceLocation RBraceLoc) { 3960 unsigned NumInit = InitArgList.size(); 3961 Expr **InitList = InitArgList.release(); 3962 3963 // Immediately handle non-overload placeholders. Overloads can be 3964 // resolved contextually, but everything else here can't. 3965 for (unsigned I = 0; I != NumInit; ++I) { 3966 if (const BuiltinType *pty 3967 = InitList[I]->getType()->getAsPlaceholderType()) { 3968 if (pty->getKind() == BuiltinType::Overload) continue; 3969 3970 ExprResult result = CheckPlaceholderExpr(InitList[I]); 3971 3972 // Ignore failures; dropping the entire initializer list because 3973 // of one failure would be terrible for indexing/etc. 3974 if (result.isInvalid()) continue; 3975 3976 InitList[I] = result.take(); 3977 } 3978 } 3979 3980 // Semantic analysis for initializers is done by ActOnDeclarator() and 3981 // CheckInitializer() - it requires knowledge of the object being intialized. 3982 3983 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList, 3984 NumInit, RBraceLoc); 3985 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 3986 return Owned(E); 3987 } 3988 3989 /// Do an explicit extend of the given block pointer if we're in ARC. 3990 static void maybeExtendBlockObject(Sema &S, ExprResult &E) { 3991 assert(E.get()->getType()->isBlockPointerType()); 3992 assert(E.get()->isRValue()); 3993 3994 // Only do this in an r-value context. 3995 if (!S.getLangOptions().ObjCAutoRefCount) return; 3996 3997 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), 3998 CK_ARCExtendBlockObject, E.get(), 3999 /*base path*/ 0, VK_RValue); 4000 S.ExprNeedsCleanups = true; 4001 } 4002 4003 /// Prepare a conversion of the given expression to an ObjC object 4004 /// pointer type. 4005 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 4006 QualType type = E.get()->getType(); 4007 if (type->isObjCObjectPointerType()) { 4008 return CK_BitCast; 4009 } else if (type->isBlockPointerType()) { 4010 maybeExtendBlockObject(*this, E); 4011 return CK_BlockPointerToObjCPointerCast; 4012 } else { 4013 assert(type->isPointerType()); 4014 return CK_CPointerToObjCPointerCast; 4015 } 4016 } 4017 4018 /// Prepares for a scalar cast, performing all the necessary stages 4019 /// except the final cast and returning the kind required. 4020 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 4021 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 4022 // Also, callers should have filtered out the invalid cases with 4023 // pointers. Everything else should be possible. 4024 4025 QualType SrcTy = Src.get()->getType(); 4026 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 4027 return CK_NoOp; 4028 4029 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 4030 case Type::STK_MemberPointer: 4031 llvm_unreachable("member pointer type in C"); 4032 4033 case Type::STK_CPointer: 4034 case Type::STK_BlockPointer: 4035 case Type::STK_ObjCObjectPointer: 4036 switch (DestTy->getScalarTypeKind()) { 4037 case Type::STK_CPointer: 4038 return CK_BitCast; 4039 case Type::STK_BlockPointer: 4040 return (SrcKind == Type::STK_BlockPointer 4041 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 4042 case Type::STK_ObjCObjectPointer: 4043 if (SrcKind == Type::STK_ObjCObjectPointer) 4044 return CK_BitCast; 4045 else if (SrcKind == Type::STK_CPointer) 4046 return CK_CPointerToObjCPointerCast; 4047 else { 4048 maybeExtendBlockObject(*this, Src); 4049 return CK_BlockPointerToObjCPointerCast; 4050 } 4051 case Type::STK_Bool: 4052 return CK_PointerToBoolean; 4053 case Type::STK_Integral: 4054 return CK_PointerToIntegral; 4055 case Type::STK_Floating: 4056 case Type::STK_FloatingComplex: 4057 case Type::STK_IntegralComplex: 4058 case Type::STK_MemberPointer: 4059 llvm_unreachable("illegal cast from pointer"); 4060 } 4061 break; 4062 4063 case Type::STK_Bool: // casting from bool is like casting from an integer 4064 case Type::STK_Integral: 4065 switch (DestTy->getScalarTypeKind()) { 4066 case Type::STK_CPointer: 4067 case Type::STK_ObjCObjectPointer: 4068 case Type::STK_BlockPointer: 4069 if (Src.get()->isNullPointerConstant(Context, 4070 Expr::NPC_ValueDependentIsNull)) 4071 return CK_NullToPointer; 4072 return CK_IntegralToPointer; 4073 case Type::STK_Bool: 4074 return CK_IntegralToBoolean; 4075 case Type::STK_Integral: 4076 return CK_IntegralCast; 4077 case Type::STK_Floating: 4078 return CK_IntegralToFloating; 4079 case Type::STK_IntegralComplex: 4080 Src = ImpCastExprToType(Src.take(), 4081 DestTy->castAs<ComplexType>()->getElementType(), 4082 CK_IntegralCast); 4083 return CK_IntegralRealToComplex; 4084 case Type::STK_FloatingComplex: 4085 Src = ImpCastExprToType(Src.take(), 4086 DestTy->castAs<ComplexType>()->getElementType(), 4087 CK_IntegralToFloating); 4088 return CK_FloatingRealToComplex; 4089 case Type::STK_MemberPointer: 4090 llvm_unreachable("member pointer type in C"); 4091 } 4092 break; 4093 4094 case Type::STK_Floating: 4095 switch (DestTy->getScalarTypeKind()) { 4096 case Type::STK_Floating: 4097 return CK_FloatingCast; 4098 case Type::STK_Bool: 4099 return CK_FloatingToBoolean; 4100 case Type::STK_Integral: 4101 return CK_FloatingToIntegral; 4102 case Type::STK_FloatingComplex: 4103 Src = ImpCastExprToType(Src.take(), 4104 DestTy->castAs<ComplexType>()->getElementType(), 4105 CK_FloatingCast); 4106 return CK_FloatingRealToComplex; 4107 case Type::STK_IntegralComplex: 4108 Src = ImpCastExprToType(Src.take(), 4109 DestTy->castAs<ComplexType>()->getElementType(), 4110 CK_FloatingToIntegral); 4111 return CK_IntegralRealToComplex; 4112 case Type::STK_CPointer: 4113 case Type::STK_ObjCObjectPointer: 4114 case Type::STK_BlockPointer: 4115 llvm_unreachable("valid float->pointer cast?"); 4116 case Type::STK_MemberPointer: 4117 llvm_unreachable("member pointer type in C"); 4118 } 4119 break; 4120 4121 case Type::STK_FloatingComplex: 4122 switch (DestTy->getScalarTypeKind()) { 4123 case Type::STK_FloatingComplex: 4124 return CK_FloatingComplexCast; 4125 case Type::STK_IntegralComplex: 4126 return CK_FloatingComplexToIntegralComplex; 4127 case Type::STK_Floating: { 4128 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 4129 if (Context.hasSameType(ET, DestTy)) 4130 return CK_FloatingComplexToReal; 4131 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal); 4132 return CK_FloatingCast; 4133 } 4134 case Type::STK_Bool: 4135 return CK_FloatingComplexToBoolean; 4136 case Type::STK_Integral: 4137 Src = ImpCastExprToType(Src.take(), 4138 SrcTy->castAs<ComplexType>()->getElementType(), 4139 CK_FloatingComplexToReal); 4140 return CK_FloatingToIntegral; 4141 case Type::STK_CPointer: 4142 case Type::STK_ObjCObjectPointer: 4143 case Type::STK_BlockPointer: 4144 llvm_unreachable("valid complex float->pointer cast?"); 4145 case Type::STK_MemberPointer: 4146 llvm_unreachable("member pointer type in C"); 4147 } 4148 break; 4149 4150 case Type::STK_IntegralComplex: 4151 switch (DestTy->getScalarTypeKind()) { 4152 case Type::STK_FloatingComplex: 4153 return CK_IntegralComplexToFloatingComplex; 4154 case Type::STK_IntegralComplex: 4155 return CK_IntegralComplexCast; 4156 case Type::STK_Integral: { 4157 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 4158 if (Context.hasSameType(ET, DestTy)) 4159 return CK_IntegralComplexToReal; 4160 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal); 4161 return CK_IntegralCast; 4162 } 4163 case Type::STK_Bool: 4164 return CK_IntegralComplexToBoolean; 4165 case Type::STK_Floating: 4166 Src = ImpCastExprToType(Src.take(), 4167 SrcTy->castAs<ComplexType>()->getElementType(), 4168 CK_IntegralComplexToReal); 4169 return CK_IntegralToFloating; 4170 case Type::STK_CPointer: 4171 case Type::STK_ObjCObjectPointer: 4172 case Type::STK_BlockPointer: 4173 llvm_unreachable("valid complex int->pointer cast?"); 4174 case Type::STK_MemberPointer: 4175 llvm_unreachable("member pointer type in C"); 4176 } 4177 break; 4178 } 4179 4180 llvm_unreachable("Unhandled scalar cast"); 4181 } 4182 4183 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 4184 CastKind &Kind) { 4185 assert(VectorTy->isVectorType() && "Not a vector type!"); 4186 4187 if (Ty->isVectorType() || Ty->isIntegerType()) { 4188 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty)) 4189 return Diag(R.getBegin(), 4190 Ty->isVectorType() ? 4191 diag::err_invalid_conversion_between_vectors : 4192 diag::err_invalid_conversion_between_vector_and_integer) 4193 << VectorTy << Ty << R; 4194 } else 4195 return Diag(R.getBegin(), 4196 diag::err_invalid_conversion_between_vector_and_scalar) 4197 << VectorTy << Ty << R; 4198 4199 Kind = CK_BitCast; 4200 return false; 4201 } 4202 4203 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 4204 Expr *CastExpr, CastKind &Kind) { 4205 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 4206 4207 QualType SrcTy = CastExpr->getType(); 4208 4209 // If SrcTy is a VectorType, the total size must match to explicitly cast to 4210 // an ExtVectorType. 4211 // In OpenCL, casts between vectors of different types are not allowed. 4212 // (See OpenCL 6.2). 4213 if (SrcTy->isVectorType()) { 4214 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy) 4215 || (getLangOptions().OpenCL && 4216 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 4217 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 4218 << DestTy << SrcTy << R; 4219 return ExprError(); 4220 } 4221 Kind = CK_BitCast; 4222 return Owned(CastExpr); 4223 } 4224 4225 // All non-pointer scalars can be cast to ExtVector type. The appropriate 4226 // conversion will take place first from scalar to elt type, and then 4227 // splat from elt type to vector. 4228 if (SrcTy->isPointerType()) 4229 return Diag(R.getBegin(), 4230 diag::err_invalid_conversion_between_vector_and_scalar) 4231 << DestTy << SrcTy << R; 4232 4233 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType(); 4234 ExprResult CastExprRes = Owned(CastExpr); 4235 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy); 4236 if (CastExprRes.isInvalid()) 4237 return ExprError(); 4238 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take(); 4239 4240 Kind = CK_VectorSplat; 4241 return Owned(CastExpr); 4242 } 4243 4244 ExprResult 4245 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 4246 Declarator &D, ParsedType &Ty, 4247 SourceLocation RParenLoc, Expr *CastExpr) { 4248 assert(!D.isInvalidType() && (CastExpr != 0) && 4249 "ActOnCastExpr(): missing type or expr"); 4250 4251 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 4252 if (D.isInvalidType()) 4253 return ExprError(); 4254 4255 if (getLangOptions().CPlusPlus) { 4256 // Check that there are no default arguments (C++ only). 4257 CheckExtraCXXDefaultArguments(D); 4258 } 4259 4260 checkUnusedDeclAttributes(D); 4261 4262 QualType castType = castTInfo->getType(); 4263 Ty = CreateParsedType(castType, castTInfo); 4264 4265 bool isVectorLiteral = false; 4266 4267 // Check for an altivec or OpenCL literal, 4268 // i.e. all the elements are integer constants. 4269 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 4270 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 4271 if ((getLangOptions().AltiVec || getLangOptions().OpenCL) 4272 && castType->isVectorType() && (PE || PLE)) { 4273 if (PLE && PLE->getNumExprs() == 0) { 4274 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 4275 return ExprError(); 4276 } 4277 if (PE || PLE->getNumExprs() == 1) { 4278 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 4279 if (!E->getType()->isVectorType()) 4280 isVectorLiteral = true; 4281 } 4282 else 4283 isVectorLiteral = true; 4284 } 4285 4286 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 4287 // then handle it as such. 4288 if (isVectorLiteral) 4289 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 4290 4291 // If the Expr being casted is a ParenListExpr, handle it specially. 4292 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 4293 // sequence of BinOp comma operators. 4294 if (isa<ParenListExpr>(CastExpr)) { 4295 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 4296 if (Result.isInvalid()) return ExprError(); 4297 CastExpr = Result.take(); 4298 } 4299 4300 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 4301 } 4302 4303 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 4304 SourceLocation RParenLoc, Expr *E, 4305 TypeSourceInfo *TInfo) { 4306 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 4307 "Expected paren or paren list expression"); 4308 4309 Expr **exprs; 4310 unsigned numExprs; 4311 Expr *subExpr; 4312 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 4313 exprs = PE->getExprs(); 4314 numExprs = PE->getNumExprs(); 4315 } else { 4316 subExpr = cast<ParenExpr>(E)->getSubExpr(); 4317 exprs = &subExpr; 4318 numExprs = 1; 4319 } 4320 4321 QualType Ty = TInfo->getType(); 4322 assert(Ty->isVectorType() && "Expected vector type"); 4323 4324 SmallVector<Expr *, 8> initExprs; 4325 const VectorType *VTy = Ty->getAs<VectorType>(); 4326 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 4327 4328 // '(...)' form of vector initialization in AltiVec: the number of 4329 // initializers must be one or must match the size of the vector. 4330 // If a single value is specified in the initializer then it will be 4331 // replicated to all the components of the vector 4332 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 4333 // The number of initializers must be one or must match the size of the 4334 // vector. If a single value is specified in the initializer then it will 4335 // be replicated to all the components of the vector 4336 if (numExprs == 1) { 4337 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 4338 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 4339 if (Literal.isInvalid()) 4340 return ExprError(); 4341 Literal = ImpCastExprToType(Literal.take(), ElemTy, 4342 PrepareScalarCast(Literal, ElemTy)); 4343 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 4344 } 4345 else if (numExprs < numElems) { 4346 Diag(E->getExprLoc(), 4347 diag::err_incorrect_number_of_vector_initializers); 4348 return ExprError(); 4349 } 4350 else 4351 for (unsigned i = 0, e = numExprs; i != e; ++i) 4352 initExprs.push_back(exprs[i]); 4353 } 4354 else { 4355 // For OpenCL, when the number of initializers is a single value, 4356 // it will be replicated to all components of the vector. 4357 if (getLangOptions().OpenCL && 4358 VTy->getVectorKind() == VectorType::GenericVector && 4359 numExprs == 1) { 4360 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 4361 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 4362 if (Literal.isInvalid()) 4363 return ExprError(); 4364 Literal = ImpCastExprToType(Literal.take(), ElemTy, 4365 PrepareScalarCast(Literal, ElemTy)); 4366 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 4367 } 4368 4369 for (unsigned i = 0, e = numExprs; i != e; ++i) 4370 initExprs.push_back(exprs[i]); 4371 } 4372 // FIXME: This means that pretty-printing the final AST will produce curly 4373 // braces instead of the original commas. 4374 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc, 4375 &initExprs[0], 4376 initExprs.size(), RParenLoc); 4377 initE->setType(Ty); 4378 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 4379 } 4380 4381 /// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence 4382 /// of comma binary operators. 4383 ExprResult 4384 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 4385 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 4386 if (!E) 4387 return Owned(OrigExpr); 4388 4389 ExprResult Result(E->getExpr(0)); 4390 4391 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 4392 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 4393 E->getExpr(i)); 4394 4395 if (Result.isInvalid()) return ExprError(); 4396 4397 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 4398 } 4399 4400 ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L, 4401 SourceLocation R, 4402 MultiExprArg Val) { 4403 unsigned nexprs = Val.size(); 4404 Expr **exprs = reinterpret_cast<Expr**>(Val.release()); 4405 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list"); 4406 Expr *expr; 4407 if (nexprs == 1) 4408 expr = new (Context) ParenExpr(L, R, exprs[0]); 4409 else 4410 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R, 4411 exprs[nexprs-1]->getType()); 4412 return Owned(expr); 4413 } 4414 4415 /// \brief Emit a specialized diagnostic when one expression is a null pointer 4416 /// constant and the other is not a pointer. Returns true if a diagnostic is 4417 /// emitted. 4418 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 4419 SourceLocation QuestionLoc) { 4420 Expr *NullExpr = LHSExpr; 4421 Expr *NonPointerExpr = RHSExpr; 4422 Expr::NullPointerConstantKind NullKind = 4423 NullExpr->isNullPointerConstant(Context, 4424 Expr::NPC_ValueDependentIsNotNull); 4425 4426 if (NullKind == Expr::NPCK_NotNull) { 4427 NullExpr = RHSExpr; 4428 NonPointerExpr = LHSExpr; 4429 NullKind = 4430 NullExpr->isNullPointerConstant(Context, 4431 Expr::NPC_ValueDependentIsNotNull); 4432 } 4433 4434 if (NullKind == Expr::NPCK_NotNull) 4435 return false; 4436 4437 if (NullKind == Expr::NPCK_ZeroInteger) { 4438 // In this case, check to make sure that we got here from a "NULL" 4439 // string in the source code. 4440 NullExpr = NullExpr->IgnoreParenImpCasts(); 4441 SourceLocation loc = NullExpr->getExprLoc(); 4442 if (!findMacroSpelling(loc, "NULL")) 4443 return false; 4444 } 4445 4446 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr); 4447 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 4448 << NonPointerExpr->getType() << DiagType 4449 << NonPointerExpr->getSourceRange(); 4450 return true; 4451 } 4452 4453 /// \brief Return false if the condition expression is valid, true otherwise. 4454 static bool checkCondition(Sema &S, Expr *Cond) { 4455 QualType CondTy = Cond->getType(); 4456 4457 // C99 6.5.15p2 4458 if (CondTy->isScalarType()) return false; 4459 4460 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar. 4461 if (S.getLangOptions().OpenCL && CondTy->isVectorType()) 4462 return false; 4463 4464 // Emit the proper error message. 4465 S.Diag(Cond->getLocStart(), S.getLangOptions().OpenCL ? 4466 diag::err_typecheck_cond_expect_scalar : 4467 diag::err_typecheck_cond_expect_scalar_or_vector) 4468 << CondTy; 4469 return true; 4470 } 4471 4472 /// \brief Return false if the two expressions can be converted to a vector, 4473 /// true otherwise 4474 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS, 4475 ExprResult &RHS, 4476 QualType CondTy) { 4477 // Both operands should be of scalar type. 4478 if (!LHS.get()->getType()->isScalarType()) { 4479 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 4480 << CondTy; 4481 return true; 4482 } 4483 if (!RHS.get()->getType()->isScalarType()) { 4484 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 4485 << CondTy; 4486 return true; 4487 } 4488 4489 // Implicity convert these scalars to the type of the condition. 4490 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast); 4491 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast); 4492 return false; 4493 } 4494 4495 /// \brief Handle when one or both operands are void type. 4496 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 4497 ExprResult &RHS) { 4498 Expr *LHSExpr = LHS.get(); 4499 Expr *RHSExpr = RHS.get(); 4500 4501 if (!LHSExpr->getType()->isVoidType()) 4502 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 4503 << RHSExpr->getSourceRange(); 4504 if (!RHSExpr->getType()->isVoidType()) 4505 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 4506 << LHSExpr->getSourceRange(); 4507 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid); 4508 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid); 4509 return S.Context.VoidTy; 4510 } 4511 4512 /// \brief Return false if the NullExpr can be promoted to PointerTy, 4513 /// true otherwise. 4514 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 4515 QualType PointerTy) { 4516 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 4517 !NullExpr.get()->isNullPointerConstant(S.Context, 4518 Expr::NPC_ValueDependentIsNull)) 4519 return true; 4520 4521 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer); 4522 return false; 4523 } 4524 4525 /// \brief Checks compatibility between two pointers and return the resulting 4526 /// type. 4527 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 4528 ExprResult &RHS, 4529 SourceLocation Loc) { 4530 QualType LHSTy = LHS.get()->getType(); 4531 QualType RHSTy = RHS.get()->getType(); 4532 4533 if (S.Context.hasSameType(LHSTy, RHSTy)) { 4534 // Two identical pointers types are always compatible. 4535 return LHSTy; 4536 } 4537 4538 QualType lhptee, rhptee; 4539 4540 // Get the pointee types. 4541 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 4542 lhptee = LHSBTy->getPointeeType(); 4543 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 4544 } else { 4545 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 4546 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 4547 } 4548 4549 if (!S.Context.typesAreCompatible(lhptee.getUnqualifiedType(), 4550 rhptee.getUnqualifiedType())) { 4551 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers) 4552 << LHSTy << RHSTy << LHS.get()->getSourceRange() 4553 << RHS.get()->getSourceRange(); 4554 // In this situation, we assume void* type. No especially good 4555 // reason, but this is what gcc does, and we do have to pick 4556 // to get a consistent AST. 4557 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy); 4558 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 4559 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 4560 return incompatTy; 4561 } 4562 4563 // The pointer types are compatible. 4564 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to 4565 // differently qualified versions of compatible types, the result type is 4566 // a pointer to an appropriately qualified version of the *composite* 4567 // type. 4568 // FIXME: Need to calculate the composite type. 4569 // FIXME: Need to add qualifiers 4570 4571 LHS = S.ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast); 4572 RHS = S.ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast); 4573 return LHSTy; 4574 } 4575 4576 /// \brief Return the resulting type when the operands are both block pointers. 4577 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 4578 ExprResult &LHS, 4579 ExprResult &RHS, 4580 SourceLocation Loc) { 4581 QualType LHSTy = LHS.get()->getType(); 4582 QualType RHSTy = RHS.get()->getType(); 4583 4584 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 4585 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 4586 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 4587 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 4588 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 4589 return destType; 4590 } 4591 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 4592 << LHSTy << RHSTy << LHS.get()->getSourceRange() 4593 << RHS.get()->getSourceRange(); 4594 return QualType(); 4595 } 4596 4597 // We have 2 block pointer types. 4598 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 4599 } 4600 4601 /// \brief Return the resulting type when the operands are both pointers. 4602 static QualType 4603 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 4604 ExprResult &RHS, 4605 SourceLocation Loc) { 4606 // get the pointer types 4607 QualType LHSTy = LHS.get()->getType(); 4608 QualType RHSTy = RHS.get()->getType(); 4609 4610 // get the "pointed to" types 4611 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 4612 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 4613 4614 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 4615 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 4616 // Figure out necessary qualifiers (C99 6.5.15p6) 4617 QualType destPointee 4618 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 4619 QualType destType = S.Context.getPointerType(destPointee); 4620 // Add qualifiers if necessary. 4621 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp); 4622 // Promote to void*. 4623 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 4624 return destType; 4625 } 4626 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 4627 QualType destPointee 4628 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 4629 QualType destType = S.Context.getPointerType(destPointee); 4630 // Add qualifiers if necessary. 4631 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp); 4632 // Promote to void*. 4633 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 4634 return destType; 4635 } 4636 4637 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 4638 } 4639 4640 /// \brief Return false if the first expression is not an integer and the second 4641 /// expression is not a pointer, true otherwise. 4642 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 4643 Expr* PointerExpr, SourceLocation Loc, 4644 bool IsIntFirstExpr) { 4645 if (!PointerExpr->getType()->isPointerType() || 4646 !Int.get()->getType()->isIntegerType()) 4647 return false; 4648 4649 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 4650 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 4651 4652 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch) 4653 << Expr1->getType() << Expr2->getType() 4654 << Expr1->getSourceRange() << Expr2->getSourceRange(); 4655 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(), 4656 CK_IntegralToPointer); 4657 return true; 4658 } 4659 4660 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 4661 /// In that case, LHS = cond. 4662 /// C99 6.5.15 4663 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 4664 ExprResult &RHS, ExprValueKind &VK, 4665 ExprObjectKind &OK, 4666 SourceLocation QuestionLoc) { 4667 4668 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 4669 if (!LHSResult.isUsable()) return QualType(); 4670 LHS = move(LHSResult); 4671 4672 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 4673 if (!RHSResult.isUsable()) return QualType(); 4674 RHS = move(RHSResult); 4675 4676 // C++ is sufficiently different to merit its own checker. 4677 if (getLangOptions().CPlusPlus) 4678 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 4679 4680 VK = VK_RValue; 4681 OK = OK_Ordinary; 4682 4683 Cond = UsualUnaryConversions(Cond.take()); 4684 if (Cond.isInvalid()) 4685 return QualType(); 4686 LHS = UsualUnaryConversions(LHS.take()); 4687 if (LHS.isInvalid()) 4688 return QualType(); 4689 RHS = UsualUnaryConversions(RHS.take()); 4690 if (RHS.isInvalid()) 4691 return QualType(); 4692 4693 QualType CondTy = Cond.get()->getType(); 4694 QualType LHSTy = LHS.get()->getType(); 4695 QualType RHSTy = RHS.get()->getType(); 4696 4697 // first, check the condition. 4698 if (checkCondition(*this, Cond.get())) 4699 return QualType(); 4700 4701 // Now check the two expressions. 4702 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 4703 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false); 4704 4705 // OpenCL: If the condition is a vector, and both operands are scalar, 4706 // attempt to implicity convert them to the vector type to act like the 4707 // built in select. 4708 if (getLangOptions().OpenCL && CondTy->isVectorType()) 4709 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy)) 4710 return QualType(); 4711 4712 // If both operands have arithmetic type, do the usual arithmetic conversions 4713 // to find a common type: C99 6.5.15p3,5. 4714 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 4715 UsualArithmeticConversions(LHS, RHS); 4716 if (LHS.isInvalid() || RHS.isInvalid()) 4717 return QualType(); 4718 return LHS.get()->getType(); 4719 } 4720 4721 // If both operands are the same structure or union type, the result is that 4722 // type. 4723 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 4724 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 4725 if (LHSRT->getDecl() == RHSRT->getDecl()) 4726 // "If both the operands have structure or union type, the result has 4727 // that type." This implies that CV qualifiers are dropped. 4728 return LHSTy.getUnqualifiedType(); 4729 // FIXME: Type of conditional expression must be complete in C mode. 4730 } 4731 4732 // C99 6.5.15p5: "If both operands have void type, the result has void type." 4733 // The following || allows only one side to be void (a GCC-ism). 4734 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 4735 return checkConditionalVoidType(*this, LHS, RHS); 4736 } 4737 4738 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 4739 // the type of the other operand." 4740 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 4741 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 4742 4743 // All objective-c pointer type analysis is done here. 4744 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 4745 QuestionLoc); 4746 if (LHS.isInvalid() || RHS.isInvalid()) 4747 return QualType(); 4748 if (!compositeType.isNull()) 4749 return compositeType; 4750 4751 4752 // Handle block pointer types. 4753 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 4754 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 4755 QuestionLoc); 4756 4757 // Check constraints for C object pointers types (C99 6.5.15p3,6). 4758 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 4759 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 4760 QuestionLoc); 4761 4762 // GCC compatibility: soften pointer/integer mismatch. Note that 4763 // null pointers have been filtered out by this point. 4764 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 4765 /*isIntFirstExpr=*/true)) 4766 return RHSTy; 4767 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 4768 /*isIntFirstExpr=*/false)) 4769 return LHSTy; 4770 4771 // Emit a better diagnostic if one of the expressions is a null pointer 4772 // constant and the other is not a pointer type. In this case, the user most 4773 // likely forgot to take the address of the other expression. 4774 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 4775 return QualType(); 4776 4777 // Otherwise, the operands are not compatible. 4778 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 4779 << LHSTy << RHSTy << LHS.get()->getSourceRange() 4780 << RHS.get()->getSourceRange(); 4781 return QualType(); 4782 } 4783 4784 /// FindCompositeObjCPointerType - Helper method to find composite type of 4785 /// two objective-c pointer types of the two input expressions. 4786 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 4787 SourceLocation QuestionLoc) { 4788 QualType LHSTy = LHS.get()->getType(); 4789 QualType RHSTy = RHS.get()->getType(); 4790 4791 // Handle things like Class and struct objc_class*. Here we case the result 4792 // to the pseudo-builtin, because that will be implicitly cast back to the 4793 // redefinition type if an attempt is made to access its fields. 4794 if (LHSTy->isObjCClassType() && 4795 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 4796 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 4797 return LHSTy; 4798 } 4799 if (RHSTy->isObjCClassType() && 4800 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 4801 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 4802 return RHSTy; 4803 } 4804 // And the same for struct objc_object* / id 4805 if (LHSTy->isObjCIdType() && 4806 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 4807 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 4808 return LHSTy; 4809 } 4810 if (RHSTy->isObjCIdType() && 4811 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 4812 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 4813 return RHSTy; 4814 } 4815 // And the same for struct objc_selector* / SEL 4816 if (Context.isObjCSelType(LHSTy) && 4817 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 4818 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast); 4819 return LHSTy; 4820 } 4821 if (Context.isObjCSelType(RHSTy) && 4822 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 4823 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast); 4824 return RHSTy; 4825 } 4826 // Check constraints for Objective-C object pointers types. 4827 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 4828 4829 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 4830 // Two identical object pointer types are always compatible. 4831 return LHSTy; 4832 } 4833 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 4834 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 4835 QualType compositeType = LHSTy; 4836 4837 // If both operands are interfaces and either operand can be 4838 // assigned to the other, use that type as the composite 4839 // type. This allows 4840 // xxx ? (A*) a : (B*) b 4841 // where B is a subclass of A. 4842 // 4843 // Additionally, as for assignment, if either type is 'id' 4844 // allow silent coercion. Finally, if the types are 4845 // incompatible then make sure to use 'id' as the composite 4846 // type so the result is acceptable for sending messages to. 4847 4848 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 4849 // It could return the composite type. 4850 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 4851 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 4852 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 4853 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 4854 } else if ((LHSTy->isObjCQualifiedIdType() || 4855 RHSTy->isObjCQualifiedIdType()) && 4856 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 4857 // Need to handle "id<xx>" explicitly. 4858 // GCC allows qualified id and any Objective-C type to devolve to 4859 // id. Currently localizing to here until clear this should be 4860 // part of ObjCQualifiedIdTypesAreCompatible. 4861 compositeType = Context.getObjCIdType(); 4862 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 4863 compositeType = Context.getObjCIdType(); 4864 } else if (!(compositeType = 4865 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) 4866 ; 4867 else { 4868 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 4869 << LHSTy << RHSTy 4870 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 4871 QualType incompatTy = Context.getObjCIdType(); 4872 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 4873 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 4874 return incompatTy; 4875 } 4876 // The object pointer types are compatible. 4877 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast); 4878 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast); 4879 return compositeType; 4880 } 4881 // Check Objective-C object pointer types and 'void *' 4882 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 4883 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 4884 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 4885 QualType destPointee 4886 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 4887 QualType destType = Context.getPointerType(destPointee); 4888 // Add qualifiers if necessary. 4889 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp); 4890 // Promote to void*. 4891 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast); 4892 return destType; 4893 } 4894 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 4895 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 4896 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 4897 QualType destPointee 4898 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 4899 QualType destType = Context.getPointerType(destPointee); 4900 // Add qualifiers if necessary. 4901 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp); 4902 // Promote to void*. 4903 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast); 4904 return destType; 4905 } 4906 return QualType(); 4907 } 4908 4909 /// SuggestParentheses - Emit a note with a fixit hint that wraps 4910 /// ParenRange in parentheses. 4911 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 4912 const PartialDiagnostic &Note, 4913 SourceRange ParenRange) { 4914 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd()); 4915 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 4916 EndLoc.isValid()) { 4917 Self.Diag(Loc, Note) 4918 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 4919 << FixItHint::CreateInsertion(EndLoc, ")"); 4920 } else { 4921 // We can't display the parentheses, so just show the bare note. 4922 Self.Diag(Loc, Note) << ParenRange; 4923 } 4924 } 4925 4926 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 4927 return Opc >= BO_Mul && Opc <= BO_Shr; 4928 } 4929 4930 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 4931 /// expression, either using a built-in or overloaded operator, 4932 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 4933 /// expression. 4934 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 4935 Expr **RHSExprs) { 4936 // Don't strip parenthesis: we should not warn if E is in parenthesis. 4937 E = E->IgnoreImpCasts(); 4938 E = E->IgnoreConversionOperator(); 4939 E = E->IgnoreImpCasts(); 4940 4941 // Built-in binary operator. 4942 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 4943 if (IsArithmeticOp(OP->getOpcode())) { 4944 *Opcode = OP->getOpcode(); 4945 *RHSExprs = OP->getRHS(); 4946 return true; 4947 } 4948 } 4949 4950 // Overloaded operator. 4951 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 4952 if (Call->getNumArgs() != 2) 4953 return false; 4954 4955 // Make sure this is really a binary operator that is safe to pass into 4956 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 4957 OverloadedOperatorKind OO = Call->getOperator(); 4958 if (OO < OO_Plus || OO > OO_Arrow) 4959 return false; 4960 4961 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 4962 if (IsArithmeticOp(OpKind)) { 4963 *Opcode = OpKind; 4964 *RHSExprs = Call->getArg(1); 4965 return true; 4966 } 4967 } 4968 4969 return false; 4970 } 4971 4972 static bool IsLogicOp(BinaryOperatorKind Opc) { 4973 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr); 4974 } 4975 4976 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 4977 /// or is a logical expression such as (x==y) which has int type, but is 4978 /// commonly interpreted as boolean. 4979 static bool ExprLooksBoolean(Expr *E) { 4980 E = E->IgnoreParenImpCasts(); 4981 4982 if (E->getType()->isBooleanType()) 4983 return true; 4984 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 4985 return IsLogicOp(OP->getOpcode()); 4986 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 4987 return OP->getOpcode() == UO_LNot; 4988 4989 return false; 4990 } 4991 4992 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 4993 /// and binary operator are mixed in a way that suggests the programmer assumed 4994 /// the conditional operator has higher precedence, for example: 4995 /// "int x = a + someBinaryCondition ? 1 : 2". 4996 static void DiagnoseConditionalPrecedence(Sema &Self, 4997 SourceLocation OpLoc, 4998 Expr *Condition, 4999 Expr *LHSExpr, 5000 Expr *RHSExpr) { 5001 BinaryOperatorKind CondOpcode; 5002 Expr *CondRHS; 5003 5004 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 5005 return; 5006 if (!ExprLooksBoolean(CondRHS)) 5007 return; 5008 5009 // The condition is an arithmetic binary expression, with a right- 5010 // hand side that looks boolean, so warn. 5011 5012 Self.Diag(OpLoc, diag::warn_precedence_conditional) 5013 << Condition->getSourceRange() 5014 << BinaryOperator::getOpcodeStr(CondOpcode); 5015 5016 SuggestParentheses(Self, OpLoc, 5017 Self.PDiag(diag::note_precedence_conditional_silence) 5018 << BinaryOperator::getOpcodeStr(CondOpcode), 5019 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 5020 5021 SuggestParentheses(Self, OpLoc, 5022 Self.PDiag(diag::note_precedence_conditional_first), 5023 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 5024 } 5025 5026 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 5027 /// in the case of a the GNU conditional expr extension. 5028 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 5029 SourceLocation ColonLoc, 5030 Expr *CondExpr, Expr *LHSExpr, 5031 Expr *RHSExpr) { 5032 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 5033 // was the condition. 5034 OpaqueValueExpr *opaqueValue = 0; 5035 Expr *commonExpr = 0; 5036 if (LHSExpr == 0) { 5037 commonExpr = CondExpr; 5038 5039 // We usually want to apply unary conversions *before* saving, except 5040 // in the special case of a C++ l-value conditional. 5041 if (!(getLangOptions().CPlusPlus 5042 && !commonExpr->isTypeDependent() 5043 && commonExpr->getValueKind() == RHSExpr->getValueKind() 5044 && commonExpr->isGLValue() 5045 && commonExpr->isOrdinaryOrBitFieldObject() 5046 && RHSExpr->isOrdinaryOrBitFieldObject() 5047 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 5048 ExprResult commonRes = UsualUnaryConversions(commonExpr); 5049 if (commonRes.isInvalid()) 5050 return ExprError(); 5051 commonExpr = commonRes.take(); 5052 } 5053 5054 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 5055 commonExpr->getType(), 5056 commonExpr->getValueKind(), 5057 commonExpr->getObjectKind()); 5058 LHSExpr = CondExpr = opaqueValue; 5059 } 5060 5061 ExprValueKind VK = VK_RValue; 5062 ExprObjectKind OK = OK_Ordinary; 5063 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 5064 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 5065 VK, OK, QuestionLoc); 5066 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 5067 RHS.isInvalid()) 5068 return ExprError(); 5069 5070 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 5071 RHS.get()); 5072 5073 if (!commonExpr) 5074 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc, 5075 LHS.take(), ColonLoc, 5076 RHS.take(), result, VK, OK)); 5077 5078 return Owned(new (Context) 5079 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(), 5080 RHS.take(), QuestionLoc, ColonLoc, result, VK, 5081 OK)); 5082 } 5083 5084 // checkPointerTypesForAssignment - This is a very tricky routine (despite 5085 // being closely modeled after the C99 spec:-). The odd characteristic of this 5086 // routine is it effectively iqnores the qualifiers on the top level pointee. 5087 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 5088 // FIXME: add a couple examples in this comment. 5089 static Sema::AssignConvertType 5090 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 5091 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 5092 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 5093 5094 // get the "pointed to" type (ignoring qualifiers at the top level) 5095 const Type *lhptee, *rhptee; 5096 Qualifiers lhq, rhq; 5097 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split(); 5098 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split(); 5099 5100 Sema::AssignConvertType ConvTy = Sema::Compatible; 5101 5102 // C99 6.5.16.1p1: This following citation is common to constraints 5103 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 5104 // qualifiers of the type *pointed to* by the right; 5105 Qualifiers lq; 5106 5107 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 5108 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 5109 lhq.compatiblyIncludesObjCLifetime(rhq)) { 5110 // Ignore lifetime for further calculation. 5111 lhq.removeObjCLifetime(); 5112 rhq.removeObjCLifetime(); 5113 } 5114 5115 if (!lhq.compatiblyIncludes(rhq)) { 5116 // Treat address-space mismatches as fatal. TODO: address subspaces 5117 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 5118 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 5119 5120 // It's okay to add or remove GC or lifetime qualifiers when converting to 5121 // and from void*. 5122 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime() 5123 .compatiblyIncludes( 5124 rhq.withoutObjCGCAttr().withoutObjCGLifetime()) 5125 && (lhptee->isVoidType() || rhptee->isVoidType())) 5126 ; // keep old 5127 5128 // Treat lifetime mismatches as fatal. 5129 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 5130 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 5131 5132 // For GCC compatibility, other qualifier mismatches are treated 5133 // as still compatible in C. 5134 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 5135 } 5136 5137 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 5138 // incomplete type and the other is a pointer to a qualified or unqualified 5139 // version of void... 5140 if (lhptee->isVoidType()) { 5141 if (rhptee->isIncompleteOrObjectType()) 5142 return ConvTy; 5143 5144 // As an extension, we allow cast to/from void* to function pointer. 5145 assert(rhptee->isFunctionType()); 5146 return Sema::FunctionVoidPointer; 5147 } 5148 5149 if (rhptee->isVoidType()) { 5150 if (lhptee->isIncompleteOrObjectType()) 5151 return ConvTy; 5152 5153 // As an extension, we allow cast to/from void* to function pointer. 5154 assert(lhptee->isFunctionType()); 5155 return Sema::FunctionVoidPointer; 5156 } 5157 5158 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 5159 // unqualified versions of compatible types, ... 5160 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 5161 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 5162 // Check if the pointee types are compatible ignoring the sign. 5163 // We explicitly check for char so that we catch "char" vs 5164 // "unsigned char" on systems where "char" is unsigned. 5165 if (lhptee->isCharType()) 5166 ltrans = S.Context.UnsignedCharTy; 5167 else if (lhptee->hasSignedIntegerRepresentation()) 5168 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 5169 5170 if (rhptee->isCharType()) 5171 rtrans = S.Context.UnsignedCharTy; 5172 else if (rhptee->hasSignedIntegerRepresentation()) 5173 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 5174 5175 if (ltrans == rtrans) { 5176 // Types are compatible ignoring the sign. Qualifier incompatibility 5177 // takes priority over sign incompatibility because the sign 5178 // warning can be disabled. 5179 if (ConvTy != Sema::Compatible) 5180 return ConvTy; 5181 5182 return Sema::IncompatiblePointerSign; 5183 } 5184 5185 // If we are a multi-level pointer, it's possible that our issue is simply 5186 // one of qualification - e.g. char ** -> const char ** is not allowed. If 5187 // the eventual target type is the same and the pointers have the same 5188 // level of indirection, this must be the issue. 5189 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 5190 do { 5191 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 5192 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 5193 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 5194 5195 if (lhptee == rhptee) 5196 return Sema::IncompatibleNestedPointerQualifiers; 5197 } 5198 5199 // General pointer incompatibility takes priority over qualifiers. 5200 return Sema::IncompatiblePointer; 5201 } 5202 if (!S.getLangOptions().CPlusPlus && 5203 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 5204 return Sema::IncompatiblePointer; 5205 return ConvTy; 5206 } 5207 5208 /// checkBlockPointerTypesForAssignment - This routine determines whether two 5209 /// block pointer types are compatible or whether a block and normal pointer 5210 /// are compatible. It is more restrict than comparing two function pointer 5211 // types. 5212 static Sema::AssignConvertType 5213 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 5214 QualType RHSType) { 5215 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 5216 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 5217 5218 QualType lhptee, rhptee; 5219 5220 // get the "pointed to" type (ignoring qualifiers at the top level) 5221 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 5222 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 5223 5224 // In C++, the types have to match exactly. 5225 if (S.getLangOptions().CPlusPlus) 5226 return Sema::IncompatibleBlockPointer; 5227 5228 Sema::AssignConvertType ConvTy = Sema::Compatible; 5229 5230 // For blocks we enforce that qualifiers are identical. 5231 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 5232 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 5233 5234 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 5235 return Sema::IncompatibleBlockPointer; 5236 5237 return ConvTy; 5238 } 5239 5240 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 5241 /// for assignment compatibility. 5242 static Sema::AssignConvertType 5243 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 5244 QualType RHSType) { 5245 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 5246 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 5247 5248 if (LHSType->isObjCBuiltinType()) { 5249 // Class is not compatible with ObjC object pointers. 5250 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 5251 !RHSType->isObjCQualifiedClassType()) 5252 return Sema::IncompatiblePointer; 5253 return Sema::Compatible; 5254 } 5255 if (RHSType->isObjCBuiltinType()) { 5256 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 5257 !LHSType->isObjCQualifiedClassType()) 5258 return Sema::IncompatiblePointer; 5259 return Sema::Compatible; 5260 } 5261 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 5262 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 5263 5264 if (!lhptee.isAtLeastAsQualifiedAs(rhptee)) 5265 return Sema::CompatiblePointerDiscardsQualifiers; 5266 5267 if (S.Context.typesAreCompatible(LHSType, RHSType)) 5268 return Sema::Compatible; 5269 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 5270 return Sema::IncompatibleObjCQualifiedId; 5271 return Sema::IncompatiblePointer; 5272 } 5273 5274 Sema::AssignConvertType 5275 Sema::CheckAssignmentConstraints(SourceLocation Loc, 5276 QualType LHSType, QualType RHSType) { 5277 // Fake up an opaque expression. We don't actually care about what 5278 // cast operations are required, so if CheckAssignmentConstraints 5279 // adds casts to this they'll be wasted, but fortunately that doesn't 5280 // usually happen on valid code. 5281 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 5282 ExprResult RHSPtr = &RHSExpr; 5283 CastKind K = CK_Invalid; 5284 5285 return CheckAssignmentConstraints(LHSType, RHSPtr, K); 5286 } 5287 5288 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 5289 /// has code to accommodate several GCC extensions when type checking 5290 /// pointers. Here are some objectionable examples that GCC considers warnings: 5291 /// 5292 /// int a, *pint; 5293 /// short *pshort; 5294 /// struct foo *pfoo; 5295 /// 5296 /// pint = pshort; // warning: assignment from incompatible pointer type 5297 /// a = pint; // warning: assignment makes integer from pointer without a cast 5298 /// pint = a; // warning: assignment makes pointer from integer without a cast 5299 /// pint = pfoo; // warning: assignment from incompatible pointer type 5300 /// 5301 /// As a result, the code for dealing with pointers is more complex than the 5302 /// C99 spec dictates. 5303 /// 5304 /// Sets 'Kind' for any result kind except Incompatible. 5305 Sema::AssignConvertType 5306 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 5307 CastKind &Kind) { 5308 QualType RHSType = RHS.get()->getType(); 5309 QualType OrigLHSType = LHSType; 5310 5311 // Get canonical types. We're not formatting these types, just comparing 5312 // them. 5313 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 5314 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 5315 5316 // We can't do assignment from/to atomics yet. 5317 if (LHSType->isAtomicType()) 5318 return Incompatible; 5319 5320 // Common case: no conversion required. 5321 if (LHSType == RHSType) { 5322 Kind = CK_NoOp; 5323 return Compatible; 5324 } 5325 5326 // If the left-hand side is a reference type, then we are in a 5327 // (rare!) case where we've allowed the use of references in C, 5328 // e.g., as a parameter type in a built-in function. In this case, 5329 // just make sure that the type referenced is compatible with the 5330 // right-hand side type. The caller is responsible for adjusting 5331 // LHSType so that the resulting expression does not have reference 5332 // type. 5333 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 5334 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 5335 Kind = CK_LValueBitCast; 5336 return Compatible; 5337 } 5338 return Incompatible; 5339 } 5340 5341 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 5342 // to the same ExtVector type. 5343 if (LHSType->isExtVectorType()) { 5344 if (RHSType->isExtVectorType()) 5345 return Incompatible; 5346 if (RHSType->isArithmeticType()) { 5347 // CK_VectorSplat does T -> vector T, so first cast to the 5348 // element type. 5349 QualType elType = cast<ExtVectorType>(LHSType)->getElementType(); 5350 if (elType != RHSType) { 5351 Kind = PrepareScalarCast(RHS, elType); 5352 RHS = ImpCastExprToType(RHS.take(), elType, Kind); 5353 } 5354 Kind = CK_VectorSplat; 5355 return Compatible; 5356 } 5357 } 5358 5359 // Conversions to or from vector type. 5360 if (LHSType->isVectorType() || RHSType->isVectorType()) { 5361 if (LHSType->isVectorType() && RHSType->isVectorType()) { 5362 // Allow assignments of an AltiVec vector type to an equivalent GCC 5363 // vector type and vice versa 5364 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 5365 Kind = CK_BitCast; 5366 return Compatible; 5367 } 5368 5369 // If we are allowing lax vector conversions, and LHS and RHS are both 5370 // vectors, the total size only needs to be the same. This is a bitcast; 5371 // no bits are changed but the result type is different. 5372 if (getLangOptions().LaxVectorConversions && 5373 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) { 5374 Kind = CK_BitCast; 5375 return IncompatibleVectors; 5376 } 5377 } 5378 return Incompatible; 5379 } 5380 5381 // Arithmetic conversions. 5382 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 5383 !(getLangOptions().CPlusPlus && LHSType->isEnumeralType())) { 5384 Kind = PrepareScalarCast(RHS, LHSType); 5385 return Compatible; 5386 } 5387 5388 // Conversions to normal pointers. 5389 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 5390 // U* -> T* 5391 if (isa<PointerType>(RHSType)) { 5392 Kind = CK_BitCast; 5393 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 5394 } 5395 5396 // int -> T* 5397 if (RHSType->isIntegerType()) { 5398 Kind = CK_IntegralToPointer; // FIXME: null? 5399 return IntToPointer; 5400 } 5401 5402 // C pointers are not compatible with ObjC object pointers, 5403 // with two exceptions: 5404 if (isa<ObjCObjectPointerType>(RHSType)) { 5405 // - conversions to void* 5406 if (LHSPointer->getPointeeType()->isVoidType()) { 5407 Kind = CK_BitCast; 5408 return Compatible; 5409 } 5410 5411 // - conversions from 'Class' to the redefinition type 5412 if (RHSType->isObjCClassType() && 5413 Context.hasSameType(LHSType, 5414 Context.getObjCClassRedefinitionType())) { 5415 Kind = CK_BitCast; 5416 return Compatible; 5417 } 5418 5419 Kind = CK_BitCast; 5420 return IncompatiblePointer; 5421 } 5422 5423 // U^ -> void* 5424 if (RHSType->getAs<BlockPointerType>()) { 5425 if (LHSPointer->getPointeeType()->isVoidType()) { 5426 Kind = CK_BitCast; 5427 return Compatible; 5428 } 5429 } 5430 5431 return Incompatible; 5432 } 5433 5434 // Conversions to block pointers. 5435 if (isa<BlockPointerType>(LHSType)) { 5436 // U^ -> T^ 5437 if (RHSType->isBlockPointerType()) { 5438 Kind = CK_BitCast; 5439 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 5440 } 5441 5442 // int or null -> T^ 5443 if (RHSType->isIntegerType()) { 5444 Kind = CK_IntegralToPointer; // FIXME: null 5445 return IntToBlockPointer; 5446 } 5447 5448 // id -> T^ 5449 if (getLangOptions().ObjC1 && RHSType->isObjCIdType()) { 5450 Kind = CK_AnyPointerToBlockPointerCast; 5451 return Compatible; 5452 } 5453 5454 // void* -> T^ 5455 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 5456 if (RHSPT->getPointeeType()->isVoidType()) { 5457 Kind = CK_AnyPointerToBlockPointerCast; 5458 return Compatible; 5459 } 5460 5461 return Incompatible; 5462 } 5463 5464 // Conversions to Objective-C pointers. 5465 if (isa<ObjCObjectPointerType>(LHSType)) { 5466 // A* -> B* 5467 if (RHSType->isObjCObjectPointerType()) { 5468 Kind = CK_BitCast; 5469 Sema::AssignConvertType result = 5470 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 5471 if (getLangOptions().ObjCAutoRefCount && 5472 result == Compatible && 5473 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 5474 result = IncompatibleObjCWeakRef; 5475 return result; 5476 } 5477 5478 // int or null -> A* 5479 if (RHSType->isIntegerType()) { 5480 Kind = CK_IntegralToPointer; // FIXME: null 5481 return IntToPointer; 5482 } 5483 5484 // In general, C pointers are not compatible with ObjC object pointers, 5485 // with two exceptions: 5486 if (isa<PointerType>(RHSType)) { 5487 Kind = CK_CPointerToObjCPointerCast; 5488 5489 // - conversions from 'void*' 5490 if (RHSType->isVoidPointerType()) { 5491 return Compatible; 5492 } 5493 5494 // - conversions to 'Class' from its redefinition type 5495 if (LHSType->isObjCClassType() && 5496 Context.hasSameType(RHSType, 5497 Context.getObjCClassRedefinitionType())) { 5498 return Compatible; 5499 } 5500 5501 return IncompatiblePointer; 5502 } 5503 5504 // T^ -> A* 5505 if (RHSType->isBlockPointerType()) { 5506 maybeExtendBlockObject(*this, RHS); 5507 Kind = CK_BlockPointerToObjCPointerCast; 5508 return Compatible; 5509 } 5510 5511 return Incompatible; 5512 } 5513 5514 // Conversions from pointers that are not covered by the above. 5515 if (isa<PointerType>(RHSType)) { 5516 // T* -> _Bool 5517 if (LHSType == Context.BoolTy) { 5518 Kind = CK_PointerToBoolean; 5519 return Compatible; 5520 } 5521 5522 // T* -> int 5523 if (LHSType->isIntegerType()) { 5524 Kind = CK_PointerToIntegral; 5525 return PointerToInt; 5526 } 5527 5528 return Incompatible; 5529 } 5530 5531 // Conversions from Objective-C pointers that are not covered by the above. 5532 if (isa<ObjCObjectPointerType>(RHSType)) { 5533 // T* -> _Bool 5534 if (LHSType == Context.BoolTy) { 5535 Kind = CK_PointerToBoolean; 5536 return Compatible; 5537 } 5538 5539 // T* -> int 5540 if (LHSType->isIntegerType()) { 5541 Kind = CK_PointerToIntegral; 5542 return PointerToInt; 5543 } 5544 5545 return Incompatible; 5546 } 5547 5548 // struct A -> struct B 5549 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 5550 if (Context.typesAreCompatible(LHSType, RHSType)) { 5551 Kind = CK_NoOp; 5552 return Compatible; 5553 } 5554 } 5555 5556 return Incompatible; 5557 } 5558 5559 /// \brief Constructs a transparent union from an expression that is 5560 /// used to initialize the transparent union. 5561 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 5562 ExprResult &EResult, QualType UnionType, 5563 FieldDecl *Field) { 5564 // Build an initializer list that designates the appropriate member 5565 // of the transparent union. 5566 Expr *E = EResult.take(); 5567 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 5568 &E, 1, 5569 SourceLocation()); 5570 Initializer->setType(UnionType); 5571 Initializer->setInitializedFieldInUnion(Field); 5572 5573 // Build a compound literal constructing a value of the transparent 5574 // union type from this initializer list. 5575 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 5576 EResult = S.Owned( 5577 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 5578 VK_RValue, Initializer, false)); 5579 } 5580 5581 Sema::AssignConvertType 5582 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 5583 ExprResult &RHS) { 5584 QualType RHSType = RHS.get()->getType(); 5585 5586 // If the ArgType is a Union type, we want to handle a potential 5587 // transparent_union GCC extension. 5588 const RecordType *UT = ArgType->getAsUnionType(); 5589 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 5590 return Incompatible; 5591 5592 // The field to initialize within the transparent union. 5593 RecordDecl *UD = UT->getDecl(); 5594 FieldDecl *InitField = 0; 5595 // It's compatible if the expression matches any of the fields. 5596 for (RecordDecl::field_iterator it = UD->field_begin(), 5597 itend = UD->field_end(); 5598 it != itend; ++it) { 5599 if (it->getType()->isPointerType()) { 5600 // If the transparent union contains a pointer type, we allow: 5601 // 1) void pointer 5602 // 2) null pointer constant 5603 if (RHSType->isPointerType()) 5604 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 5605 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast); 5606 InitField = *it; 5607 break; 5608 } 5609 5610 if (RHS.get()->isNullPointerConstant(Context, 5611 Expr::NPC_ValueDependentIsNull)) { 5612 RHS = ImpCastExprToType(RHS.take(), it->getType(), 5613 CK_NullToPointer); 5614 InitField = *it; 5615 break; 5616 } 5617 } 5618 5619 CastKind Kind = CK_Invalid; 5620 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 5621 == Compatible) { 5622 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind); 5623 InitField = *it; 5624 break; 5625 } 5626 } 5627 5628 if (!InitField) 5629 return Incompatible; 5630 5631 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 5632 return Compatible; 5633 } 5634 5635 Sema::AssignConvertType 5636 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, 5637 bool Diagnose) { 5638 if (getLangOptions().CPlusPlus) { 5639 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 5640 // C++ 5.17p3: If the left operand is not of class type, the 5641 // expression is implicitly converted (C++ 4) to the 5642 // cv-unqualified type of the left operand. 5643 ExprResult Res; 5644 if (Diagnose) { 5645 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 5646 AA_Assigning); 5647 } else { 5648 ImplicitConversionSequence ICS = 5649 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 5650 /*SuppressUserConversions=*/false, 5651 /*AllowExplicit=*/false, 5652 /*InOverloadResolution=*/false, 5653 /*CStyle=*/false, 5654 /*AllowObjCWritebackConversion=*/false); 5655 if (ICS.isFailure()) 5656 return Incompatible; 5657 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 5658 ICS, AA_Assigning); 5659 } 5660 if (Res.isInvalid()) 5661 return Incompatible; 5662 Sema::AssignConvertType result = Compatible; 5663 if (getLangOptions().ObjCAutoRefCount && 5664 !CheckObjCARCUnavailableWeakConversion(LHSType, 5665 RHS.get()->getType())) 5666 result = IncompatibleObjCWeakRef; 5667 RHS = move(Res); 5668 return result; 5669 } 5670 5671 // FIXME: Currently, we fall through and treat C++ classes like C 5672 // structures. 5673 // FIXME: We also fall through for atomics; not sure what should 5674 // happen there, though. 5675 } 5676 5677 // C99 6.5.16.1p1: the left operand is a pointer and the right is 5678 // a null pointer constant. 5679 if ((LHSType->isPointerType() || 5680 LHSType->isObjCObjectPointerType() || 5681 LHSType->isBlockPointerType()) 5682 && RHS.get()->isNullPointerConstant(Context, 5683 Expr::NPC_ValueDependentIsNull)) { 5684 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer); 5685 return Compatible; 5686 } 5687 5688 // This check seems unnatural, however it is necessary to ensure the proper 5689 // conversion of functions/arrays. If the conversion were done for all 5690 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 5691 // expressions that suppress this implicit conversion (&, sizeof). 5692 // 5693 // Suppress this for references: C++ 8.5.3p5. 5694 if (!LHSType->isReferenceType()) { 5695 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 5696 if (RHS.isInvalid()) 5697 return Incompatible; 5698 } 5699 5700 CastKind Kind = CK_Invalid; 5701 Sema::AssignConvertType result = 5702 CheckAssignmentConstraints(LHSType, RHS, Kind); 5703 5704 // C99 6.5.16.1p2: The value of the right operand is converted to the 5705 // type of the assignment expression. 5706 // CheckAssignmentConstraints allows the left-hand side to be a reference, 5707 // so that we can use references in built-in functions even in C. 5708 // The getNonReferenceType() call makes sure that the resulting expression 5709 // does not have reference type. 5710 if (result != Incompatible && RHS.get()->getType() != LHSType) 5711 RHS = ImpCastExprToType(RHS.take(), 5712 LHSType.getNonLValueExprType(Context), Kind); 5713 return result; 5714 } 5715 5716 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 5717 ExprResult &RHS) { 5718 Diag(Loc, diag::err_typecheck_invalid_operands) 5719 << LHS.get()->getType() << RHS.get()->getType() 5720 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5721 return QualType(); 5722 } 5723 5724 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 5725 SourceLocation Loc, bool IsCompAssign) { 5726 if (!IsCompAssign) { 5727 LHS = DefaultFunctionArrayLvalueConversion(LHS.take()); 5728 if (LHS.isInvalid()) 5729 return QualType(); 5730 } 5731 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 5732 if (RHS.isInvalid()) 5733 return QualType(); 5734 5735 // For conversion purposes, we ignore any qualifiers. 5736 // For example, "const float" and "float" are equivalent. 5737 QualType LHSType = 5738 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 5739 QualType RHSType = 5740 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 5741 5742 // If the vector types are identical, return. 5743 if (LHSType == RHSType) 5744 return LHSType; 5745 5746 // Handle the case of equivalent AltiVec and GCC vector types 5747 if (LHSType->isVectorType() && RHSType->isVectorType() && 5748 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 5749 if (LHSType->isExtVectorType()) { 5750 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 5751 return LHSType; 5752 } 5753 5754 if (!IsCompAssign) 5755 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 5756 return RHSType; 5757 } 5758 5759 if (getLangOptions().LaxVectorConversions && 5760 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) { 5761 // If we are allowing lax vector conversions, and LHS and RHS are both 5762 // vectors, the total size only needs to be the same. This is a 5763 // bitcast; no bits are changed but the result type is different. 5764 // FIXME: Should we really be allowing this? 5765 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 5766 return LHSType; 5767 } 5768 5769 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can 5770 // swap back (so that we don't reverse the inputs to a subtract, for instance. 5771 bool swapped = false; 5772 if (RHSType->isExtVectorType() && !IsCompAssign) { 5773 swapped = true; 5774 std::swap(RHS, LHS); 5775 std::swap(RHSType, LHSType); 5776 } 5777 5778 // Handle the case of an ext vector and scalar. 5779 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) { 5780 QualType EltTy = LV->getElementType(); 5781 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) { 5782 int order = Context.getIntegerTypeOrder(EltTy, RHSType); 5783 if (order > 0) 5784 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast); 5785 if (order >= 0) { 5786 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat); 5787 if (swapped) std::swap(RHS, LHS); 5788 return LHSType; 5789 } 5790 } 5791 if (EltTy->isRealFloatingType() && RHSType->isScalarType() && 5792 RHSType->isRealFloatingType()) { 5793 int order = Context.getFloatingTypeOrder(EltTy, RHSType); 5794 if (order > 0) 5795 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast); 5796 if (order >= 0) { 5797 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat); 5798 if (swapped) std::swap(RHS, LHS); 5799 return LHSType; 5800 } 5801 } 5802 } 5803 5804 // Vectors of different size or scalar and non-ext-vector are errors. 5805 if (swapped) std::swap(RHS, LHS); 5806 Diag(Loc, diag::err_typecheck_vector_not_convertable) 5807 << LHS.get()->getType() << RHS.get()->getType() 5808 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5809 return QualType(); 5810 } 5811 5812 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 5813 // expression. These are mainly cases where the null pointer is used as an 5814 // integer instead of a pointer. 5815 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 5816 SourceLocation Loc, bool IsCompare) { 5817 // The canonical way to check for a GNU null is with isNullPointerConstant, 5818 // but we use a bit of a hack here for speed; this is a relatively 5819 // hot path, and isNullPointerConstant is slow. 5820 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 5821 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 5822 5823 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 5824 5825 // Avoid analyzing cases where the result will either be invalid (and 5826 // diagnosed as such) or entirely valid and not something to warn about. 5827 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 5828 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 5829 return; 5830 5831 // Comparison operations would not make sense with a null pointer no matter 5832 // what the other expression is. 5833 if (!IsCompare) { 5834 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 5835 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 5836 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 5837 return; 5838 } 5839 5840 // The rest of the operations only make sense with a null pointer 5841 // if the other expression is a pointer. 5842 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 5843 NonNullType->canDecayToPointerType()) 5844 return; 5845 5846 S.Diag(Loc, diag::warn_null_in_comparison_operation) 5847 << LHSNull /* LHS is NULL */ << NonNullType 5848 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5849 } 5850 5851 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 5852 SourceLocation Loc, 5853 bool IsCompAssign, bool IsDiv) { 5854 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 5855 5856 if (LHS.get()->getType()->isVectorType() || 5857 RHS.get()->getType()->isVectorType()) 5858 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 5859 5860 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 5861 if (LHS.isInvalid() || RHS.isInvalid()) 5862 return QualType(); 5863 5864 if (!LHS.get()->getType()->isArithmeticType() || 5865 !RHS.get()->getType()->isArithmeticType()) 5866 return InvalidOperands(Loc, LHS, RHS); 5867 5868 // Check for division by zero. 5869 if (IsDiv && 5870 RHS.get()->isNullPointerConstant(Context, 5871 Expr::NPC_ValueDependentIsNotNull)) 5872 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero) 5873 << RHS.get()->getSourceRange()); 5874 5875 return compType; 5876 } 5877 5878 QualType Sema::CheckRemainderOperands( 5879 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 5880 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 5881 5882 if (LHS.get()->getType()->isVectorType() || 5883 RHS.get()->getType()->isVectorType()) { 5884 if (LHS.get()->getType()->hasIntegerRepresentation() && 5885 RHS.get()->getType()->hasIntegerRepresentation()) 5886 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 5887 return InvalidOperands(Loc, LHS, RHS); 5888 } 5889 5890 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 5891 if (LHS.isInvalid() || RHS.isInvalid()) 5892 return QualType(); 5893 5894 if (!LHS.get()->getType()->isIntegerType() || 5895 !RHS.get()->getType()->isIntegerType()) 5896 return InvalidOperands(Loc, LHS, RHS); 5897 5898 // Check for remainder by zero. 5899 if (RHS.get()->isNullPointerConstant(Context, 5900 Expr::NPC_ValueDependentIsNotNull)) 5901 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero) 5902 << RHS.get()->getSourceRange()); 5903 5904 return compType; 5905 } 5906 5907 /// \brief Diagnose invalid arithmetic on two void pointers. 5908 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 5909 Expr *LHSExpr, Expr *RHSExpr) { 5910 S.Diag(Loc, S.getLangOptions().CPlusPlus 5911 ? diag::err_typecheck_pointer_arith_void_type 5912 : diag::ext_gnu_void_ptr) 5913 << 1 /* two pointers */ << LHSExpr->getSourceRange() 5914 << RHSExpr->getSourceRange(); 5915 } 5916 5917 /// \brief Diagnose invalid arithmetic on a void pointer. 5918 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 5919 Expr *Pointer) { 5920 S.Diag(Loc, S.getLangOptions().CPlusPlus 5921 ? diag::err_typecheck_pointer_arith_void_type 5922 : diag::ext_gnu_void_ptr) 5923 << 0 /* one pointer */ << Pointer->getSourceRange(); 5924 } 5925 5926 /// \brief Diagnose invalid arithmetic on two function pointers. 5927 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 5928 Expr *LHS, Expr *RHS) { 5929 assert(LHS->getType()->isAnyPointerType()); 5930 assert(RHS->getType()->isAnyPointerType()); 5931 S.Diag(Loc, S.getLangOptions().CPlusPlus 5932 ? diag::err_typecheck_pointer_arith_function_type 5933 : diag::ext_gnu_ptr_func_arith) 5934 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 5935 // We only show the second type if it differs from the first. 5936 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 5937 RHS->getType()) 5938 << RHS->getType()->getPointeeType() 5939 << LHS->getSourceRange() << RHS->getSourceRange(); 5940 } 5941 5942 /// \brief Diagnose invalid arithmetic on a function pointer. 5943 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 5944 Expr *Pointer) { 5945 assert(Pointer->getType()->isAnyPointerType()); 5946 S.Diag(Loc, S.getLangOptions().CPlusPlus 5947 ? diag::err_typecheck_pointer_arith_function_type 5948 : diag::ext_gnu_ptr_func_arith) 5949 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 5950 << 0 /* one pointer, so only one type */ 5951 << Pointer->getSourceRange(); 5952 } 5953 5954 /// \brief Emit error if Operand is incomplete pointer type 5955 /// 5956 /// \returns True if pointer has incomplete type 5957 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 5958 Expr *Operand) { 5959 if ((Operand->getType()->isPointerType() && 5960 !Operand->getType()->isDependentType()) || 5961 Operand->getType()->isObjCObjectPointerType()) { 5962 QualType PointeeTy = Operand->getType()->getPointeeType(); 5963 if (S.RequireCompleteType( 5964 Loc, PointeeTy, 5965 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type) 5966 << PointeeTy << Operand->getSourceRange())) 5967 return true; 5968 } 5969 return false; 5970 } 5971 5972 /// \brief Check the validity of an arithmetic pointer operand. 5973 /// 5974 /// If the operand has pointer type, this code will check for pointer types 5975 /// which are invalid in arithmetic operations. These will be diagnosed 5976 /// appropriately, including whether or not the use is supported as an 5977 /// extension. 5978 /// 5979 /// \returns True when the operand is valid to use (even if as an extension). 5980 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 5981 Expr *Operand) { 5982 if (!Operand->getType()->isAnyPointerType()) return true; 5983 5984 QualType PointeeTy = Operand->getType()->getPointeeType(); 5985 if (PointeeTy->isVoidType()) { 5986 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 5987 return !S.getLangOptions().CPlusPlus; 5988 } 5989 if (PointeeTy->isFunctionType()) { 5990 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 5991 return !S.getLangOptions().CPlusPlus; 5992 } 5993 5994 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 5995 5996 return true; 5997 } 5998 5999 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 6000 /// operands. 6001 /// 6002 /// This routine will diagnose any invalid arithmetic on pointer operands much 6003 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 6004 /// for emitting a single diagnostic even for operations where both LHS and RHS 6005 /// are (potentially problematic) pointers. 6006 /// 6007 /// \returns True when the operand is valid to use (even if as an extension). 6008 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 6009 Expr *LHSExpr, Expr *RHSExpr) { 6010 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 6011 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 6012 if (!isLHSPointer && !isRHSPointer) return true; 6013 6014 QualType LHSPointeeTy, RHSPointeeTy; 6015 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 6016 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 6017 6018 // Check for arithmetic on pointers to incomplete types. 6019 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 6020 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 6021 if (isLHSVoidPtr || isRHSVoidPtr) { 6022 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 6023 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 6024 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 6025 6026 return !S.getLangOptions().CPlusPlus; 6027 } 6028 6029 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 6030 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 6031 if (isLHSFuncPtr || isRHSFuncPtr) { 6032 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 6033 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 6034 RHSExpr); 6035 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 6036 6037 return !S.getLangOptions().CPlusPlus; 6038 } 6039 6040 if (checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) return false; 6041 if (checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) return false; 6042 6043 return true; 6044 } 6045 6046 /// \brief Check bad cases where we step over interface counts. 6047 static bool checkArithmethicPointerOnNonFragileABI(Sema &S, 6048 SourceLocation OpLoc, 6049 Expr *Op) { 6050 assert(Op->getType()->isAnyPointerType()); 6051 QualType PointeeTy = Op->getType()->getPointeeType(); 6052 if (!PointeeTy->isObjCObjectType() || !S.LangOpts.ObjCNonFragileABI) 6053 return true; 6054 6055 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface) 6056 << PointeeTy << Op->getSourceRange(); 6057 return false; 6058 } 6059 6060 /// \brief Emit error when two pointers are incompatible. 6061 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 6062 Expr *LHSExpr, Expr *RHSExpr) { 6063 assert(LHSExpr->getType()->isAnyPointerType()); 6064 assert(RHSExpr->getType()->isAnyPointerType()); 6065 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 6066 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 6067 << RHSExpr->getSourceRange(); 6068 } 6069 6070 QualType Sema::CheckAdditionOperands( // C99 6.5.6 6071 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType* CompLHSTy) { 6072 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6073 6074 if (LHS.get()->getType()->isVectorType() || 6075 RHS.get()->getType()->isVectorType()) { 6076 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 6077 if (CompLHSTy) *CompLHSTy = compType; 6078 return compType; 6079 } 6080 6081 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 6082 if (LHS.isInvalid() || RHS.isInvalid()) 6083 return QualType(); 6084 6085 // handle the common case first (both operands are arithmetic). 6086 if (LHS.get()->getType()->isArithmeticType() && 6087 RHS.get()->getType()->isArithmeticType()) { 6088 if (CompLHSTy) *CompLHSTy = compType; 6089 return compType; 6090 } 6091 6092 // Put any potential pointer into PExp 6093 Expr* PExp = LHS.get(), *IExp = RHS.get(); 6094 if (IExp->getType()->isAnyPointerType()) 6095 std::swap(PExp, IExp); 6096 6097 if (!PExp->getType()->isAnyPointerType()) 6098 return InvalidOperands(Loc, LHS, RHS); 6099 6100 if (!IExp->getType()->isIntegerType()) 6101 return InvalidOperands(Loc, LHS, RHS); 6102 6103 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 6104 return QualType(); 6105 6106 // Diagnose bad cases where we step over interface counts. 6107 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp)) 6108 return QualType(); 6109 6110 // Check array bounds for pointer arithemtic 6111 CheckArrayAccess(PExp, IExp); 6112 6113 if (CompLHSTy) { 6114 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 6115 if (LHSTy.isNull()) { 6116 LHSTy = LHS.get()->getType(); 6117 if (LHSTy->isPromotableIntegerType()) 6118 LHSTy = Context.getPromotedIntegerType(LHSTy); 6119 } 6120 *CompLHSTy = LHSTy; 6121 } 6122 6123 return PExp->getType(); 6124 } 6125 6126 // C99 6.5.6 6127 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 6128 SourceLocation Loc, 6129 QualType* CompLHSTy) { 6130 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6131 6132 if (LHS.get()->getType()->isVectorType() || 6133 RHS.get()->getType()->isVectorType()) { 6134 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 6135 if (CompLHSTy) *CompLHSTy = compType; 6136 return compType; 6137 } 6138 6139 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 6140 if (LHS.isInvalid() || RHS.isInvalid()) 6141 return QualType(); 6142 6143 // Enforce type constraints: C99 6.5.6p3. 6144 6145 // Handle the common case first (both operands are arithmetic). 6146 if (LHS.get()->getType()->isArithmeticType() && 6147 RHS.get()->getType()->isArithmeticType()) { 6148 if (CompLHSTy) *CompLHSTy = compType; 6149 return compType; 6150 } 6151 6152 // Either ptr - int or ptr - ptr. 6153 if (LHS.get()->getType()->isAnyPointerType()) { 6154 QualType lpointee = LHS.get()->getType()->getPointeeType(); 6155 6156 // Diagnose bad cases where we step over interface counts. 6157 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, LHS.get())) 6158 return QualType(); 6159 6160 // The result type of a pointer-int computation is the pointer type. 6161 if (RHS.get()->getType()->isIntegerType()) { 6162 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 6163 return QualType(); 6164 6165 Expr *IExpr = RHS.get()->IgnoreParenCasts(); 6166 UnaryOperator negRex(IExpr, UO_Minus, IExpr->getType(), VK_RValue, 6167 OK_Ordinary, IExpr->getExprLoc()); 6168 // Check array bounds for pointer arithemtic 6169 CheckArrayAccess(LHS.get()->IgnoreParenCasts(), &negRex); 6170 6171 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 6172 return LHS.get()->getType(); 6173 } 6174 6175 // Handle pointer-pointer subtractions. 6176 if (const PointerType *RHSPTy 6177 = RHS.get()->getType()->getAs<PointerType>()) { 6178 QualType rpointee = RHSPTy->getPointeeType(); 6179 6180 if (getLangOptions().CPlusPlus) { 6181 // Pointee types must be the same: C++ [expr.add] 6182 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 6183 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 6184 } 6185 } else { 6186 // Pointee types must be compatible C99 6.5.6p3 6187 if (!Context.typesAreCompatible( 6188 Context.getCanonicalType(lpointee).getUnqualifiedType(), 6189 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 6190 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 6191 return QualType(); 6192 } 6193 } 6194 6195 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 6196 LHS.get(), RHS.get())) 6197 return QualType(); 6198 6199 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 6200 return Context.getPointerDiffType(); 6201 } 6202 } 6203 6204 return InvalidOperands(Loc, LHS, RHS); 6205 } 6206 6207 static bool isScopedEnumerationType(QualType T) { 6208 if (const EnumType *ET = dyn_cast<EnumType>(T)) 6209 return ET->getDecl()->isScoped(); 6210 return false; 6211 } 6212 6213 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 6214 SourceLocation Loc, unsigned Opc, 6215 QualType LHSType) { 6216 llvm::APSInt Right; 6217 // Check right/shifter operand 6218 if (RHS.get()->isValueDependent() || 6219 !RHS.get()->isIntegerConstantExpr(Right, S.Context)) 6220 return; 6221 6222 if (Right.isNegative()) { 6223 S.DiagRuntimeBehavior(Loc, RHS.get(), 6224 S.PDiag(diag::warn_shift_negative) 6225 << RHS.get()->getSourceRange()); 6226 return; 6227 } 6228 llvm::APInt LeftBits(Right.getBitWidth(), 6229 S.Context.getTypeSize(LHS.get()->getType())); 6230 if (Right.uge(LeftBits)) { 6231 S.DiagRuntimeBehavior(Loc, RHS.get(), 6232 S.PDiag(diag::warn_shift_gt_typewidth) 6233 << RHS.get()->getSourceRange()); 6234 return; 6235 } 6236 if (Opc != BO_Shl) 6237 return; 6238 6239 // When left shifting an ICE which is signed, we can check for overflow which 6240 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 6241 // integers have defined behavior modulo one more than the maximum value 6242 // representable in the result type, so never warn for those. 6243 llvm::APSInt Left; 6244 if (LHS.get()->isValueDependent() || 6245 !LHS.get()->isIntegerConstantExpr(Left, S.Context) || 6246 LHSType->hasUnsignedIntegerRepresentation()) 6247 return; 6248 llvm::APInt ResultBits = 6249 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 6250 if (LeftBits.uge(ResultBits)) 6251 return; 6252 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 6253 Result = Result.shl(Right); 6254 6255 // Print the bit representation of the signed integer as an unsigned 6256 // hexadecimal number. 6257 llvm::SmallString<40> HexResult; 6258 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 6259 6260 // If we are only missing a sign bit, this is less likely to result in actual 6261 // bugs -- if the result is cast back to an unsigned type, it will have the 6262 // expected value. Thus we place this behind a different warning that can be 6263 // turned off separately if needed. 6264 if (LeftBits == ResultBits - 1) { 6265 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 6266 << HexResult.str() << LHSType 6267 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6268 return; 6269 } 6270 6271 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 6272 << HexResult.str() << Result.getMinSignedBits() << LHSType 6273 << Left.getBitWidth() << LHS.get()->getSourceRange() 6274 << RHS.get()->getSourceRange(); 6275 } 6276 6277 // C99 6.5.7 6278 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 6279 SourceLocation Loc, unsigned Opc, 6280 bool IsCompAssign) { 6281 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6282 6283 // C99 6.5.7p2: Each of the operands shall have integer type. 6284 if (!LHS.get()->getType()->hasIntegerRepresentation() || 6285 !RHS.get()->getType()->hasIntegerRepresentation()) 6286 return InvalidOperands(Loc, LHS, RHS); 6287 6288 // C++0x: Don't allow scoped enums. FIXME: Use something better than 6289 // hasIntegerRepresentation() above instead of this. 6290 if (isScopedEnumerationType(LHS.get()->getType()) || 6291 isScopedEnumerationType(RHS.get()->getType())) { 6292 return InvalidOperands(Loc, LHS, RHS); 6293 } 6294 6295 // Vector shifts promote their scalar inputs to vector type. 6296 if (LHS.get()->getType()->isVectorType() || 6297 RHS.get()->getType()->isVectorType()) 6298 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6299 6300 // Shifts don't perform usual arithmetic conversions, they just do integer 6301 // promotions on each operand. C99 6.5.7p3 6302 6303 // For the LHS, do usual unary conversions, but then reset them away 6304 // if this is a compound assignment. 6305 ExprResult OldLHS = LHS; 6306 LHS = UsualUnaryConversions(LHS.take()); 6307 if (LHS.isInvalid()) 6308 return QualType(); 6309 QualType LHSType = LHS.get()->getType(); 6310 if (IsCompAssign) LHS = OldLHS; 6311 6312 // The RHS is simpler. 6313 RHS = UsualUnaryConversions(RHS.take()); 6314 if (RHS.isInvalid()) 6315 return QualType(); 6316 6317 // Sanity-check shift operands 6318 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 6319 6320 // "The type of the result is that of the promoted left operand." 6321 return LHSType; 6322 } 6323 6324 static bool IsWithinTemplateSpecialization(Decl *D) { 6325 if (DeclContext *DC = D->getDeclContext()) { 6326 if (isa<ClassTemplateSpecializationDecl>(DC)) 6327 return true; 6328 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 6329 return FD->isFunctionTemplateSpecialization(); 6330 } 6331 return false; 6332 } 6333 6334 /// If two different enums are compared, raise a warning. 6335 static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, 6336 ExprResult &RHS) { 6337 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType(); 6338 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType(); 6339 6340 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 6341 if (!LHSEnumType) 6342 return; 6343 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 6344 if (!RHSEnumType) 6345 return; 6346 6347 // Ignore anonymous enums. 6348 if (!LHSEnumType->getDecl()->getIdentifier()) 6349 return; 6350 if (!RHSEnumType->getDecl()->getIdentifier()) 6351 return; 6352 6353 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 6354 return; 6355 6356 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 6357 << LHSStrippedType << RHSStrippedType 6358 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6359 } 6360 6361 /// \brief Diagnose bad pointer comparisons. 6362 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 6363 ExprResult &LHS, ExprResult &RHS, 6364 bool IsError) { 6365 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 6366 : diag::ext_typecheck_comparison_of_distinct_pointers) 6367 << LHS.get()->getType() << RHS.get()->getType() 6368 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6369 } 6370 6371 /// \brief Returns false if the pointers are converted to a composite type, 6372 /// true otherwise. 6373 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 6374 ExprResult &LHS, ExprResult &RHS) { 6375 // C++ [expr.rel]p2: 6376 // [...] Pointer conversions (4.10) and qualification 6377 // conversions (4.4) are performed on pointer operands (or on 6378 // a pointer operand and a null pointer constant) to bring 6379 // them to their composite pointer type. [...] 6380 // 6381 // C++ [expr.eq]p1 uses the same notion for (in)equality 6382 // comparisons of pointers. 6383 6384 // C++ [expr.eq]p2: 6385 // In addition, pointers to members can be compared, or a pointer to 6386 // member and a null pointer constant. Pointer to member conversions 6387 // (4.11) and qualification conversions (4.4) are performed to bring 6388 // them to a common type. If one operand is a null pointer constant, 6389 // the common type is the type of the other operand. Otherwise, the 6390 // common type is a pointer to member type similar (4.4) to the type 6391 // of one of the operands, with a cv-qualification signature (4.4) 6392 // that is the union of the cv-qualification signatures of the operand 6393 // types. 6394 6395 QualType LHSType = LHS.get()->getType(); 6396 QualType RHSType = RHS.get()->getType(); 6397 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 6398 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 6399 6400 bool NonStandardCompositeType = false; 6401 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType; 6402 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 6403 if (T.isNull()) { 6404 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 6405 return true; 6406 } 6407 6408 if (NonStandardCompositeType) 6409 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 6410 << LHSType << RHSType << T << LHS.get()->getSourceRange() 6411 << RHS.get()->getSourceRange(); 6412 6413 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast); 6414 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast); 6415 return false; 6416 } 6417 6418 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 6419 ExprResult &LHS, 6420 ExprResult &RHS, 6421 bool IsError) { 6422 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 6423 : diag::ext_typecheck_comparison_of_fptr_to_void) 6424 << LHS.get()->getType() << RHS.get()->getType() 6425 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6426 } 6427 6428 // C99 6.5.8, C++ [expr.rel] 6429 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 6430 SourceLocation Loc, unsigned OpaqueOpc, 6431 bool IsRelational) { 6432 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 6433 6434 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc; 6435 6436 // Handle vector comparisons separately. 6437 if (LHS.get()->getType()->isVectorType() || 6438 RHS.get()->getType()->isVectorType()) 6439 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 6440 6441 QualType LHSType = LHS.get()->getType(); 6442 QualType RHSType = RHS.get()->getType(); 6443 6444 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 6445 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 6446 6447 checkEnumComparison(*this, Loc, LHS, RHS); 6448 6449 if (!LHSType->hasFloatingRepresentation() && 6450 !(LHSType->isBlockPointerType() && IsRelational) && 6451 !LHS.get()->getLocStart().isMacroID() && 6452 !RHS.get()->getLocStart().isMacroID()) { 6453 // For non-floating point types, check for self-comparisons of the form 6454 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 6455 // often indicate logic errors in the program. 6456 // 6457 // NOTE: Don't warn about comparison expressions resulting from macro 6458 // expansion. Also don't warn about comparisons which are only self 6459 // comparisons within a template specialization. The warnings should catch 6460 // obvious cases in the definition of the template anyways. The idea is to 6461 // warn when the typed comparison operator will always evaluate to the same 6462 // result. 6463 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) { 6464 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) { 6465 if (DRL->getDecl() == DRR->getDecl() && 6466 !IsWithinTemplateSpecialization(DRL->getDecl())) { 6467 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 6468 << 0 // self- 6469 << (Opc == BO_EQ 6470 || Opc == BO_LE 6471 || Opc == BO_GE)); 6472 } else if (LHSType->isArrayType() && RHSType->isArrayType() && 6473 !DRL->getDecl()->getType()->isReferenceType() && 6474 !DRR->getDecl()->getType()->isReferenceType()) { 6475 // what is it always going to eval to? 6476 char always_evals_to; 6477 switch(Opc) { 6478 case BO_EQ: // e.g. array1 == array2 6479 always_evals_to = 0; // false 6480 break; 6481 case BO_NE: // e.g. array1 != array2 6482 always_evals_to = 1; // true 6483 break; 6484 default: 6485 // best we can say is 'a constant' 6486 always_evals_to = 2; // e.g. array1 <= array2 6487 break; 6488 } 6489 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 6490 << 1 // array 6491 << always_evals_to); 6492 } 6493 } 6494 } 6495 6496 if (isa<CastExpr>(LHSStripped)) 6497 LHSStripped = LHSStripped->IgnoreParenCasts(); 6498 if (isa<CastExpr>(RHSStripped)) 6499 RHSStripped = RHSStripped->IgnoreParenCasts(); 6500 6501 // Warn about comparisons against a string constant (unless the other 6502 // operand is null), the user probably wants strcmp. 6503 Expr *literalString = 0; 6504 Expr *literalStringStripped = 0; 6505 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 6506 !RHSStripped->isNullPointerConstant(Context, 6507 Expr::NPC_ValueDependentIsNull)) { 6508 literalString = LHS.get(); 6509 literalStringStripped = LHSStripped; 6510 } else if ((isa<StringLiteral>(RHSStripped) || 6511 isa<ObjCEncodeExpr>(RHSStripped)) && 6512 !LHSStripped->isNullPointerConstant(Context, 6513 Expr::NPC_ValueDependentIsNull)) { 6514 literalString = RHS.get(); 6515 literalStringStripped = RHSStripped; 6516 } 6517 6518 if (literalString) { 6519 std::string resultComparison; 6520 switch (Opc) { 6521 case BO_LT: resultComparison = ") < 0"; break; 6522 case BO_GT: resultComparison = ") > 0"; break; 6523 case BO_LE: resultComparison = ") <= 0"; break; 6524 case BO_GE: resultComparison = ") >= 0"; break; 6525 case BO_EQ: resultComparison = ") == 0"; break; 6526 case BO_NE: resultComparison = ") != 0"; break; 6527 default: llvm_unreachable("Invalid comparison operator"); 6528 } 6529 6530 DiagRuntimeBehavior(Loc, 0, 6531 PDiag(diag::warn_stringcompare) 6532 << isa<ObjCEncodeExpr>(literalStringStripped) 6533 << literalString->getSourceRange()); 6534 } 6535 } 6536 6537 // C99 6.5.8p3 / C99 6.5.9p4 6538 if (LHS.get()->getType()->isArithmeticType() && 6539 RHS.get()->getType()->isArithmeticType()) { 6540 UsualArithmeticConversions(LHS, RHS); 6541 if (LHS.isInvalid() || RHS.isInvalid()) 6542 return QualType(); 6543 } 6544 else { 6545 LHS = UsualUnaryConversions(LHS.take()); 6546 if (LHS.isInvalid()) 6547 return QualType(); 6548 6549 RHS = UsualUnaryConversions(RHS.take()); 6550 if (RHS.isInvalid()) 6551 return QualType(); 6552 } 6553 6554 LHSType = LHS.get()->getType(); 6555 RHSType = RHS.get()->getType(); 6556 6557 // The result of comparisons is 'bool' in C++, 'int' in C. 6558 QualType ResultTy = Context.getLogicalOperationType(); 6559 6560 if (IsRelational) { 6561 if (LHSType->isRealType() && RHSType->isRealType()) 6562 return ResultTy; 6563 } else { 6564 // Check for comparisons of floating point operands using != and ==. 6565 if (LHSType->hasFloatingRepresentation()) 6566 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 6567 6568 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 6569 return ResultTy; 6570 } 6571 6572 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context, 6573 Expr::NPC_ValueDependentIsNull); 6574 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context, 6575 Expr::NPC_ValueDependentIsNull); 6576 6577 // All of the following pointer-related warnings are GCC extensions, except 6578 // when handling null pointer constants. 6579 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 6580 QualType LCanPointeeTy = 6581 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 6582 QualType RCanPointeeTy = 6583 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 6584 6585 if (getLangOptions().CPlusPlus) { 6586 if (LCanPointeeTy == RCanPointeeTy) 6587 return ResultTy; 6588 if (!IsRelational && 6589 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 6590 // Valid unless comparison between non-null pointer and function pointer 6591 // This is a gcc extension compatibility comparison. 6592 // In a SFINAE context, we treat this as a hard error to maintain 6593 // conformance with the C++ standard. 6594 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 6595 && !LHSIsNull && !RHSIsNull) { 6596 diagnoseFunctionPointerToVoidComparison( 6597 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext()); 6598 6599 if (isSFINAEContext()) 6600 return QualType(); 6601 6602 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6603 return ResultTy; 6604 } 6605 } 6606 6607 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 6608 return QualType(); 6609 else 6610 return ResultTy; 6611 } 6612 // C99 6.5.9p2 and C99 6.5.8p2 6613 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 6614 RCanPointeeTy.getUnqualifiedType())) { 6615 // Valid unless a relational comparison of function pointers 6616 if (IsRelational && LCanPointeeTy->isFunctionType()) { 6617 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 6618 << LHSType << RHSType << LHS.get()->getSourceRange() 6619 << RHS.get()->getSourceRange(); 6620 } 6621 } else if (!IsRelational && 6622 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 6623 // Valid unless comparison between non-null pointer and function pointer 6624 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 6625 && !LHSIsNull && !RHSIsNull) 6626 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 6627 /*isError*/false); 6628 } else { 6629 // Invalid 6630 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 6631 } 6632 if (LCanPointeeTy != RCanPointeeTy) { 6633 if (LHSIsNull && !RHSIsNull) 6634 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 6635 else 6636 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6637 } 6638 return ResultTy; 6639 } 6640 6641 if (getLangOptions().CPlusPlus) { 6642 // Comparison of nullptr_t with itself. 6643 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 6644 return ResultTy; 6645 6646 // Comparison of pointers with null pointer constants and equality 6647 // comparisons of member pointers to null pointer constants. 6648 if (RHSIsNull && 6649 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 6650 (!IsRelational && 6651 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 6652 RHS = ImpCastExprToType(RHS.take(), LHSType, 6653 LHSType->isMemberPointerType() 6654 ? CK_NullToMemberPointer 6655 : CK_NullToPointer); 6656 return ResultTy; 6657 } 6658 if (LHSIsNull && 6659 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 6660 (!IsRelational && 6661 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 6662 LHS = ImpCastExprToType(LHS.take(), RHSType, 6663 RHSType->isMemberPointerType() 6664 ? CK_NullToMemberPointer 6665 : CK_NullToPointer); 6666 return ResultTy; 6667 } 6668 6669 // Comparison of member pointers. 6670 if (!IsRelational && 6671 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 6672 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 6673 return QualType(); 6674 else 6675 return ResultTy; 6676 } 6677 6678 // Handle scoped enumeration types specifically, since they don't promote 6679 // to integers. 6680 if (LHS.get()->getType()->isEnumeralType() && 6681 Context.hasSameUnqualifiedType(LHS.get()->getType(), 6682 RHS.get()->getType())) 6683 return ResultTy; 6684 } 6685 6686 // Handle block pointer types. 6687 if (!IsRelational && LHSType->isBlockPointerType() && 6688 RHSType->isBlockPointerType()) { 6689 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 6690 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 6691 6692 if (!LHSIsNull && !RHSIsNull && 6693 !Context.typesAreCompatible(lpointee, rpointee)) { 6694 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 6695 << LHSType << RHSType << LHS.get()->getSourceRange() 6696 << RHS.get()->getSourceRange(); 6697 } 6698 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6699 return ResultTy; 6700 } 6701 6702 // Allow block pointers to be compared with null pointer constants. 6703 if (!IsRelational 6704 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 6705 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 6706 if (!LHSIsNull && !RHSIsNull) { 6707 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 6708 ->getPointeeType()->isVoidType()) 6709 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 6710 ->getPointeeType()->isVoidType()))) 6711 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 6712 << LHSType << RHSType << LHS.get()->getSourceRange() 6713 << RHS.get()->getSourceRange(); 6714 } 6715 if (LHSIsNull && !RHSIsNull) 6716 LHS = ImpCastExprToType(LHS.take(), RHSType, 6717 RHSType->isPointerType() ? CK_BitCast 6718 : CK_AnyPointerToBlockPointerCast); 6719 else 6720 RHS = ImpCastExprToType(RHS.take(), LHSType, 6721 LHSType->isPointerType() ? CK_BitCast 6722 : CK_AnyPointerToBlockPointerCast); 6723 return ResultTy; 6724 } 6725 6726 if (LHSType->isObjCObjectPointerType() || 6727 RHSType->isObjCObjectPointerType()) { 6728 const PointerType *LPT = LHSType->getAs<PointerType>(); 6729 const PointerType *RPT = RHSType->getAs<PointerType>(); 6730 if (LPT || RPT) { 6731 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 6732 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 6733 6734 if (!LPtrToVoid && !RPtrToVoid && 6735 !Context.typesAreCompatible(LHSType, RHSType)) { 6736 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 6737 /*isError*/false); 6738 } 6739 if (LHSIsNull && !RHSIsNull) 6740 LHS = ImpCastExprToType(LHS.take(), RHSType, 6741 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 6742 else 6743 RHS = ImpCastExprToType(RHS.take(), LHSType, 6744 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 6745 return ResultTy; 6746 } 6747 if (LHSType->isObjCObjectPointerType() && 6748 RHSType->isObjCObjectPointerType()) { 6749 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 6750 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 6751 /*isError*/false); 6752 if (LHSIsNull && !RHSIsNull) 6753 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 6754 else 6755 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6756 return ResultTy; 6757 } 6758 } 6759 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 6760 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 6761 unsigned DiagID = 0; 6762 bool isError = false; 6763 if ((LHSIsNull && LHSType->isIntegerType()) || 6764 (RHSIsNull && RHSType->isIntegerType())) { 6765 if (IsRelational && !getLangOptions().CPlusPlus) 6766 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 6767 } else if (IsRelational && !getLangOptions().CPlusPlus) 6768 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 6769 else if (getLangOptions().CPlusPlus) { 6770 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 6771 isError = true; 6772 } else 6773 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 6774 6775 if (DiagID) { 6776 Diag(Loc, DiagID) 6777 << LHSType << RHSType << LHS.get()->getSourceRange() 6778 << RHS.get()->getSourceRange(); 6779 if (isError) 6780 return QualType(); 6781 } 6782 6783 if (LHSType->isIntegerType()) 6784 LHS = ImpCastExprToType(LHS.take(), RHSType, 6785 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 6786 else 6787 RHS = ImpCastExprToType(RHS.take(), LHSType, 6788 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 6789 return ResultTy; 6790 } 6791 6792 // Handle block pointers. 6793 if (!IsRelational && RHSIsNull 6794 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 6795 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer); 6796 return ResultTy; 6797 } 6798 if (!IsRelational && LHSIsNull 6799 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 6800 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer); 6801 return ResultTy; 6802 } 6803 6804 return InvalidOperands(Loc, LHS, RHS); 6805 } 6806 6807 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 6808 /// operates on extended vector types. Instead of producing an IntTy result, 6809 /// like a scalar comparison, a vector comparison produces a vector of integer 6810 /// types. 6811 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 6812 SourceLocation Loc, 6813 bool IsRelational) { 6814 // Check to make sure we're operating on vectors of the same type and width, 6815 // Allowing one side to be a scalar of element type. 6816 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false); 6817 if (vType.isNull()) 6818 return vType; 6819 6820 QualType LHSType = LHS.get()->getType(); 6821 QualType RHSType = RHS.get()->getType(); 6822 6823 // If AltiVec, the comparison results in a numeric type, i.e. 6824 // bool for C++, int for C 6825 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 6826 return Context.getLogicalOperationType(); 6827 6828 // For non-floating point types, check for self-comparisons of the form 6829 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 6830 // often indicate logic errors in the program. 6831 if (!LHSType->hasFloatingRepresentation()) { 6832 if (DeclRefExpr* DRL 6833 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 6834 if (DeclRefExpr* DRR 6835 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 6836 if (DRL->getDecl() == DRR->getDecl()) 6837 DiagRuntimeBehavior(Loc, 0, 6838 PDiag(diag::warn_comparison_always) 6839 << 0 // self- 6840 << 2 // "a constant" 6841 ); 6842 } 6843 6844 // Check for comparisons of floating point operands using != and ==. 6845 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 6846 assert (RHSType->hasFloatingRepresentation()); 6847 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 6848 } 6849 6850 // Return a signed type that is of identical size and number of elements. 6851 // For floating point vectors, return an integer type of identical size 6852 // and number of elements. 6853 const VectorType *VTy = LHSType->getAs<VectorType>(); 6854 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 6855 if (TypeSize == Context.getTypeSize(Context.CharTy)) 6856 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 6857 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 6858 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 6859 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 6860 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 6861 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 6862 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 6863 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 6864 "Unhandled vector element size in vector compare"); 6865 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 6866 } 6867 6868 inline QualType Sema::CheckBitwiseOperands( 6869 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 6870 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6871 6872 if (LHS.get()->getType()->isVectorType() || 6873 RHS.get()->getType()->isVectorType()) { 6874 if (LHS.get()->getType()->hasIntegerRepresentation() && 6875 RHS.get()->getType()->hasIntegerRepresentation()) 6876 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6877 6878 return InvalidOperands(Loc, LHS, RHS); 6879 } 6880 6881 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS); 6882 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 6883 IsCompAssign); 6884 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 6885 return QualType(); 6886 LHS = LHSResult.take(); 6887 RHS = RHSResult.take(); 6888 6889 if (LHS.get()->getType()->isIntegralOrUnscopedEnumerationType() && 6890 RHS.get()->getType()->isIntegralOrUnscopedEnumerationType()) 6891 return compType; 6892 return InvalidOperands(Loc, LHS, RHS); 6893 } 6894 6895 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 6896 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) { 6897 6898 // Diagnose cases where the user write a logical and/or but probably meant a 6899 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 6900 // is a constant. 6901 if (LHS.get()->getType()->isIntegerType() && 6902 !LHS.get()->getType()->isBooleanType() && 6903 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 6904 // Don't warn in macros or template instantiations. 6905 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 6906 // If the RHS can be constant folded, and if it constant folds to something 6907 // that isn't 0 or 1 (which indicate a potential logical operation that 6908 // happened to fold to true/false) then warn. 6909 // Parens on the RHS are ignored. 6910 llvm::APSInt Result; 6911 if (RHS.get()->EvaluateAsInt(Result, Context)) 6912 if ((getLangOptions().Bool && !RHS.get()->getType()->isBooleanType()) || 6913 (Result != 0 && Result != 1)) { 6914 Diag(Loc, diag::warn_logical_instead_of_bitwise) 6915 << RHS.get()->getSourceRange() 6916 << (Opc == BO_LAnd ? "&&" : "||"); 6917 // Suggest replacing the logical operator with the bitwise version 6918 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 6919 << (Opc == BO_LAnd ? "&" : "|") 6920 << FixItHint::CreateReplacement(SourceRange( 6921 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(), 6922 getLangOptions())), 6923 Opc == BO_LAnd ? "&" : "|"); 6924 if (Opc == BO_LAnd) 6925 // Suggest replacing "Foo() && kNonZero" with "Foo()" 6926 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 6927 << FixItHint::CreateRemoval( 6928 SourceRange( 6929 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(), 6930 0, getSourceManager(), 6931 getLangOptions()), 6932 RHS.get()->getLocEnd())); 6933 } 6934 } 6935 6936 if (!Context.getLangOptions().CPlusPlus) { 6937 LHS = UsualUnaryConversions(LHS.take()); 6938 if (LHS.isInvalid()) 6939 return QualType(); 6940 6941 RHS = UsualUnaryConversions(RHS.take()); 6942 if (RHS.isInvalid()) 6943 return QualType(); 6944 6945 if (!LHS.get()->getType()->isScalarType() || 6946 !RHS.get()->getType()->isScalarType()) 6947 return InvalidOperands(Loc, LHS, RHS); 6948 6949 return Context.IntTy; 6950 } 6951 6952 // The following is safe because we only use this method for 6953 // non-overloadable operands. 6954 6955 // C++ [expr.log.and]p1 6956 // C++ [expr.log.or]p1 6957 // The operands are both contextually converted to type bool. 6958 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 6959 if (LHSRes.isInvalid()) 6960 return InvalidOperands(Loc, LHS, RHS); 6961 LHS = move(LHSRes); 6962 6963 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 6964 if (RHSRes.isInvalid()) 6965 return InvalidOperands(Loc, LHS, RHS); 6966 RHS = move(RHSRes); 6967 6968 // C++ [expr.log.and]p2 6969 // C++ [expr.log.or]p2 6970 // The result is a bool. 6971 return Context.BoolTy; 6972 } 6973 6974 /// IsReadonlyProperty - Verify that otherwise a valid l-value expression 6975 /// is a read-only property; return true if so. A readonly property expression 6976 /// depends on various declarations and thus must be treated specially. 6977 /// 6978 static bool IsReadonlyProperty(Expr *E, Sema &S) { 6979 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E); 6980 if (!PropExpr) return false; 6981 if (PropExpr->isImplicitProperty()) return false; 6982 6983 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty(); 6984 QualType BaseType = PropExpr->isSuperReceiver() ? 6985 PropExpr->getSuperReceiverType() : 6986 PropExpr->getBase()->getType(); 6987 6988 if (const ObjCObjectPointerType *OPT = 6989 BaseType->getAsObjCInterfacePointerType()) 6990 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl()) 6991 if (S.isPropertyReadonly(PDecl, IFace)) 6992 return true; 6993 return false; 6994 } 6995 6996 static bool IsConstProperty(Expr *E, Sema &S) { 6997 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E); 6998 if (!PropExpr) return false; 6999 if (PropExpr->isImplicitProperty()) return false; 7000 7001 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty(); 7002 QualType T = PDecl->getType().getNonReferenceType(); 7003 return T.isConstQualified(); 7004 } 7005 7006 static bool IsReadonlyMessage(Expr *E, Sema &S) { 7007 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 7008 if (!ME) return false; 7009 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 7010 ObjCMessageExpr *Base = 7011 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 7012 if (!Base) return false; 7013 return Base->getMethodDecl() != 0; 7014 } 7015 7016 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 7017 /// emit an error and return true. If so, return false. 7018 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 7019 SourceLocation OrigLoc = Loc; 7020 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 7021 &Loc); 7022 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S)) 7023 IsLV = Expr::MLV_ReadonlyProperty; 7024 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S)) 7025 IsLV = Expr::MLV_Valid; 7026 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 7027 IsLV = Expr::MLV_InvalidMessageExpression; 7028 if (IsLV == Expr::MLV_Valid) 7029 return false; 7030 7031 unsigned Diag = 0; 7032 bool NeedType = false; 7033 switch (IsLV) { // C99 6.5.16p2 7034 case Expr::MLV_ConstQualified: 7035 Diag = diag::err_typecheck_assign_const; 7036 7037 // In ARC, use some specialized diagnostics for occasions where we 7038 // infer 'const'. These are always pseudo-strong variables. 7039 if (S.getLangOptions().ObjCAutoRefCount) { 7040 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 7041 if (declRef && isa<VarDecl>(declRef->getDecl())) { 7042 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 7043 7044 // Use the normal diagnostic if it's pseudo-__strong but the 7045 // user actually wrote 'const'. 7046 if (var->isARCPseudoStrong() && 7047 (!var->getTypeSourceInfo() || 7048 !var->getTypeSourceInfo()->getType().isConstQualified())) { 7049 // There are two pseudo-strong cases: 7050 // - self 7051 ObjCMethodDecl *method = S.getCurMethodDecl(); 7052 if (method && var == method->getSelfDecl()) 7053 Diag = diag::err_typecheck_arr_assign_self; 7054 7055 // - fast enumeration variables 7056 else 7057 Diag = diag::err_typecheck_arr_assign_enumeration; 7058 7059 SourceRange Assign; 7060 if (Loc != OrigLoc) 7061 Assign = SourceRange(OrigLoc, OrigLoc); 7062 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 7063 // We need to preserve the AST regardless, so migration tool 7064 // can do its job. 7065 return false; 7066 } 7067 } 7068 } 7069 7070 break; 7071 case Expr::MLV_ArrayType: 7072 Diag = diag::err_typecheck_array_not_modifiable_lvalue; 7073 NeedType = true; 7074 break; 7075 case Expr::MLV_NotObjectType: 7076 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue; 7077 NeedType = true; 7078 break; 7079 case Expr::MLV_LValueCast: 7080 Diag = diag::err_typecheck_lvalue_casts_not_supported; 7081 break; 7082 case Expr::MLV_Valid: 7083 llvm_unreachable("did not take early return for MLV_Valid"); 7084 case Expr::MLV_InvalidExpression: 7085 case Expr::MLV_MemberFunction: 7086 case Expr::MLV_ClassTemporary: 7087 Diag = diag::err_typecheck_expression_not_modifiable_lvalue; 7088 break; 7089 case Expr::MLV_IncompleteType: 7090 case Expr::MLV_IncompleteVoidType: 7091 return S.RequireCompleteType(Loc, E->getType(), 7092 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue) 7093 << E->getSourceRange()); 7094 case Expr::MLV_DuplicateVectorComponents: 7095 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 7096 break; 7097 case Expr::MLV_NotBlockQualified: 7098 Diag = diag::err_block_decl_ref_not_modifiable_lvalue; 7099 break; 7100 case Expr::MLV_ReadonlyProperty: 7101 case Expr::MLV_NoSetterProperty: 7102 llvm_unreachable("readonly properties should be processed differently"); 7103 break; 7104 case Expr::MLV_InvalidMessageExpression: 7105 Diag = diag::error_readonly_message_assignment; 7106 break; 7107 case Expr::MLV_SubObjCPropertySetting: 7108 Diag = diag::error_no_subobject_property_setting; 7109 break; 7110 } 7111 7112 SourceRange Assign; 7113 if (Loc != OrigLoc) 7114 Assign = SourceRange(OrigLoc, OrigLoc); 7115 if (NeedType) 7116 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign; 7117 else 7118 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 7119 return true; 7120 } 7121 7122 7123 7124 // C99 6.5.16.1 7125 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 7126 SourceLocation Loc, 7127 QualType CompoundType) { 7128 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 7129 7130 // Verify that LHS is a modifiable lvalue, and emit error if not. 7131 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 7132 return QualType(); 7133 7134 QualType LHSType = LHSExpr->getType(); 7135 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 7136 CompoundType; 7137 AssignConvertType ConvTy; 7138 if (CompoundType.isNull()) { 7139 QualType LHSTy(LHSType); 7140 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 7141 if (RHS.isInvalid()) 7142 return QualType(); 7143 // Special case of NSObject attributes on c-style pointer types. 7144 if (ConvTy == IncompatiblePointer && 7145 ((Context.isObjCNSObjectType(LHSType) && 7146 RHSType->isObjCObjectPointerType()) || 7147 (Context.isObjCNSObjectType(RHSType) && 7148 LHSType->isObjCObjectPointerType()))) 7149 ConvTy = Compatible; 7150 7151 if (ConvTy == Compatible && 7152 getLangOptions().ObjCNonFragileABI && 7153 LHSType->isObjCObjectType()) 7154 Diag(Loc, diag::err_assignment_requires_nonfragile_object) 7155 << LHSType; 7156 7157 // If the RHS is a unary plus or minus, check to see if they = and + are 7158 // right next to each other. If so, the user may have typo'd "x =+ 4" 7159 // instead of "x += 4". 7160 Expr *RHSCheck = RHS.get(); 7161 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 7162 RHSCheck = ICE->getSubExpr(); 7163 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 7164 if ((UO->getOpcode() == UO_Plus || 7165 UO->getOpcode() == UO_Minus) && 7166 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 7167 // Only if the two operators are exactly adjacent. 7168 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 7169 // And there is a space or other character before the subexpr of the 7170 // unary +/-. We don't want to warn on "x=-1". 7171 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 7172 UO->getSubExpr()->getLocStart().isFileID()) { 7173 Diag(Loc, diag::warn_not_compound_assign) 7174 << (UO->getOpcode() == UO_Plus ? "+" : "-") 7175 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 7176 } 7177 } 7178 7179 if (ConvTy == Compatible) { 7180 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) 7181 checkRetainCycles(LHSExpr, RHS.get()); 7182 else if (getLangOptions().ObjCAutoRefCount) 7183 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 7184 } 7185 } else { 7186 // Compound assignment "x += y" 7187 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 7188 } 7189 7190 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 7191 RHS.get(), AA_Assigning)) 7192 return QualType(); 7193 7194 CheckForNullPointerDereference(*this, LHSExpr); 7195 7196 // C99 6.5.16p3: The type of an assignment expression is the type of the 7197 // left operand unless the left operand has qualified type, in which case 7198 // it is the unqualified version of the type of the left operand. 7199 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 7200 // is converted to the type of the assignment expression (above). 7201 // C++ 5.17p1: the type of the assignment expression is that of its left 7202 // operand. 7203 return (getLangOptions().CPlusPlus 7204 ? LHSType : LHSType.getUnqualifiedType()); 7205 } 7206 7207 // C99 6.5.17 7208 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 7209 SourceLocation Loc) { 7210 S.DiagnoseUnusedExprResult(LHS.get()); 7211 7212 LHS = S.CheckPlaceholderExpr(LHS.take()); 7213 RHS = S.CheckPlaceholderExpr(RHS.take()); 7214 if (LHS.isInvalid() || RHS.isInvalid()) 7215 return QualType(); 7216 7217 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 7218 // operands, but not unary promotions. 7219 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 7220 7221 // So we treat the LHS as a ignored value, and in C++ we allow the 7222 // containing site to determine what should be done with the RHS. 7223 LHS = S.IgnoredValueConversions(LHS.take()); 7224 if (LHS.isInvalid()) 7225 return QualType(); 7226 7227 if (!S.getLangOptions().CPlusPlus) { 7228 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take()); 7229 if (RHS.isInvalid()) 7230 return QualType(); 7231 if (!RHS.get()->getType()->isVoidType()) 7232 S.RequireCompleteType(Loc, RHS.get()->getType(), 7233 diag::err_incomplete_type); 7234 } 7235 7236 return RHS.get()->getType(); 7237 } 7238 7239 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 7240 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 7241 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 7242 ExprValueKind &VK, 7243 SourceLocation OpLoc, 7244 bool IsInc, bool IsPrefix) { 7245 if (Op->isTypeDependent()) 7246 return S.Context.DependentTy; 7247 7248 QualType ResType = Op->getType(); 7249 assert(!ResType.isNull() && "no type for increment/decrement expression"); 7250 7251 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) { 7252 // Decrement of bool is not allowed. 7253 if (!IsInc) { 7254 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 7255 return QualType(); 7256 } 7257 // Increment of bool sets it to true, but is deprecated. 7258 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); 7259 } else if (ResType->isRealType()) { 7260 // OK! 7261 } else if (ResType->isAnyPointerType()) { 7262 // C99 6.5.2.4p2, 6.5.6p2 7263 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 7264 return QualType(); 7265 7266 // Diagnose bad cases where we step over interface counts. 7267 else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op)) 7268 return QualType(); 7269 } else if (ResType->isAnyComplexType()) { 7270 // C99 does not support ++/-- on complex types, we allow as an extension. 7271 S.Diag(OpLoc, diag::ext_integer_increment_complex) 7272 << ResType << Op->getSourceRange(); 7273 } else if (ResType->isPlaceholderType()) { 7274 ExprResult PR = S.CheckPlaceholderExpr(Op); 7275 if (PR.isInvalid()) return QualType(); 7276 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc, 7277 IsInc, IsPrefix); 7278 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) { 7279 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 7280 } else { 7281 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 7282 << ResType << int(IsInc) << Op->getSourceRange(); 7283 return QualType(); 7284 } 7285 // At this point, we know we have a real, complex or pointer type. 7286 // Now make sure the operand is a modifiable lvalue. 7287 if (CheckForModifiableLvalue(Op, OpLoc, S)) 7288 return QualType(); 7289 // In C++, a prefix increment is the same type as the operand. Otherwise 7290 // (in C or with postfix), the increment is the unqualified type of the 7291 // operand. 7292 if (IsPrefix && S.getLangOptions().CPlusPlus) { 7293 VK = VK_LValue; 7294 return ResType; 7295 } else { 7296 VK = VK_RValue; 7297 return ResType.getUnqualifiedType(); 7298 } 7299 } 7300 7301 7302 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 7303 /// This routine allows us to typecheck complex/recursive expressions 7304 /// where the declaration is needed for type checking. We only need to 7305 /// handle cases when the expression references a function designator 7306 /// or is an lvalue. Here are some examples: 7307 /// - &(x) => x 7308 /// - &*****f => f for f a function designator. 7309 /// - &s.xx => s 7310 /// - &s.zz[1].yy -> s, if zz is an array 7311 /// - *(x + 1) -> x, if x is an array 7312 /// - &"123"[2] -> 0 7313 /// - & __real__ x -> x 7314 static ValueDecl *getPrimaryDecl(Expr *E) { 7315 switch (E->getStmtClass()) { 7316 case Stmt::DeclRefExprClass: 7317 return cast<DeclRefExpr>(E)->getDecl(); 7318 case Stmt::MemberExprClass: 7319 // If this is an arrow operator, the address is an offset from 7320 // the base's value, so the object the base refers to is 7321 // irrelevant. 7322 if (cast<MemberExpr>(E)->isArrow()) 7323 return 0; 7324 // Otherwise, the expression refers to a part of the base 7325 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 7326 case Stmt::ArraySubscriptExprClass: { 7327 // FIXME: This code shouldn't be necessary! We should catch the implicit 7328 // promotion of register arrays earlier. 7329 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 7330 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 7331 if (ICE->getSubExpr()->getType()->isArrayType()) 7332 return getPrimaryDecl(ICE->getSubExpr()); 7333 } 7334 return 0; 7335 } 7336 case Stmt::UnaryOperatorClass: { 7337 UnaryOperator *UO = cast<UnaryOperator>(E); 7338 7339 switch(UO->getOpcode()) { 7340 case UO_Real: 7341 case UO_Imag: 7342 case UO_Extension: 7343 return getPrimaryDecl(UO->getSubExpr()); 7344 default: 7345 return 0; 7346 } 7347 } 7348 case Stmt::ParenExprClass: 7349 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 7350 case Stmt::ImplicitCastExprClass: 7351 // If the result of an implicit cast is an l-value, we care about 7352 // the sub-expression; otherwise, the result here doesn't matter. 7353 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 7354 default: 7355 return 0; 7356 } 7357 } 7358 7359 namespace { 7360 enum { 7361 AO_Bit_Field = 0, 7362 AO_Vector_Element = 1, 7363 AO_Property_Expansion = 2, 7364 AO_Register_Variable = 3, 7365 AO_No_Error = 4 7366 }; 7367 } 7368 /// \brief Diagnose invalid operand for address of operations. 7369 /// 7370 /// \param Type The type of operand which cannot have its address taken. 7371 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 7372 Expr *E, unsigned Type) { 7373 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 7374 } 7375 7376 /// CheckAddressOfOperand - The operand of & must be either a function 7377 /// designator or an lvalue designating an object. If it is an lvalue, the 7378 /// object cannot be declared with storage class register or be a bit field. 7379 /// Note: The usual conversions are *not* applied to the operand of the & 7380 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 7381 /// In C++, the operand might be an overloaded function name, in which case 7382 /// we allow the '&' but retain the overloaded-function type. 7383 static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp, 7384 SourceLocation OpLoc) { 7385 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 7386 if (PTy->getKind() == BuiltinType::Overload) { 7387 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) { 7388 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 7389 << OrigOp.get()->getSourceRange(); 7390 return QualType(); 7391 } 7392 7393 return S.Context.OverloadTy; 7394 } 7395 7396 if (PTy->getKind() == BuiltinType::UnknownAny) 7397 return S.Context.UnknownAnyTy; 7398 7399 if (PTy->getKind() == BuiltinType::BoundMember) { 7400 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 7401 << OrigOp.get()->getSourceRange(); 7402 return QualType(); 7403 } 7404 7405 OrigOp = S.CheckPlaceholderExpr(OrigOp.take()); 7406 if (OrigOp.isInvalid()) return QualType(); 7407 } 7408 7409 if (OrigOp.get()->isTypeDependent()) 7410 return S.Context.DependentTy; 7411 7412 assert(!OrigOp.get()->getType()->isPlaceholderType()); 7413 7414 // Make sure to ignore parentheses in subsequent checks 7415 Expr *op = OrigOp.get()->IgnoreParens(); 7416 7417 if (S.getLangOptions().C99) { 7418 // Implement C99-only parts of addressof rules. 7419 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 7420 if (uOp->getOpcode() == UO_Deref) 7421 // Per C99 6.5.3.2, the address of a deref always returns a valid result 7422 // (assuming the deref expression is valid). 7423 return uOp->getSubExpr()->getType(); 7424 } 7425 // Technically, there should be a check for array subscript 7426 // expressions here, but the result of one is always an lvalue anyway. 7427 } 7428 ValueDecl *dcl = getPrimaryDecl(op); 7429 Expr::LValueClassification lval = op->ClassifyLValue(S.Context); 7430 unsigned AddressOfError = AO_No_Error; 7431 7432 if (lval == Expr::LV_ClassTemporary) { 7433 bool sfinae = S.isSFINAEContext(); 7434 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary 7435 : diag::ext_typecheck_addrof_class_temporary) 7436 << op->getType() << op->getSourceRange(); 7437 if (sfinae) 7438 return QualType(); 7439 } else if (isa<ObjCSelectorExpr>(op)) { 7440 return S.Context.getPointerType(op->getType()); 7441 } else if (lval == Expr::LV_MemberFunction) { 7442 // If it's an instance method, make a member pointer. 7443 // The expression must have exactly the form &A::foo. 7444 7445 // If the underlying expression isn't a decl ref, give up. 7446 if (!isa<DeclRefExpr>(op)) { 7447 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 7448 << OrigOp.get()->getSourceRange(); 7449 return QualType(); 7450 } 7451 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 7452 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 7453 7454 // The id-expression was parenthesized. 7455 if (OrigOp.get() != DRE) { 7456 S.Diag(OpLoc, diag::err_parens_pointer_member_function) 7457 << OrigOp.get()->getSourceRange(); 7458 7459 // The method was named without a qualifier. 7460 } else if (!DRE->getQualifier()) { 7461 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function) 7462 << op->getSourceRange(); 7463 } 7464 7465 return S.Context.getMemberPointerType(op->getType(), 7466 S.Context.getTypeDeclType(MD->getParent()).getTypePtr()); 7467 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 7468 // C99 6.5.3.2p1 7469 // The operand must be either an l-value or a function designator 7470 if (!op->getType()->isFunctionType()) { 7471 // Use a special diagnostic for loads from property references. 7472 if (isa<PseudoObjectExpr>(op)) { 7473 AddressOfError = AO_Property_Expansion; 7474 } else { 7475 // FIXME: emit more specific diag... 7476 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 7477 << op->getSourceRange(); 7478 return QualType(); 7479 } 7480 } 7481 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 7482 // The operand cannot be a bit-field 7483 AddressOfError = AO_Bit_Field; 7484 } else if (op->getObjectKind() == OK_VectorComponent) { 7485 // The operand cannot be an element of a vector 7486 AddressOfError = AO_Vector_Element; 7487 } else if (dcl) { // C99 6.5.3.2p1 7488 // We have an lvalue with a decl. Make sure the decl is not declared 7489 // with the register storage-class specifier. 7490 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 7491 // in C++ it is not error to take address of a register 7492 // variable (c++03 7.1.1P3) 7493 if (vd->getStorageClass() == SC_Register && 7494 !S.getLangOptions().CPlusPlus) { 7495 AddressOfError = AO_Register_Variable; 7496 } 7497 } else if (isa<FunctionTemplateDecl>(dcl)) { 7498 return S.Context.OverloadTy; 7499 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 7500 // Okay: we can take the address of a field. 7501 // Could be a pointer to member, though, if there is an explicit 7502 // scope qualifier for the class. 7503 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 7504 DeclContext *Ctx = dcl->getDeclContext(); 7505 if (Ctx && Ctx->isRecord()) { 7506 if (dcl->getType()->isReferenceType()) { 7507 S.Diag(OpLoc, 7508 diag::err_cannot_form_pointer_to_member_of_reference_type) 7509 << dcl->getDeclName() << dcl->getType(); 7510 return QualType(); 7511 } 7512 7513 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 7514 Ctx = Ctx->getParent(); 7515 return S.Context.getMemberPointerType(op->getType(), 7516 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 7517 } 7518 } 7519 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl)) 7520 llvm_unreachable("Unknown/unexpected decl type"); 7521 } 7522 7523 if (AddressOfError != AO_No_Error) { 7524 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError); 7525 return QualType(); 7526 } 7527 7528 if (lval == Expr::LV_IncompleteVoidType) { 7529 // Taking the address of a void variable is technically illegal, but we 7530 // allow it in cases which are otherwise valid. 7531 // Example: "extern void x; void* y = &x;". 7532 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 7533 } 7534 7535 // If the operand has type "type", the result has type "pointer to type". 7536 if (op->getType()->isObjCObjectType()) 7537 return S.Context.getObjCObjectPointerType(op->getType()); 7538 return S.Context.getPointerType(op->getType()); 7539 } 7540 7541 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 7542 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 7543 SourceLocation OpLoc) { 7544 if (Op->isTypeDependent()) 7545 return S.Context.DependentTy; 7546 7547 ExprResult ConvResult = S.UsualUnaryConversions(Op); 7548 if (ConvResult.isInvalid()) 7549 return QualType(); 7550 Op = ConvResult.take(); 7551 QualType OpTy = Op->getType(); 7552 QualType Result; 7553 7554 if (isa<CXXReinterpretCastExpr>(Op)) { 7555 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 7556 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 7557 Op->getSourceRange()); 7558 } 7559 7560 // Note that per both C89 and C99, indirection is always legal, even if OpTy 7561 // is an incomplete type or void. It would be possible to warn about 7562 // dereferencing a void pointer, but it's completely well-defined, and such a 7563 // warning is unlikely to catch any mistakes. 7564 if (const PointerType *PT = OpTy->getAs<PointerType>()) 7565 Result = PT->getPointeeType(); 7566 else if (const ObjCObjectPointerType *OPT = 7567 OpTy->getAs<ObjCObjectPointerType>()) 7568 Result = OPT->getPointeeType(); 7569 else { 7570 ExprResult PR = S.CheckPlaceholderExpr(Op); 7571 if (PR.isInvalid()) return QualType(); 7572 if (PR.take() != Op) 7573 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc); 7574 } 7575 7576 if (Result.isNull()) { 7577 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 7578 << OpTy << Op->getSourceRange(); 7579 return QualType(); 7580 } 7581 7582 // Dereferences are usually l-values... 7583 VK = VK_LValue; 7584 7585 // ...except that certain expressions are never l-values in C. 7586 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType()) 7587 VK = VK_RValue; 7588 7589 return Result; 7590 } 7591 7592 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode( 7593 tok::TokenKind Kind) { 7594 BinaryOperatorKind Opc; 7595 switch (Kind) { 7596 default: llvm_unreachable("Unknown binop!"); 7597 case tok::periodstar: Opc = BO_PtrMemD; break; 7598 case tok::arrowstar: Opc = BO_PtrMemI; break; 7599 case tok::star: Opc = BO_Mul; break; 7600 case tok::slash: Opc = BO_Div; break; 7601 case tok::percent: Opc = BO_Rem; break; 7602 case tok::plus: Opc = BO_Add; break; 7603 case tok::minus: Opc = BO_Sub; break; 7604 case tok::lessless: Opc = BO_Shl; break; 7605 case tok::greatergreater: Opc = BO_Shr; break; 7606 case tok::lessequal: Opc = BO_LE; break; 7607 case tok::less: Opc = BO_LT; break; 7608 case tok::greaterequal: Opc = BO_GE; break; 7609 case tok::greater: Opc = BO_GT; break; 7610 case tok::exclaimequal: Opc = BO_NE; break; 7611 case tok::equalequal: Opc = BO_EQ; break; 7612 case tok::amp: Opc = BO_And; break; 7613 case tok::caret: Opc = BO_Xor; break; 7614 case tok::pipe: Opc = BO_Or; break; 7615 case tok::ampamp: Opc = BO_LAnd; break; 7616 case tok::pipepipe: Opc = BO_LOr; break; 7617 case tok::equal: Opc = BO_Assign; break; 7618 case tok::starequal: Opc = BO_MulAssign; break; 7619 case tok::slashequal: Opc = BO_DivAssign; break; 7620 case tok::percentequal: Opc = BO_RemAssign; break; 7621 case tok::plusequal: Opc = BO_AddAssign; break; 7622 case tok::minusequal: Opc = BO_SubAssign; break; 7623 case tok::lesslessequal: Opc = BO_ShlAssign; break; 7624 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 7625 case tok::ampequal: Opc = BO_AndAssign; break; 7626 case tok::caretequal: Opc = BO_XorAssign; break; 7627 case tok::pipeequal: Opc = BO_OrAssign; break; 7628 case tok::comma: Opc = BO_Comma; break; 7629 } 7630 return Opc; 7631 } 7632 7633 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 7634 tok::TokenKind Kind) { 7635 UnaryOperatorKind Opc; 7636 switch (Kind) { 7637 default: llvm_unreachable("Unknown unary op!"); 7638 case tok::plusplus: Opc = UO_PreInc; break; 7639 case tok::minusminus: Opc = UO_PreDec; break; 7640 case tok::amp: Opc = UO_AddrOf; break; 7641 case tok::star: Opc = UO_Deref; break; 7642 case tok::plus: Opc = UO_Plus; break; 7643 case tok::minus: Opc = UO_Minus; break; 7644 case tok::tilde: Opc = UO_Not; break; 7645 case tok::exclaim: Opc = UO_LNot; break; 7646 case tok::kw___real: Opc = UO_Real; break; 7647 case tok::kw___imag: Opc = UO_Imag; break; 7648 case tok::kw___extension__: Opc = UO_Extension; break; 7649 } 7650 return Opc; 7651 } 7652 7653 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 7654 /// This warning is only emitted for builtin assignment operations. It is also 7655 /// suppressed in the event of macro expansions. 7656 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 7657 SourceLocation OpLoc) { 7658 if (!S.ActiveTemplateInstantiations.empty()) 7659 return; 7660 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 7661 return; 7662 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 7663 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 7664 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 7665 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 7666 if (!LHSDeclRef || !RHSDeclRef || 7667 LHSDeclRef->getLocation().isMacroID() || 7668 RHSDeclRef->getLocation().isMacroID()) 7669 return; 7670 const ValueDecl *LHSDecl = 7671 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 7672 const ValueDecl *RHSDecl = 7673 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 7674 if (LHSDecl != RHSDecl) 7675 return; 7676 if (LHSDecl->getType().isVolatileQualified()) 7677 return; 7678 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 7679 if (RefTy->getPointeeType().isVolatileQualified()) 7680 return; 7681 7682 S.Diag(OpLoc, diag::warn_self_assignment) 7683 << LHSDeclRef->getType() 7684 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 7685 } 7686 7687 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 7688 /// operator @p Opc at location @c TokLoc. This routine only supports 7689 /// built-in operations; ActOnBinOp handles overloaded operators. 7690 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 7691 BinaryOperatorKind Opc, 7692 Expr *LHSExpr, Expr *RHSExpr) { 7693 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 7694 QualType ResultTy; // Result type of the binary operator. 7695 // The following two variables are used for compound assignment operators 7696 QualType CompLHSTy; // Type of LHS after promotions for computation 7697 QualType CompResultTy; // Type of computation result 7698 ExprValueKind VK = VK_RValue; 7699 ExprObjectKind OK = OK_Ordinary; 7700 7701 switch (Opc) { 7702 case BO_Assign: 7703 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 7704 if (getLangOptions().CPlusPlus && 7705 LHS.get()->getObjectKind() != OK_ObjCProperty) { 7706 VK = LHS.get()->getValueKind(); 7707 OK = LHS.get()->getObjectKind(); 7708 } 7709 if (!ResultTy.isNull()) 7710 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 7711 break; 7712 case BO_PtrMemD: 7713 case BO_PtrMemI: 7714 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 7715 Opc == BO_PtrMemI); 7716 break; 7717 case BO_Mul: 7718 case BO_Div: 7719 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 7720 Opc == BO_Div); 7721 break; 7722 case BO_Rem: 7723 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 7724 break; 7725 case BO_Add: 7726 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc); 7727 break; 7728 case BO_Sub: 7729 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 7730 break; 7731 case BO_Shl: 7732 case BO_Shr: 7733 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 7734 break; 7735 case BO_LE: 7736 case BO_LT: 7737 case BO_GE: 7738 case BO_GT: 7739 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 7740 break; 7741 case BO_EQ: 7742 case BO_NE: 7743 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 7744 break; 7745 case BO_And: 7746 case BO_Xor: 7747 case BO_Or: 7748 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 7749 break; 7750 case BO_LAnd: 7751 case BO_LOr: 7752 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 7753 break; 7754 case BO_MulAssign: 7755 case BO_DivAssign: 7756 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 7757 Opc == BO_DivAssign); 7758 CompLHSTy = CompResultTy; 7759 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 7760 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 7761 break; 7762 case BO_RemAssign: 7763 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 7764 CompLHSTy = CompResultTy; 7765 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 7766 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 7767 break; 7768 case BO_AddAssign: 7769 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, &CompLHSTy); 7770 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 7771 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 7772 break; 7773 case BO_SubAssign: 7774 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 7775 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 7776 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 7777 break; 7778 case BO_ShlAssign: 7779 case BO_ShrAssign: 7780 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 7781 CompLHSTy = CompResultTy; 7782 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 7783 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 7784 break; 7785 case BO_AndAssign: 7786 case BO_XorAssign: 7787 case BO_OrAssign: 7788 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 7789 CompLHSTy = CompResultTy; 7790 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 7791 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 7792 break; 7793 case BO_Comma: 7794 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 7795 if (getLangOptions().CPlusPlus && !RHS.isInvalid()) { 7796 VK = RHS.get()->getValueKind(); 7797 OK = RHS.get()->getObjectKind(); 7798 } 7799 break; 7800 } 7801 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 7802 return ExprError(); 7803 7804 // Check for array bounds violations for both sides of the BinaryOperator 7805 CheckArrayAccess(LHS.get()); 7806 CheckArrayAccess(RHS.get()); 7807 7808 if (CompResultTy.isNull()) 7809 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc, 7810 ResultTy, VK, OK, OpLoc)); 7811 if (getLangOptions().CPlusPlus && LHS.get()->getObjectKind() != 7812 OK_ObjCProperty) { 7813 VK = VK_LValue; 7814 OK = LHS.get()->getObjectKind(); 7815 } 7816 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc, 7817 ResultTy, VK, OK, CompLHSTy, 7818 CompResultTy, OpLoc)); 7819 } 7820 7821 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 7822 /// operators are mixed in a way that suggests that the programmer forgot that 7823 /// comparison operators have higher precedence. The most typical example of 7824 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 7825 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 7826 SourceLocation OpLoc, Expr *LHSExpr, 7827 Expr *RHSExpr) { 7828 typedef BinaryOperator BinOp; 7829 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1), 7830 RHSopc = static_cast<BinOp::Opcode>(-1); 7831 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr)) 7832 LHSopc = BO->getOpcode(); 7833 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr)) 7834 RHSopc = BO->getOpcode(); 7835 7836 // Subs are not binary operators. 7837 if (LHSopc == -1 && RHSopc == -1) 7838 return; 7839 7840 // Bitwise operations are sometimes used as eager logical ops. 7841 // Don't diagnose this. 7842 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) && 7843 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc))) 7844 return; 7845 7846 bool isLeftComp = BinOp::isComparisonOp(LHSopc); 7847 bool isRightComp = BinOp::isComparisonOp(RHSopc); 7848 if (!isLeftComp && !isRightComp) return; 7849 7850 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 7851 OpLoc) 7852 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 7853 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc) 7854 : BinOp::getOpcodeStr(RHSopc); 7855 SourceRange ParensRange = isLeftComp ? 7856 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(), 7857 RHSExpr->getLocEnd()) 7858 : SourceRange(LHSExpr->getLocStart(), 7859 cast<BinOp>(RHSExpr)->getLHS()->getLocStart()); 7860 7861 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 7862 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr; 7863 SuggestParentheses(Self, OpLoc, 7864 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr, 7865 RHSExpr->getSourceRange()); 7866 SuggestParentheses(Self, OpLoc, 7867 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc), 7868 ParensRange); 7869 } 7870 7871 /// \brief It accepts a '&' expr that is inside a '|' one. 7872 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression 7873 /// in parentheses. 7874 static void 7875 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc, 7876 BinaryOperator *Bop) { 7877 assert(Bop->getOpcode() == BO_And); 7878 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or) 7879 << Bop->getSourceRange() << OpLoc; 7880 SuggestParentheses(Self, Bop->getOperatorLoc(), 7881 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence), 7882 Bop->getSourceRange()); 7883 } 7884 7885 /// \brief It accepts a '&&' expr that is inside a '||' one. 7886 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 7887 /// in parentheses. 7888 static void 7889 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 7890 BinaryOperator *Bop) { 7891 assert(Bop->getOpcode() == BO_LAnd); 7892 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 7893 << Bop->getSourceRange() << OpLoc; 7894 SuggestParentheses(Self, Bop->getOperatorLoc(), 7895 Self.PDiag(diag::note_logical_and_in_logical_or_silence), 7896 Bop->getSourceRange()); 7897 } 7898 7899 /// \brief Returns true if the given expression can be evaluated as a constant 7900 /// 'true'. 7901 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 7902 bool Res; 7903 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 7904 } 7905 7906 /// \brief Returns true if the given expression can be evaluated as a constant 7907 /// 'false'. 7908 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 7909 bool Res; 7910 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 7911 } 7912 7913 /// \brief Look for '&&' in the left hand of a '||' expr. 7914 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 7915 Expr *LHSExpr, Expr *RHSExpr) { 7916 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 7917 if (Bop->getOpcode() == BO_LAnd) { 7918 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 7919 if (EvaluatesAsFalse(S, RHSExpr)) 7920 return; 7921 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 7922 if (!EvaluatesAsTrue(S, Bop->getLHS())) 7923 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 7924 } else if (Bop->getOpcode() == BO_LOr) { 7925 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 7926 // If it's "a || b && 1 || c" we didn't warn earlier for 7927 // "a || b && 1", but warn now. 7928 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 7929 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 7930 } 7931 } 7932 } 7933 } 7934 7935 /// \brief Look for '&&' in the right hand of a '||' expr. 7936 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 7937 Expr *LHSExpr, Expr *RHSExpr) { 7938 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 7939 if (Bop->getOpcode() == BO_LAnd) { 7940 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 7941 if (EvaluatesAsFalse(S, LHSExpr)) 7942 return; 7943 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 7944 if (!EvaluatesAsTrue(S, Bop->getRHS())) 7945 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 7946 } 7947 } 7948 } 7949 7950 /// \brief Look for '&' in the left or right hand of a '|' expr. 7951 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc, 7952 Expr *OrArg) { 7953 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) { 7954 if (Bop->getOpcode() == BO_And) 7955 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop); 7956 } 7957 } 7958 7959 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 7960 /// precedence. 7961 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 7962 SourceLocation OpLoc, Expr *LHSExpr, 7963 Expr *RHSExpr){ 7964 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 7965 if (BinaryOperator::isBitwiseOp(Opc)) 7966 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 7967 7968 // Diagnose "arg1 & arg2 | arg3" 7969 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) { 7970 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr); 7971 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr); 7972 } 7973 7974 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 7975 // We don't warn for 'assert(a || b && "bad")' since this is safe. 7976 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 7977 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 7978 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 7979 } 7980 } 7981 7982 // Binary Operators. 'Tok' is the token for the operator. 7983 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 7984 tok::TokenKind Kind, 7985 Expr *LHSExpr, Expr *RHSExpr) { 7986 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 7987 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression"); 7988 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression"); 7989 7990 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 7991 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 7992 7993 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 7994 } 7995 7996 /// Build an overloaded binary operator expression in the given scope. 7997 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 7998 BinaryOperatorKind Opc, 7999 Expr *LHS, Expr *RHS) { 8000 // Find all of the overloaded operators visible from this 8001 // point. We perform both an operator-name lookup from the local 8002 // scope and an argument-dependent lookup based on the types of 8003 // the arguments. 8004 UnresolvedSet<16> Functions; 8005 OverloadedOperatorKind OverOp 8006 = BinaryOperator::getOverloadedOperator(Opc); 8007 if (Sc && OverOp != OO_None) 8008 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 8009 RHS->getType(), Functions); 8010 8011 // Build the (potentially-overloaded, potentially-dependent) 8012 // binary operation. 8013 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 8014 } 8015 8016 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 8017 BinaryOperatorKind Opc, 8018 Expr *LHSExpr, Expr *RHSExpr) { 8019 // We want to end up calling one of checkPseudoObjectAssignment 8020 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 8021 // both expressions are overloadable or either is type-dependent), 8022 // or CreateBuiltinBinOp (in any other case). We also want to get 8023 // any placeholder types out of the way. 8024 8025 // Handle pseudo-objects in the LHS. 8026 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 8027 // Assignments with a pseudo-object l-value need special analysis. 8028 if (pty->getKind() == BuiltinType::PseudoObject && 8029 BinaryOperator::isAssignmentOp(Opc)) 8030 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 8031 8032 // Don't resolve overloads if the other type is overloadable. 8033 if (pty->getKind() == BuiltinType::Overload) { 8034 // We can't actually test that if we still have a placeholder, 8035 // though. Fortunately, none of the exceptions we see in that 8036 // code below are valid when the LHS is an overload set. Note 8037 // that an overload set can be dependently-typed, but it never 8038 // instantiates to having an overloadable type. 8039 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 8040 if (resolvedRHS.isInvalid()) return ExprError(); 8041 RHSExpr = resolvedRHS.take(); 8042 8043 if (RHSExpr->isTypeDependent() || 8044 RHSExpr->getType()->isOverloadableType()) 8045 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 8046 } 8047 8048 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 8049 if (LHS.isInvalid()) return ExprError(); 8050 LHSExpr = LHS.take(); 8051 } 8052 8053 // Handle pseudo-objects in the RHS. 8054 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 8055 // An overload in the RHS can potentially be resolved by the type 8056 // being assigned to. 8057 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 8058 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 8059 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 8060 8061 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 8062 } 8063 8064 // Don't resolve overloads if the other type is overloadable. 8065 if (pty->getKind() == BuiltinType::Overload && 8066 LHSExpr->getType()->isOverloadableType()) 8067 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 8068 8069 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 8070 if (!resolvedRHS.isUsable()) return ExprError(); 8071 RHSExpr = resolvedRHS.take(); 8072 } 8073 8074 if (getLangOptions().CPlusPlus) { 8075 // If either expression is type-dependent, always build an 8076 // overloaded op. 8077 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 8078 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 8079 8080 // Otherwise, build an overloaded op if either expression has an 8081 // overloadable type. 8082 if (LHSExpr->getType()->isOverloadableType() || 8083 RHSExpr->getType()->isOverloadableType()) 8084 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 8085 } 8086 8087 // Build a built-in binary operation. 8088 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 8089 } 8090 8091 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 8092 UnaryOperatorKind Opc, 8093 Expr *InputExpr) { 8094 ExprResult Input = Owned(InputExpr); 8095 ExprValueKind VK = VK_RValue; 8096 ExprObjectKind OK = OK_Ordinary; 8097 QualType resultType; 8098 switch (Opc) { 8099 case UO_PreInc: 8100 case UO_PreDec: 8101 case UO_PostInc: 8102 case UO_PostDec: 8103 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc, 8104 Opc == UO_PreInc || 8105 Opc == UO_PostInc, 8106 Opc == UO_PreInc || 8107 Opc == UO_PreDec); 8108 break; 8109 case UO_AddrOf: 8110 resultType = CheckAddressOfOperand(*this, Input, OpLoc); 8111 break; 8112 case UO_Deref: { 8113 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 8114 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 8115 break; 8116 } 8117 case UO_Plus: 8118 case UO_Minus: 8119 Input = UsualUnaryConversions(Input.take()); 8120 if (Input.isInvalid()) return ExprError(); 8121 resultType = Input.get()->getType(); 8122 if (resultType->isDependentType()) 8123 break; 8124 if (resultType->isArithmeticType() || // C99 6.5.3.3p1 8125 resultType->isVectorType()) 8126 break; 8127 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7 8128 resultType->isEnumeralType()) 8129 break; 8130 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6 8131 Opc == UO_Plus && 8132 resultType->isPointerType()) 8133 break; 8134 8135 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 8136 << resultType << Input.get()->getSourceRange()); 8137 8138 case UO_Not: // bitwise complement 8139 Input = UsualUnaryConversions(Input.take()); 8140 if (Input.isInvalid()) return ExprError(); 8141 resultType = Input.get()->getType(); 8142 if (resultType->isDependentType()) 8143 break; 8144 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 8145 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 8146 // C99 does not support '~' for complex conjugation. 8147 Diag(OpLoc, diag::ext_integer_complement_complex) 8148 << resultType << Input.get()->getSourceRange(); 8149 else if (resultType->hasIntegerRepresentation()) 8150 break; 8151 else { 8152 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 8153 << resultType << Input.get()->getSourceRange()); 8154 } 8155 break; 8156 8157 case UO_LNot: // logical negation 8158 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 8159 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 8160 if (Input.isInvalid()) return ExprError(); 8161 resultType = Input.get()->getType(); 8162 8163 // Though we still have to promote half FP to float... 8164 if (resultType->isHalfType()) { 8165 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take(); 8166 resultType = Context.FloatTy; 8167 } 8168 8169 if (resultType->isDependentType()) 8170 break; 8171 if (resultType->isScalarType()) { 8172 // C99 6.5.3.3p1: ok, fallthrough; 8173 if (Context.getLangOptions().CPlusPlus) { 8174 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 8175 // operand contextually converted to bool. 8176 Input = ImpCastExprToType(Input.take(), Context.BoolTy, 8177 ScalarTypeToBooleanCastKind(resultType)); 8178 } 8179 } else { 8180 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 8181 << resultType << Input.get()->getSourceRange()); 8182 } 8183 8184 // LNot always has type int. C99 6.5.3.3p5. 8185 // In C++, it's bool. C++ 5.3.1p8 8186 resultType = Context.getLogicalOperationType(); 8187 break; 8188 case UO_Real: 8189 case UO_Imag: 8190 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 8191 // _Real and _Imag map ordinary l-values into ordinary l-values. 8192 if (Input.isInvalid()) return ExprError(); 8193 if (Input.get()->getValueKind() != VK_RValue && 8194 Input.get()->getObjectKind() == OK_Ordinary) 8195 VK = Input.get()->getValueKind(); 8196 break; 8197 case UO_Extension: 8198 resultType = Input.get()->getType(); 8199 VK = Input.get()->getValueKind(); 8200 OK = Input.get()->getObjectKind(); 8201 break; 8202 } 8203 if (resultType.isNull() || Input.isInvalid()) 8204 return ExprError(); 8205 8206 // Check for array bounds violations in the operand of the UnaryOperator, 8207 // except for the '*' and '&' operators that have to be handled specially 8208 // by CheckArrayAccess (as there are special cases like &array[arraysize] 8209 // that are explicitly defined as valid by the standard). 8210 if (Opc != UO_AddrOf && Opc != UO_Deref) 8211 CheckArrayAccess(Input.get()); 8212 8213 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType, 8214 VK, OK, OpLoc)); 8215 } 8216 8217 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 8218 UnaryOperatorKind Opc, Expr *Input) { 8219 // First things first: handle placeholders so that the 8220 // overloaded-operator check considers the right type. 8221 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 8222 // Increment and decrement of pseudo-object references. 8223 if (pty->getKind() == BuiltinType::PseudoObject && 8224 UnaryOperator::isIncrementDecrementOp(Opc)) 8225 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 8226 8227 // extension is always a builtin operator. 8228 if (Opc == UO_Extension) 8229 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 8230 8231 // & gets special logic for several kinds of placeholder. 8232 // The builtin code knows what to do. 8233 if (Opc == UO_AddrOf && 8234 (pty->getKind() == BuiltinType::Overload || 8235 pty->getKind() == BuiltinType::UnknownAny || 8236 pty->getKind() == BuiltinType::BoundMember)) 8237 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 8238 8239 // Anything else needs to be handled now. 8240 ExprResult Result = CheckPlaceholderExpr(Input); 8241 if (Result.isInvalid()) return ExprError(); 8242 Input = Result.take(); 8243 } 8244 8245 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() && 8246 UnaryOperator::getOverloadedOperator(Opc) != OO_None) { 8247 // Find all of the overloaded operators visible from this 8248 // point. We perform both an operator-name lookup from the local 8249 // scope and an argument-dependent lookup based on the types of 8250 // the arguments. 8251 UnresolvedSet<16> Functions; 8252 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 8253 if (S && OverOp != OO_None) 8254 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 8255 Functions); 8256 8257 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 8258 } 8259 8260 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 8261 } 8262 8263 // Unary Operators. 'Tok' is the token for the operator. 8264 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 8265 tok::TokenKind Op, Expr *Input) { 8266 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 8267 } 8268 8269 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 8270 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 8271 LabelDecl *TheDecl) { 8272 TheDecl->setUsed(); 8273 // Create the AST node. The address of a label always has type 'void*'. 8274 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 8275 Context.getPointerType(Context.VoidTy))); 8276 } 8277 8278 /// Given the last statement in a statement-expression, check whether 8279 /// the result is a producing expression (like a call to an 8280 /// ns_returns_retained function) and, if so, rebuild it to hoist the 8281 /// release out of the full-expression. Otherwise, return null. 8282 /// Cannot fail. 8283 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 8284 // Should always be wrapped with one of these. 8285 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 8286 if (!cleanups) return 0; 8287 8288 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 8289 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 8290 return 0; 8291 8292 // Splice out the cast. This shouldn't modify any interesting 8293 // features of the statement. 8294 Expr *producer = cast->getSubExpr(); 8295 assert(producer->getType() == cast->getType()); 8296 assert(producer->getValueKind() == cast->getValueKind()); 8297 cleanups->setSubExpr(producer); 8298 return cleanups; 8299 } 8300 8301 ExprResult 8302 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 8303 SourceLocation RPLoc) { // "({..})" 8304 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 8305 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 8306 8307 bool isFileScope 8308 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0); 8309 if (isFileScope) 8310 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope)); 8311 8312 // FIXME: there are a variety of strange constraints to enforce here, for 8313 // example, it is not possible to goto into a stmt expression apparently. 8314 // More semantic analysis is needed. 8315 8316 // If there are sub stmts in the compound stmt, take the type of the last one 8317 // as the type of the stmtexpr. 8318 QualType Ty = Context.VoidTy; 8319 bool StmtExprMayBindToTemp = false; 8320 if (!Compound->body_empty()) { 8321 Stmt *LastStmt = Compound->body_back(); 8322 LabelStmt *LastLabelStmt = 0; 8323 // If LastStmt is a label, skip down through into the body. 8324 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 8325 LastLabelStmt = Label; 8326 LastStmt = Label->getSubStmt(); 8327 } 8328 8329 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 8330 // Do function/array conversion on the last expression, but not 8331 // lvalue-to-rvalue. However, initialize an unqualified type. 8332 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 8333 if (LastExpr.isInvalid()) 8334 return ExprError(); 8335 Ty = LastExpr.get()->getType().getUnqualifiedType(); 8336 8337 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 8338 // In ARC, if the final expression ends in a consume, splice 8339 // the consume out and bind it later. In the alternate case 8340 // (when dealing with a retainable type), the result 8341 // initialization will create a produce. In both cases the 8342 // result will be +1, and we'll need to balance that out with 8343 // a bind. 8344 if (Expr *rebuiltLastStmt 8345 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 8346 LastExpr = rebuiltLastStmt; 8347 } else { 8348 LastExpr = PerformCopyInitialization( 8349 InitializedEntity::InitializeResult(LPLoc, 8350 Ty, 8351 false), 8352 SourceLocation(), 8353 LastExpr); 8354 } 8355 8356 if (LastExpr.isInvalid()) 8357 return ExprError(); 8358 if (LastExpr.get() != 0) { 8359 if (!LastLabelStmt) 8360 Compound->setLastStmt(LastExpr.take()); 8361 else 8362 LastLabelStmt->setSubStmt(LastExpr.take()); 8363 StmtExprMayBindToTemp = true; 8364 } 8365 } 8366 } 8367 } 8368 8369 // FIXME: Check that expression type is complete/non-abstract; statement 8370 // expressions are not lvalues. 8371 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 8372 if (StmtExprMayBindToTemp) 8373 return MaybeBindToTemporary(ResStmtExpr); 8374 return Owned(ResStmtExpr); 8375 } 8376 8377 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 8378 TypeSourceInfo *TInfo, 8379 OffsetOfComponent *CompPtr, 8380 unsigned NumComponents, 8381 SourceLocation RParenLoc) { 8382 QualType ArgTy = TInfo->getType(); 8383 bool Dependent = ArgTy->isDependentType(); 8384 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 8385 8386 // We must have at least one component that refers to the type, and the first 8387 // one is known to be a field designator. Verify that the ArgTy represents 8388 // a struct/union/class. 8389 if (!Dependent && !ArgTy->isRecordType()) 8390 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 8391 << ArgTy << TypeRange); 8392 8393 // Type must be complete per C99 7.17p3 because a declaring a variable 8394 // with an incomplete type would be ill-formed. 8395 if (!Dependent 8396 && RequireCompleteType(BuiltinLoc, ArgTy, 8397 PDiag(diag::err_offsetof_incomplete_type) 8398 << TypeRange)) 8399 return ExprError(); 8400 8401 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 8402 // GCC extension, diagnose them. 8403 // FIXME: This diagnostic isn't actually visible because the location is in 8404 // a system header! 8405 if (NumComponents != 1) 8406 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 8407 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); 8408 8409 bool DidWarnAboutNonPOD = false; 8410 QualType CurrentType = ArgTy; 8411 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; 8412 SmallVector<OffsetOfNode, 4> Comps; 8413 SmallVector<Expr*, 4> Exprs; 8414 for (unsigned i = 0; i != NumComponents; ++i) { 8415 const OffsetOfComponent &OC = CompPtr[i]; 8416 if (OC.isBrackets) { 8417 // Offset of an array sub-field. TODO: Should we allow vector elements? 8418 if (!CurrentType->isDependentType()) { 8419 const ArrayType *AT = Context.getAsArrayType(CurrentType); 8420 if(!AT) 8421 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 8422 << CurrentType); 8423 CurrentType = AT->getElementType(); 8424 } else 8425 CurrentType = Context.DependentTy; 8426 8427 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 8428 if (IdxRval.isInvalid()) 8429 return ExprError(); 8430 Expr *Idx = IdxRval.take(); 8431 8432 // The expression must be an integral expression. 8433 // FIXME: An integral constant expression? 8434 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 8435 !Idx->getType()->isIntegerType()) 8436 return ExprError(Diag(Idx->getLocStart(), 8437 diag::err_typecheck_subscript_not_integer) 8438 << Idx->getSourceRange()); 8439 8440 // Record this array index. 8441 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 8442 Exprs.push_back(Idx); 8443 continue; 8444 } 8445 8446 // Offset of a field. 8447 if (CurrentType->isDependentType()) { 8448 // We have the offset of a field, but we can't look into the dependent 8449 // type. Just record the identifier of the field. 8450 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 8451 CurrentType = Context.DependentTy; 8452 continue; 8453 } 8454 8455 // We need to have a complete type to look into. 8456 if (RequireCompleteType(OC.LocStart, CurrentType, 8457 diag::err_offsetof_incomplete_type)) 8458 return ExprError(); 8459 8460 // Look for the designated field. 8461 const RecordType *RC = CurrentType->getAs<RecordType>(); 8462 if (!RC) 8463 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 8464 << CurrentType); 8465 RecordDecl *RD = RC->getDecl(); 8466 8467 // C++ [lib.support.types]p5: 8468 // The macro offsetof accepts a restricted set of type arguments in this 8469 // International Standard. type shall be a POD structure or a POD union 8470 // (clause 9). 8471 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 8472 if (!CRD->isPOD() && !DidWarnAboutNonPOD && 8473 DiagRuntimeBehavior(BuiltinLoc, 0, 8474 PDiag(diag::warn_offsetof_non_pod_type) 8475 << SourceRange(CompPtr[0].LocStart, OC.LocEnd) 8476 << CurrentType)) 8477 DidWarnAboutNonPOD = true; 8478 } 8479 8480 // Look for the field. 8481 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 8482 LookupQualifiedName(R, RD); 8483 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 8484 IndirectFieldDecl *IndirectMemberDecl = 0; 8485 if (!MemberDecl) { 8486 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 8487 MemberDecl = IndirectMemberDecl->getAnonField(); 8488 } 8489 8490 if (!MemberDecl) 8491 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 8492 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 8493 OC.LocEnd)); 8494 8495 // C99 7.17p3: 8496 // (If the specified member is a bit-field, the behavior is undefined.) 8497 // 8498 // We diagnose this as an error. 8499 if (MemberDecl->isBitField()) { 8500 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 8501 << MemberDecl->getDeclName() 8502 << SourceRange(BuiltinLoc, RParenLoc); 8503 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 8504 return ExprError(); 8505 } 8506 8507 RecordDecl *Parent = MemberDecl->getParent(); 8508 if (IndirectMemberDecl) 8509 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 8510 8511 // If the member was found in a base class, introduce OffsetOfNodes for 8512 // the base class indirections. 8513 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 8514 /*DetectVirtual=*/false); 8515 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) { 8516 CXXBasePath &Path = Paths.front(); 8517 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end(); 8518 B != BEnd; ++B) 8519 Comps.push_back(OffsetOfNode(B->Base)); 8520 } 8521 8522 if (IndirectMemberDecl) { 8523 for (IndirectFieldDecl::chain_iterator FI = 8524 IndirectMemberDecl->chain_begin(), 8525 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) { 8526 assert(isa<FieldDecl>(*FI)); 8527 Comps.push_back(OffsetOfNode(OC.LocStart, 8528 cast<FieldDecl>(*FI), OC.LocEnd)); 8529 } 8530 } else 8531 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 8532 8533 CurrentType = MemberDecl->getType().getNonReferenceType(); 8534 } 8535 8536 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, 8537 TInfo, Comps.data(), Comps.size(), 8538 Exprs.data(), Exprs.size(), RParenLoc)); 8539 } 8540 8541 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 8542 SourceLocation BuiltinLoc, 8543 SourceLocation TypeLoc, 8544 ParsedType ParsedArgTy, 8545 OffsetOfComponent *CompPtr, 8546 unsigned NumComponents, 8547 SourceLocation RParenLoc) { 8548 8549 TypeSourceInfo *ArgTInfo; 8550 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 8551 if (ArgTy.isNull()) 8552 return ExprError(); 8553 8554 if (!ArgTInfo) 8555 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 8556 8557 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents, 8558 RParenLoc); 8559 } 8560 8561 8562 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 8563 Expr *CondExpr, 8564 Expr *LHSExpr, Expr *RHSExpr, 8565 SourceLocation RPLoc) { 8566 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 8567 8568 ExprValueKind VK = VK_RValue; 8569 ExprObjectKind OK = OK_Ordinary; 8570 QualType resType; 8571 bool ValueDependent = false; 8572 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 8573 resType = Context.DependentTy; 8574 ValueDependent = true; 8575 } else { 8576 // The conditional expression is required to be a constant expression. 8577 llvm::APSInt condEval(32); 8578 SourceLocation ExpLoc; 8579 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc)) 8580 return ExprError(Diag(ExpLoc, 8581 diag::err_typecheck_choose_expr_requires_constant) 8582 << CondExpr->getSourceRange()); 8583 8584 // If the condition is > zero, then the AST type is the same as the LSHExpr. 8585 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr; 8586 8587 resType = ActiveExpr->getType(); 8588 ValueDependent = ActiveExpr->isValueDependent(); 8589 VK = ActiveExpr->getValueKind(); 8590 OK = ActiveExpr->getObjectKind(); 8591 } 8592 8593 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 8594 resType, VK, OK, RPLoc, 8595 resType->isDependentType(), 8596 ValueDependent)); 8597 } 8598 8599 //===----------------------------------------------------------------------===// 8600 // Clang Extensions. 8601 //===----------------------------------------------------------------------===// 8602 8603 /// ActOnBlockStart - This callback is invoked when a block literal is started. 8604 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 8605 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 8606 PushBlockScope(CurScope, Block); 8607 CurContext->addDecl(Block); 8608 if (CurScope) 8609 PushDeclContext(CurScope, Block); 8610 else 8611 CurContext = Block; 8612 } 8613 8614 void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) { 8615 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!"); 8616 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 8617 BlockScopeInfo *CurBlock = getCurBlock(); 8618 8619 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 8620 QualType T = Sig->getType(); 8621 8622 // GetTypeForDeclarator always produces a function type for a block 8623 // literal signature. Furthermore, it is always a FunctionProtoType 8624 // unless the function was written with a typedef. 8625 assert(T->isFunctionType() && 8626 "GetTypeForDeclarator made a non-function block signature"); 8627 8628 // Look for an explicit signature in that function type. 8629 FunctionProtoTypeLoc ExplicitSignature; 8630 8631 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 8632 if (isa<FunctionProtoTypeLoc>(tmp)) { 8633 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp); 8634 8635 // Check whether that explicit signature was synthesized by 8636 // GetTypeForDeclarator. If so, don't save that as part of the 8637 // written signature. 8638 if (ExplicitSignature.getLocalRangeBegin() == 8639 ExplicitSignature.getLocalRangeEnd()) { 8640 // This would be much cheaper if we stored TypeLocs instead of 8641 // TypeSourceInfos. 8642 TypeLoc Result = ExplicitSignature.getResultLoc(); 8643 unsigned Size = Result.getFullDataSize(); 8644 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 8645 Sig->getTypeLoc().initializeFullCopy(Result, Size); 8646 8647 ExplicitSignature = FunctionProtoTypeLoc(); 8648 } 8649 } 8650 8651 CurBlock->TheDecl->setSignatureAsWritten(Sig); 8652 CurBlock->FunctionType = T; 8653 8654 const FunctionType *Fn = T->getAs<FunctionType>(); 8655 QualType RetTy = Fn->getResultType(); 8656 bool isVariadic = 8657 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 8658 8659 CurBlock->TheDecl->setIsVariadic(isVariadic); 8660 8661 // Don't allow returning a objc interface by value. 8662 if (RetTy->isObjCObjectType()) { 8663 Diag(ParamInfo.getSourceRange().getBegin(), 8664 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy; 8665 return; 8666 } 8667 8668 // Context.DependentTy is used as a placeholder for a missing block 8669 // return type. TODO: what should we do with declarators like: 8670 // ^ * { ... } 8671 // If the answer is "apply template argument deduction".... 8672 if (RetTy != Context.DependentTy) 8673 CurBlock->ReturnType = RetTy; 8674 8675 // Push block parameters from the declarator if we had them. 8676 SmallVector<ParmVarDecl*, 8> Params; 8677 if (ExplicitSignature) { 8678 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) { 8679 ParmVarDecl *Param = ExplicitSignature.getArg(I); 8680 if (Param->getIdentifier() == 0 && 8681 !Param->isImplicit() && 8682 !Param->isInvalidDecl() && 8683 !getLangOptions().CPlusPlus) 8684 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 8685 Params.push_back(Param); 8686 } 8687 8688 // Fake up parameter variables if we have a typedef, like 8689 // ^ fntype { ... } 8690 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 8691 for (FunctionProtoType::arg_type_iterator 8692 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) { 8693 ParmVarDecl *Param = 8694 BuildParmVarDeclForTypedef(CurBlock->TheDecl, 8695 ParamInfo.getSourceRange().getBegin(), 8696 *I); 8697 Params.push_back(Param); 8698 } 8699 } 8700 8701 // Set the parameters on the block decl. 8702 if (!Params.empty()) { 8703 CurBlock->TheDecl->setParams(Params); 8704 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(), 8705 CurBlock->TheDecl->param_end(), 8706 /*CheckParameterNames=*/false); 8707 } 8708 8709 // Finally we can process decl attributes. 8710 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 8711 8712 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) { 8713 Diag(ParamInfo.getAttributes()->getLoc(), 8714 diag::warn_attribute_sentinel_not_variadic) << 1; 8715 // FIXME: remove the attribute. 8716 } 8717 8718 // Put the parameter variables in scope. We can bail out immediately 8719 // if we don't have any. 8720 if (Params.empty()) 8721 return; 8722 8723 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(), 8724 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) { 8725 (*AI)->setOwningFunction(CurBlock->TheDecl); 8726 8727 // If this has an identifier, add it to the scope stack. 8728 if ((*AI)->getIdentifier()) { 8729 CheckShadow(CurBlock->TheScope, *AI); 8730 8731 PushOnScopeChains(*AI, CurBlock->TheScope); 8732 } 8733 } 8734 } 8735 8736 /// ActOnBlockError - If there is an error parsing a block, this callback 8737 /// is invoked to pop the information about the block from the action impl. 8738 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 8739 // Pop off CurBlock, handle nested blocks. 8740 PopDeclContext(); 8741 PopFunctionOrBlockScope(); 8742 } 8743 8744 /// ActOnBlockStmtExpr - This is called when the body of a block statement 8745 /// literal was successfully completed. ^(int x){...} 8746 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 8747 Stmt *Body, Scope *CurScope) { 8748 // If blocks are disabled, emit an error. 8749 if (!LangOpts.Blocks) 8750 Diag(CaretLoc, diag::err_blocks_disable); 8751 8752 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 8753 8754 PopDeclContext(); 8755 8756 QualType RetTy = Context.VoidTy; 8757 if (!BSI->ReturnType.isNull()) 8758 RetTy = BSI->ReturnType; 8759 8760 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>(); 8761 QualType BlockTy; 8762 8763 // Set the captured variables on the block. 8764 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(), 8765 BSI->CapturesCXXThis); 8766 8767 // If the user wrote a function type in some form, try to use that. 8768 if (!BSI->FunctionType.isNull()) { 8769 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 8770 8771 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 8772 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 8773 8774 // Turn protoless block types into nullary block types. 8775 if (isa<FunctionNoProtoType>(FTy)) { 8776 FunctionProtoType::ExtProtoInfo EPI; 8777 EPI.ExtInfo = Ext; 8778 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI); 8779 8780 // Otherwise, if we don't need to change anything about the function type, 8781 // preserve its sugar structure. 8782 } else if (FTy->getResultType() == RetTy && 8783 (!NoReturn || FTy->getNoReturnAttr())) { 8784 BlockTy = BSI->FunctionType; 8785 8786 // Otherwise, make the minimal modifications to the function type. 8787 } else { 8788 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 8789 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8790 EPI.TypeQuals = 0; // FIXME: silently? 8791 EPI.ExtInfo = Ext; 8792 BlockTy = Context.getFunctionType(RetTy, 8793 FPT->arg_type_begin(), 8794 FPT->getNumArgs(), 8795 EPI); 8796 } 8797 8798 // If we don't have a function type, just build one from nothing. 8799 } else { 8800 FunctionProtoType::ExtProtoInfo EPI; 8801 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 8802 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI); 8803 } 8804 8805 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(), 8806 BSI->TheDecl->param_end()); 8807 BlockTy = Context.getBlockPointerType(BlockTy); 8808 8809 // If needed, diagnose invalid gotos and switches in the block. 8810 if (getCurFunction()->NeedsScopeChecking() && 8811 !hasAnyUnrecoverableErrorsInThisFunction()) 8812 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 8813 8814 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 8815 8816 for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(), 8817 ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) { 8818 const VarDecl *variable = ci->getVariable(); 8819 QualType T = variable->getType(); 8820 QualType::DestructionKind destructKind = T.isDestructedType(); 8821 if (destructKind != QualType::DK_none) 8822 getCurFunction()->setHasBranchProtectedScope(); 8823 } 8824 8825 computeNRVO(Body, getCurBlock()); 8826 8827 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 8828 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy(); 8829 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result); 8830 8831 return Owned(Result); 8832 } 8833 8834 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 8835 Expr *E, ParsedType Ty, 8836 SourceLocation RPLoc) { 8837 TypeSourceInfo *TInfo; 8838 GetTypeFromParser(Ty, &TInfo); 8839 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 8840 } 8841 8842 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 8843 Expr *E, TypeSourceInfo *TInfo, 8844 SourceLocation RPLoc) { 8845 Expr *OrigExpr = E; 8846 8847 // Get the va_list type 8848 QualType VaListType = Context.getBuiltinVaListType(); 8849 if (VaListType->isArrayType()) { 8850 // Deal with implicit array decay; for example, on x86-64, 8851 // va_list is an array, but it's supposed to decay to 8852 // a pointer for va_arg. 8853 VaListType = Context.getArrayDecayedType(VaListType); 8854 // Make sure the input expression also decays appropriately. 8855 ExprResult Result = UsualUnaryConversions(E); 8856 if (Result.isInvalid()) 8857 return ExprError(); 8858 E = Result.take(); 8859 } else { 8860 // Otherwise, the va_list argument must be an l-value because 8861 // it is modified by va_arg. 8862 if (!E->isTypeDependent() && 8863 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 8864 return ExprError(); 8865 } 8866 8867 if (!E->isTypeDependent() && 8868 !Context.hasSameType(VaListType, E->getType())) { 8869 return ExprError(Diag(E->getLocStart(), 8870 diag::err_first_argument_to_va_arg_not_of_type_va_list) 8871 << OrigExpr->getType() << E->getSourceRange()); 8872 } 8873 8874 if (!TInfo->getType()->isDependentType()) { 8875 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 8876 PDiag(diag::err_second_parameter_to_va_arg_incomplete) 8877 << TInfo->getTypeLoc().getSourceRange())) 8878 return ExprError(); 8879 8880 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 8881 TInfo->getType(), 8882 PDiag(diag::err_second_parameter_to_va_arg_abstract) 8883 << TInfo->getTypeLoc().getSourceRange())) 8884 return ExprError(); 8885 8886 if (!TInfo->getType().isPODType(Context)) { 8887 Diag(TInfo->getTypeLoc().getBeginLoc(), 8888 TInfo->getType()->isObjCLifetimeType() 8889 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 8890 : diag::warn_second_parameter_to_va_arg_not_pod) 8891 << TInfo->getType() 8892 << TInfo->getTypeLoc().getSourceRange(); 8893 } 8894 8895 // Check for va_arg where arguments of the given type will be promoted 8896 // (i.e. this va_arg is guaranteed to have undefined behavior). 8897 QualType PromoteType; 8898 if (TInfo->getType()->isPromotableIntegerType()) { 8899 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 8900 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 8901 PromoteType = QualType(); 8902 } 8903 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 8904 PromoteType = Context.DoubleTy; 8905 if (!PromoteType.isNull()) 8906 Diag(TInfo->getTypeLoc().getBeginLoc(), 8907 diag::warn_second_parameter_to_va_arg_never_compatible) 8908 << TInfo->getType() 8909 << PromoteType 8910 << TInfo->getTypeLoc().getSourceRange(); 8911 } 8912 8913 QualType T = TInfo->getType().getNonLValueExprType(Context); 8914 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T)); 8915 } 8916 8917 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 8918 // The type of __null will be int or long, depending on the size of 8919 // pointers on the target. 8920 QualType Ty; 8921 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 8922 if (pw == Context.getTargetInfo().getIntWidth()) 8923 Ty = Context.IntTy; 8924 else if (pw == Context.getTargetInfo().getLongWidth()) 8925 Ty = Context.LongTy; 8926 else if (pw == Context.getTargetInfo().getLongLongWidth()) 8927 Ty = Context.LongLongTy; 8928 else { 8929 llvm_unreachable("I don't know size of pointer!"); 8930 } 8931 8932 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc)); 8933 } 8934 8935 static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType, 8936 Expr *SrcExpr, FixItHint &Hint) { 8937 if (!SemaRef.getLangOptions().ObjC1) 8938 return; 8939 8940 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 8941 if (!PT) 8942 return; 8943 8944 // Check if the destination is of type 'id'. 8945 if (!PT->isObjCIdType()) { 8946 // Check if the destination is the 'NSString' interface. 8947 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 8948 if (!ID || !ID->getIdentifier()->isStr("NSString")) 8949 return; 8950 } 8951 8952 // Ignore any parens, implicit casts (should only be 8953 // array-to-pointer decays), and not-so-opaque values. The last is 8954 // important for making this trigger for property assignments. 8955 SrcExpr = SrcExpr->IgnoreParenImpCasts(); 8956 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 8957 if (OV->getSourceExpr()) 8958 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 8959 8960 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 8961 if (!SL || !SL->isAscii()) 8962 return; 8963 8964 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@"); 8965 } 8966 8967 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 8968 SourceLocation Loc, 8969 QualType DstType, QualType SrcType, 8970 Expr *SrcExpr, AssignmentAction Action, 8971 bool *Complained) { 8972 if (Complained) 8973 *Complained = false; 8974 8975 // Decode the result (notice that AST's are still created for extensions). 8976 bool CheckInferredResultType = false; 8977 bool isInvalid = false; 8978 unsigned DiagKind; 8979 FixItHint Hint; 8980 ConversionFixItGenerator ConvHints; 8981 bool MayHaveConvFixit = false; 8982 8983 switch (ConvTy) { 8984 default: llvm_unreachable("Unknown conversion type"); 8985 case Compatible: return false; 8986 case PointerToInt: 8987 DiagKind = diag::ext_typecheck_convert_pointer_int; 8988 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 8989 MayHaveConvFixit = true; 8990 break; 8991 case IntToPointer: 8992 DiagKind = diag::ext_typecheck_convert_int_pointer; 8993 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 8994 MayHaveConvFixit = true; 8995 break; 8996 case IncompatiblePointer: 8997 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint); 8998 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 8999 CheckInferredResultType = DstType->isObjCObjectPointerType() && 9000 SrcType->isObjCObjectPointerType(); 9001 if (Hint.isNull() && !CheckInferredResultType) { 9002 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 9003 } 9004 MayHaveConvFixit = true; 9005 break; 9006 case IncompatiblePointerSign: 9007 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 9008 break; 9009 case FunctionVoidPointer: 9010 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 9011 break; 9012 case IncompatiblePointerDiscardsQualifiers: { 9013 // Perform array-to-pointer decay if necessary. 9014 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 9015 9016 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 9017 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 9018 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 9019 DiagKind = diag::err_typecheck_incompatible_address_space; 9020 break; 9021 9022 9023 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 9024 DiagKind = diag::err_typecheck_incompatible_ownership; 9025 break; 9026 } 9027 9028 llvm_unreachable("unknown error case for discarding qualifiers!"); 9029 // fallthrough 9030 } 9031 case CompatiblePointerDiscardsQualifiers: 9032 // If the qualifiers lost were because we were applying the 9033 // (deprecated) C++ conversion from a string literal to a char* 9034 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 9035 // Ideally, this check would be performed in 9036 // checkPointerTypesForAssignment. However, that would require a 9037 // bit of refactoring (so that the second argument is an 9038 // expression, rather than a type), which should be done as part 9039 // of a larger effort to fix checkPointerTypesForAssignment for 9040 // C++ semantics. 9041 if (getLangOptions().CPlusPlus && 9042 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 9043 return false; 9044 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 9045 break; 9046 case IncompatibleNestedPointerQualifiers: 9047 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 9048 break; 9049 case IntToBlockPointer: 9050 DiagKind = diag::err_int_to_block_pointer; 9051 break; 9052 case IncompatibleBlockPointer: 9053 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 9054 break; 9055 case IncompatibleObjCQualifiedId: 9056 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since 9057 // it can give a more specific diagnostic. 9058 DiagKind = diag::warn_incompatible_qualified_id; 9059 break; 9060 case IncompatibleVectors: 9061 DiagKind = diag::warn_incompatible_vectors; 9062 break; 9063 case IncompatibleObjCWeakRef: 9064 DiagKind = diag::err_arc_weak_unavailable_assign; 9065 break; 9066 case Incompatible: 9067 DiagKind = diag::err_typecheck_convert_incompatible; 9068 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 9069 MayHaveConvFixit = true; 9070 isInvalid = true; 9071 break; 9072 } 9073 9074 QualType FirstType, SecondType; 9075 switch (Action) { 9076 case AA_Assigning: 9077 case AA_Initializing: 9078 // The destination type comes first. 9079 FirstType = DstType; 9080 SecondType = SrcType; 9081 break; 9082 9083 case AA_Returning: 9084 case AA_Passing: 9085 case AA_Converting: 9086 case AA_Sending: 9087 case AA_Casting: 9088 // The source type comes first. 9089 FirstType = SrcType; 9090 SecondType = DstType; 9091 break; 9092 } 9093 9094 PartialDiagnostic FDiag = PDiag(DiagKind); 9095 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 9096 9097 // If we can fix the conversion, suggest the FixIts. 9098 assert(ConvHints.isNull() || Hint.isNull()); 9099 if (!ConvHints.isNull()) { 9100 for (llvm::SmallVector<FixItHint, 1>::iterator 9101 HI = ConvHints.Hints.begin(), HE = ConvHints.Hints.end(); 9102 HI != HE; ++HI) 9103 FDiag << *HI; 9104 } else { 9105 FDiag << Hint; 9106 } 9107 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 9108 9109 Diag(Loc, FDiag); 9110 9111 if (CheckInferredResultType) 9112 EmitRelatedResultTypeNote(SrcExpr); 9113 9114 if (Complained) 9115 *Complained = true; 9116 return isInvalid; 9117 } 9118 9119 bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){ 9120 llvm::APSInt ICEResult; 9121 if (E->isIntegerConstantExpr(ICEResult, Context)) { 9122 if (Result) 9123 *Result = ICEResult; 9124 return false; 9125 } 9126 9127 Expr::EvalResult EvalResult; 9128 9129 if (!E->EvaluateAsRValue(EvalResult, Context) || !EvalResult.Val.isInt() || 9130 EvalResult.HasSideEffects) { 9131 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange(); 9132 9133 if (EvalResult.Diag) { 9134 // We only show the note if it's not the usual "invalid subexpression" 9135 // or if it's actually in a subexpression. 9136 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice || 9137 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens()) 9138 Diag(EvalResult.DiagLoc, EvalResult.Diag); 9139 } 9140 9141 return true; 9142 } 9143 9144 Diag(E->getExprLoc(), diag::ext_expr_not_ice) << 9145 E->getSourceRange(); 9146 9147 if (EvalResult.Diag && 9148 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc) 9149 != DiagnosticsEngine::Ignored) 9150 Diag(EvalResult.DiagLoc, EvalResult.Diag); 9151 9152 if (Result) 9153 *Result = EvalResult.Val.getInt(); 9154 return false; 9155 } 9156 9157 void 9158 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) { 9159 ExprEvalContexts.push_back( 9160 ExpressionEvaluationContextRecord(NewContext, 9161 ExprTemporaries.size(), 9162 ExprNeedsCleanups)); 9163 ExprNeedsCleanups = false; 9164 } 9165 9166 void Sema::PopExpressionEvaluationContext() { 9167 // Pop the current expression evaluation context off the stack. 9168 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back(); 9169 ExprEvalContexts.pop_back(); 9170 9171 if (Rec.Context == PotentiallyPotentiallyEvaluated) { 9172 if (Rec.PotentiallyReferenced) { 9173 // Mark any remaining declarations in the current position of the stack 9174 // as "referenced". If they were not meant to be referenced, semantic 9175 // analysis would have eliminated them (e.g., in ActOnCXXTypeId). 9176 for (PotentiallyReferencedDecls::iterator 9177 I = Rec.PotentiallyReferenced->begin(), 9178 IEnd = Rec.PotentiallyReferenced->end(); 9179 I != IEnd; ++I) 9180 MarkDeclarationReferenced(I->first, I->second); 9181 } 9182 9183 if (Rec.PotentiallyDiagnosed) { 9184 // Emit any pending diagnostics. 9185 for (PotentiallyEmittedDiagnostics::iterator 9186 I = Rec.PotentiallyDiagnosed->begin(), 9187 IEnd = Rec.PotentiallyDiagnosed->end(); 9188 I != IEnd; ++I) 9189 Diag(I->first, I->second); 9190 } 9191 } 9192 9193 // When are coming out of an unevaluated context, clear out any 9194 // temporaries that we may have created as part of the evaluation of 9195 // the expression in that context: they aren't relevant because they 9196 // will never be constructed. 9197 if (Rec.Context == Unevaluated) { 9198 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries, 9199 ExprTemporaries.end()); 9200 ExprNeedsCleanups = Rec.ParentNeedsCleanups; 9201 9202 // Otherwise, merge the contexts together. 9203 } else { 9204 ExprNeedsCleanups |= Rec.ParentNeedsCleanups; 9205 } 9206 9207 // Destroy the popped expression evaluation record. 9208 Rec.Destroy(); 9209 } 9210 9211 void Sema::DiscardCleanupsInEvaluationContext() { 9212 ExprTemporaries.erase( 9213 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries, 9214 ExprTemporaries.end()); 9215 ExprNeedsCleanups = false; 9216 } 9217 9218 /// \brief Note that the given declaration was referenced in the source code. 9219 /// 9220 /// This routine should be invoke whenever a given declaration is referenced 9221 /// in the source code, and where that reference occurred. If this declaration 9222 /// reference means that the the declaration is used (C++ [basic.def.odr]p2, 9223 /// C99 6.9p3), then the declaration will be marked as used. 9224 /// 9225 /// \param Loc the location where the declaration was referenced. 9226 /// 9227 /// \param D the declaration that has been referenced by the source code. 9228 void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) { 9229 assert(D && "No declaration?"); 9230 9231 D->setReferenced(); 9232 9233 if (D->isUsed(false)) 9234 return; 9235 9236 // Mark a parameter or variable declaration "used", regardless of whether 9237 // we're in a template or not. The reason for this is that unevaluated 9238 // expressions (e.g. (void)sizeof()) constitute a use for warning purposes 9239 // (-Wunused-variables and -Wunused-parameters) 9240 if (isa<ParmVarDecl>(D) || 9241 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) { 9242 D->setUsed(); 9243 return; 9244 } 9245 9246 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D)) 9247 return; 9248 9249 // Do not mark anything as "used" within a dependent context; wait for 9250 // an instantiation. 9251 if (CurContext->isDependentContext()) 9252 return; 9253 9254 switch (ExprEvalContexts.back().Context) { 9255 case Unevaluated: 9256 // We are in an expression that is not potentially evaluated; do nothing. 9257 return; 9258 9259 case PotentiallyEvaluated: 9260 // We are in a potentially-evaluated expression, so this declaration is 9261 // "used"; handle this below. 9262 break; 9263 9264 case PotentiallyPotentiallyEvaluated: 9265 // We are in an expression that may be potentially evaluated; queue this 9266 // declaration reference until we know whether the expression is 9267 // potentially evaluated. 9268 ExprEvalContexts.back().addReferencedDecl(Loc, D); 9269 return; 9270 9271 case PotentiallyEvaluatedIfUsed: 9272 // Referenced declarations will only be used if the construct in the 9273 // containing expression is used. 9274 return; 9275 } 9276 9277 // Note that this declaration has been used. 9278 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) { 9279 if (Constructor->isDefaulted()) { 9280 if (Constructor->isDefaultConstructor()) { 9281 if (Constructor->isTrivial()) 9282 return; 9283 if (!Constructor->isUsed(false)) 9284 DefineImplicitDefaultConstructor(Loc, Constructor); 9285 } else if (Constructor->isCopyConstructor()) { 9286 if (!Constructor->isUsed(false)) 9287 DefineImplicitCopyConstructor(Loc, Constructor); 9288 } else if (Constructor->isMoveConstructor()) { 9289 if (!Constructor->isUsed(false)) 9290 DefineImplicitMoveConstructor(Loc, Constructor); 9291 } 9292 } 9293 9294 MarkVTableUsed(Loc, Constructor->getParent()); 9295 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) { 9296 if (Destructor->isDefaulted() && !Destructor->isUsed(false)) 9297 DefineImplicitDestructor(Loc, Destructor); 9298 if (Destructor->isVirtual()) 9299 MarkVTableUsed(Loc, Destructor->getParent()); 9300 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) { 9301 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() && 9302 MethodDecl->getOverloadedOperator() == OO_Equal) { 9303 if (!MethodDecl->isUsed(false)) { 9304 if (MethodDecl->isCopyAssignmentOperator()) 9305 DefineImplicitCopyAssignment(Loc, MethodDecl); 9306 else 9307 DefineImplicitMoveAssignment(Loc, MethodDecl); 9308 } 9309 } else if (MethodDecl->isVirtual()) 9310 MarkVTableUsed(Loc, MethodDecl->getParent()); 9311 } 9312 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 9313 // Recursive functions should be marked when used from another function. 9314 if (CurContext == Function) return; 9315 9316 // Implicit instantiation of function templates and member functions of 9317 // class templates. 9318 if (Function->isImplicitlyInstantiable()) { 9319 bool AlreadyInstantiated = false; 9320 if (FunctionTemplateSpecializationInfo *SpecInfo 9321 = Function->getTemplateSpecializationInfo()) { 9322 if (SpecInfo->getPointOfInstantiation().isInvalid()) 9323 SpecInfo->setPointOfInstantiation(Loc); 9324 else if (SpecInfo->getTemplateSpecializationKind() 9325 == TSK_ImplicitInstantiation) 9326 AlreadyInstantiated = true; 9327 } else if (MemberSpecializationInfo *MSInfo 9328 = Function->getMemberSpecializationInfo()) { 9329 if (MSInfo->getPointOfInstantiation().isInvalid()) 9330 MSInfo->setPointOfInstantiation(Loc); 9331 else if (MSInfo->getTemplateSpecializationKind() 9332 == TSK_ImplicitInstantiation) 9333 AlreadyInstantiated = true; 9334 } 9335 9336 if (!AlreadyInstantiated) { 9337 if (isa<CXXRecordDecl>(Function->getDeclContext()) && 9338 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass()) 9339 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function, 9340 Loc)); 9341 else 9342 PendingInstantiations.push_back(std::make_pair(Function, Loc)); 9343 } 9344 } else { 9345 // Walk redefinitions, as some of them may be instantiable. 9346 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()), 9347 e(Function->redecls_end()); i != e; ++i) { 9348 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 9349 MarkDeclarationReferenced(Loc, *i); 9350 } 9351 } 9352 9353 // Keep track of used but undefined functions. 9354 if (!Function->isPure() && !Function->hasBody() && 9355 Function->getLinkage() != ExternalLinkage) { 9356 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()]; 9357 if (old.isInvalid()) old = Loc; 9358 } 9359 9360 Function->setUsed(true); 9361 return; 9362 } 9363 9364 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 9365 // Implicit instantiation of static data members of class templates. 9366 if (Var->isStaticDataMember() && 9367 Var->getInstantiatedFromStaticDataMember()) { 9368 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo(); 9369 assert(MSInfo && "Missing member specialization information?"); 9370 if (MSInfo->getPointOfInstantiation().isInvalid() && 9371 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) { 9372 MSInfo->setPointOfInstantiation(Loc); 9373 // This is a modification of an existing AST node. Notify listeners. 9374 if (ASTMutationListener *L = getASTMutationListener()) 9375 L->StaticDataMemberInstantiated(Var); 9376 PendingInstantiations.push_back(std::make_pair(Var, Loc)); 9377 } 9378 } 9379 9380 // Keep track of used but undefined variables. We make a hole in 9381 // the warning for static const data members with in-line 9382 // initializers. 9383 if (Var->hasDefinition() == VarDecl::DeclarationOnly 9384 && Var->getLinkage() != ExternalLinkage 9385 && !(Var->isStaticDataMember() && Var->hasInit())) { 9386 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()]; 9387 if (old.isInvalid()) old = Loc; 9388 } 9389 9390 D->setUsed(true); 9391 return; 9392 } 9393 } 9394 9395 namespace { 9396 // Mark all of the declarations referenced 9397 // FIXME: Not fully implemented yet! We need to have a better understanding 9398 // of when we're entering 9399 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 9400 Sema &S; 9401 SourceLocation Loc; 9402 9403 public: 9404 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 9405 9406 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 9407 9408 bool TraverseTemplateArgument(const TemplateArgument &Arg); 9409 bool TraverseRecordType(RecordType *T); 9410 }; 9411 } 9412 9413 bool MarkReferencedDecls::TraverseTemplateArgument( 9414 const TemplateArgument &Arg) { 9415 if (Arg.getKind() == TemplateArgument::Declaration) { 9416 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl()); 9417 } 9418 9419 return Inherited::TraverseTemplateArgument(Arg); 9420 } 9421 9422 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 9423 if (ClassTemplateSpecializationDecl *Spec 9424 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 9425 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 9426 return TraverseTemplateArguments(Args.data(), Args.size()); 9427 } 9428 9429 return true; 9430 } 9431 9432 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 9433 MarkReferencedDecls Marker(*this, Loc); 9434 Marker.TraverseType(Context.getCanonicalType(T)); 9435 } 9436 9437 namespace { 9438 /// \brief Helper class that marks all of the declarations referenced by 9439 /// potentially-evaluated subexpressions as "referenced". 9440 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 9441 Sema &S; 9442 9443 public: 9444 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 9445 9446 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { } 9447 9448 void VisitDeclRefExpr(DeclRefExpr *E) { 9449 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl()); 9450 } 9451 9452 void VisitMemberExpr(MemberExpr *E) { 9453 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl()); 9454 Inherited::VisitMemberExpr(E); 9455 } 9456 9457 void VisitCXXNewExpr(CXXNewExpr *E) { 9458 if (E->getConstructor()) 9459 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor()); 9460 if (E->getOperatorNew()) 9461 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew()); 9462 if (E->getOperatorDelete()) 9463 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete()); 9464 Inherited::VisitCXXNewExpr(E); 9465 } 9466 9467 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 9468 if (E->getOperatorDelete()) 9469 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete()); 9470 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 9471 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 9472 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 9473 S.MarkDeclarationReferenced(E->getLocStart(), 9474 S.LookupDestructor(Record)); 9475 } 9476 9477 Inherited::VisitCXXDeleteExpr(E); 9478 } 9479 9480 void VisitCXXConstructExpr(CXXConstructExpr *E) { 9481 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor()); 9482 Inherited::VisitCXXConstructExpr(E); 9483 } 9484 9485 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) { 9486 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl()); 9487 } 9488 9489 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 9490 Visit(E->getExpr()); 9491 } 9492 }; 9493 } 9494 9495 /// \brief Mark any declarations that appear within this expression or any 9496 /// potentially-evaluated subexpressions as "referenced". 9497 void Sema::MarkDeclarationsReferencedInExpr(Expr *E) { 9498 EvaluatedExprMarker(*this).Visit(E); 9499 } 9500 9501 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 9502 /// of the program being compiled. 9503 /// 9504 /// This routine emits the given diagnostic when the code currently being 9505 /// type-checked is "potentially evaluated", meaning that there is a 9506 /// possibility that the code will actually be executable. Code in sizeof() 9507 /// expressions, code used only during overload resolution, etc., are not 9508 /// potentially evaluated. This routine will suppress such diagnostics or, 9509 /// in the absolutely nutty case of potentially potentially evaluated 9510 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 9511 /// later. 9512 /// 9513 /// This routine should be used for all diagnostics that describe the run-time 9514 /// behavior of a program, such as passing a non-POD value through an ellipsis. 9515 /// Failure to do so will likely result in spurious diagnostics or failures 9516 /// during overload resolution or within sizeof/alignof/typeof/typeid. 9517 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 9518 const PartialDiagnostic &PD) { 9519 switch (ExprEvalContexts.back().Context) { 9520 case Unevaluated: 9521 // The argument will never be evaluated, so don't complain. 9522 break; 9523 9524 case PotentiallyEvaluated: 9525 case PotentiallyEvaluatedIfUsed: 9526 if (Statement && getCurFunctionOrMethodDecl()) { 9527 FunctionScopes.back()->PossiblyUnreachableDiags. 9528 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 9529 } 9530 else 9531 Diag(Loc, PD); 9532 9533 return true; 9534 9535 case PotentiallyPotentiallyEvaluated: 9536 ExprEvalContexts.back().addDiagnostic(Loc, PD); 9537 break; 9538 } 9539 9540 return false; 9541 } 9542 9543 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 9544 CallExpr *CE, FunctionDecl *FD) { 9545 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 9546 return false; 9547 9548 PartialDiagnostic Note = 9549 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here) 9550 << FD->getDeclName() : PDiag(); 9551 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation(); 9552 9553 if (RequireCompleteType(Loc, ReturnType, 9554 FD ? 9555 PDiag(diag::err_call_function_incomplete_return) 9556 << CE->getSourceRange() << FD->getDeclName() : 9557 PDiag(diag::err_call_incomplete_return) 9558 << CE->getSourceRange(), 9559 std::make_pair(NoteLoc, Note))) 9560 return true; 9561 9562 return false; 9563 } 9564 9565 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 9566 // will prevent this condition from triggering, which is what we want. 9567 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 9568 SourceLocation Loc; 9569 9570 unsigned diagnostic = diag::warn_condition_is_assignment; 9571 bool IsOrAssign = false; 9572 9573 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 9574 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 9575 return; 9576 9577 IsOrAssign = Op->getOpcode() == BO_OrAssign; 9578 9579 // Greylist some idioms by putting them into a warning subcategory. 9580 if (ObjCMessageExpr *ME 9581 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 9582 Selector Sel = ME->getSelector(); 9583 9584 // self = [<foo> init...] 9585 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init")) 9586 diagnostic = diag::warn_condition_is_idiomatic_assignment; 9587 9588 // <foo> = [<bar> nextObject] 9589 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 9590 diagnostic = diag::warn_condition_is_idiomatic_assignment; 9591 } 9592 9593 Loc = Op->getOperatorLoc(); 9594 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 9595 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 9596 return; 9597 9598 IsOrAssign = Op->getOperator() == OO_PipeEqual; 9599 Loc = Op->getOperatorLoc(); 9600 } else { 9601 // Not an assignment. 9602 return; 9603 } 9604 9605 Diag(Loc, diagnostic) << E->getSourceRange(); 9606 9607 SourceLocation Open = E->getSourceRange().getBegin(); 9608 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd()); 9609 Diag(Loc, diag::note_condition_assign_silence) 9610 << FixItHint::CreateInsertion(Open, "(") 9611 << FixItHint::CreateInsertion(Close, ")"); 9612 9613 if (IsOrAssign) 9614 Diag(Loc, diag::note_condition_or_assign_to_comparison) 9615 << FixItHint::CreateReplacement(Loc, "!="); 9616 else 9617 Diag(Loc, diag::note_condition_assign_to_comparison) 9618 << FixItHint::CreateReplacement(Loc, "=="); 9619 } 9620 9621 /// \brief Redundant parentheses over an equality comparison can indicate 9622 /// that the user intended an assignment used as condition. 9623 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 9624 // Don't warn if the parens came from a macro. 9625 SourceLocation parenLoc = ParenE->getLocStart(); 9626 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 9627 return; 9628 // Don't warn for dependent expressions. 9629 if (ParenE->isTypeDependent()) 9630 return; 9631 9632 Expr *E = ParenE->IgnoreParens(); 9633 9634 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 9635 if (opE->getOpcode() == BO_EQ && 9636 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 9637 == Expr::MLV_Valid) { 9638 SourceLocation Loc = opE->getOperatorLoc(); 9639 9640 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 9641 Diag(Loc, diag::note_equality_comparison_silence) 9642 << FixItHint::CreateRemoval(ParenE->getSourceRange().getBegin()) 9643 << FixItHint::CreateRemoval(ParenE->getSourceRange().getEnd()); 9644 Diag(Loc, diag::note_equality_comparison_to_assign) 9645 << FixItHint::CreateReplacement(Loc, "="); 9646 } 9647 } 9648 9649 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) { 9650 DiagnoseAssignmentAsCondition(E); 9651 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 9652 DiagnoseEqualityWithExtraParens(parenE); 9653 9654 ExprResult result = CheckPlaceholderExpr(E); 9655 if (result.isInvalid()) return ExprError(); 9656 E = result.take(); 9657 9658 if (!E->isTypeDependent()) { 9659 if (getLangOptions().CPlusPlus) 9660 return CheckCXXBooleanCondition(E); // C++ 6.4p4 9661 9662 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 9663 if (ERes.isInvalid()) 9664 return ExprError(); 9665 E = ERes.take(); 9666 9667 QualType T = E->getType(); 9668 if (!T->isScalarType()) { // C99 6.8.4.1p1 9669 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 9670 << T << E->getSourceRange(); 9671 return ExprError(); 9672 } 9673 } 9674 9675 return Owned(E); 9676 } 9677 9678 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc, 9679 Expr *SubExpr) { 9680 if (!SubExpr) 9681 return ExprError(); 9682 9683 return CheckBooleanCondition(SubExpr, Loc); 9684 } 9685 9686 namespace { 9687 /// A visitor for rebuilding a call to an __unknown_any expression 9688 /// to have an appropriate type. 9689 struct RebuildUnknownAnyFunction 9690 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 9691 9692 Sema &S; 9693 9694 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 9695 9696 ExprResult VisitStmt(Stmt *S) { 9697 llvm_unreachable("unexpected statement!"); 9698 return ExprError(); 9699 } 9700 9701 ExprResult VisitExpr(Expr *E) { 9702 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 9703 << E->getSourceRange(); 9704 return ExprError(); 9705 } 9706 9707 /// Rebuild an expression which simply semantically wraps another 9708 /// expression which it shares the type and value kind of. 9709 template <class T> ExprResult rebuildSugarExpr(T *E) { 9710 ExprResult SubResult = Visit(E->getSubExpr()); 9711 if (SubResult.isInvalid()) return ExprError(); 9712 9713 Expr *SubExpr = SubResult.take(); 9714 E->setSubExpr(SubExpr); 9715 E->setType(SubExpr->getType()); 9716 E->setValueKind(SubExpr->getValueKind()); 9717 assert(E->getObjectKind() == OK_Ordinary); 9718 return E; 9719 } 9720 9721 ExprResult VisitParenExpr(ParenExpr *E) { 9722 return rebuildSugarExpr(E); 9723 } 9724 9725 ExprResult VisitUnaryExtension(UnaryOperator *E) { 9726 return rebuildSugarExpr(E); 9727 } 9728 9729 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 9730 ExprResult SubResult = Visit(E->getSubExpr()); 9731 if (SubResult.isInvalid()) return ExprError(); 9732 9733 Expr *SubExpr = SubResult.take(); 9734 E->setSubExpr(SubExpr); 9735 E->setType(S.Context.getPointerType(SubExpr->getType())); 9736 assert(E->getValueKind() == VK_RValue); 9737 assert(E->getObjectKind() == OK_Ordinary); 9738 return E; 9739 } 9740 9741 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 9742 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 9743 9744 E->setType(VD->getType()); 9745 9746 assert(E->getValueKind() == VK_RValue); 9747 if (S.getLangOptions().CPlusPlus && 9748 !(isa<CXXMethodDecl>(VD) && 9749 cast<CXXMethodDecl>(VD)->isInstance())) 9750 E->setValueKind(VK_LValue); 9751 9752 return E; 9753 } 9754 9755 ExprResult VisitMemberExpr(MemberExpr *E) { 9756 return resolveDecl(E, E->getMemberDecl()); 9757 } 9758 9759 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 9760 return resolveDecl(E, E->getDecl()); 9761 } 9762 }; 9763 } 9764 9765 /// Given a function expression of unknown-any type, try to rebuild it 9766 /// to have a function type. 9767 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 9768 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 9769 if (Result.isInvalid()) return ExprError(); 9770 return S.DefaultFunctionArrayConversion(Result.take()); 9771 } 9772 9773 namespace { 9774 /// A visitor for rebuilding an expression of type __unknown_anytype 9775 /// into one which resolves the type directly on the referring 9776 /// expression. Strict preservation of the original source 9777 /// structure is not a goal. 9778 struct RebuildUnknownAnyExpr 9779 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 9780 9781 Sema &S; 9782 9783 /// The current destination type. 9784 QualType DestType; 9785 9786 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 9787 : S(S), DestType(CastType) {} 9788 9789 ExprResult VisitStmt(Stmt *S) { 9790 llvm_unreachable("unexpected statement!"); 9791 return ExprError(); 9792 } 9793 9794 ExprResult VisitExpr(Expr *E) { 9795 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 9796 << E->getSourceRange(); 9797 return ExprError(); 9798 } 9799 9800 ExprResult VisitCallExpr(CallExpr *E); 9801 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 9802 9803 /// Rebuild an expression which simply semantically wraps another 9804 /// expression which it shares the type and value kind of. 9805 template <class T> ExprResult rebuildSugarExpr(T *E) { 9806 ExprResult SubResult = Visit(E->getSubExpr()); 9807 if (SubResult.isInvalid()) return ExprError(); 9808 Expr *SubExpr = SubResult.take(); 9809 E->setSubExpr(SubExpr); 9810 E->setType(SubExpr->getType()); 9811 E->setValueKind(SubExpr->getValueKind()); 9812 assert(E->getObjectKind() == OK_Ordinary); 9813 return E; 9814 } 9815 9816 ExprResult VisitParenExpr(ParenExpr *E) { 9817 return rebuildSugarExpr(E); 9818 } 9819 9820 ExprResult VisitUnaryExtension(UnaryOperator *E) { 9821 return rebuildSugarExpr(E); 9822 } 9823 9824 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 9825 const PointerType *Ptr = DestType->getAs<PointerType>(); 9826 if (!Ptr) { 9827 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 9828 << E->getSourceRange(); 9829 return ExprError(); 9830 } 9831 assert(E->getValueKind() == VK_RValue); 9832 assert(E->getObjectKind() == OK_Ordinary); 9833 E->setType(DestType); 9834 9835 // Build the sub-expression as if it were an object of the pointee type. 9836 DestType = Ptr->getPointeeType(); 9837 ExprResult SubResult = Visit(E->getSubExpr()); 9838 if (SubResult.isInvalid()) return ExprError(); 9839 E->setSubExpr(SubResult.take()); 9840 return E; 9841 } 9842 9843 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 9844 9845 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 9846 9847 ExprResult VisitMemberExpr(MemberExpr *E) { 9848 return resolveDecl(E, E->getMemberDecl()); 9849 } 9850 9851 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 9852 return resolveDecl(E, E->getDecl()); 9853 } 9854 }; 9855 } 9856 9857 /// Rebuilds a call expression which yielded __unknown_anytype. 9858 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 9859 Expr *CalleeExpr = E->getCallee(); 9860 9861 enum FnKind { 9862 FK_MemberFunction, 9863 FK_FunctionPointer, 9864 FK_BlockPointer 9865 }; 9866 9867 FnKind Kind; 9868 QualType CalleeType = CalleeExpr->getType(); 9869 if (CalleeType == S.Context.BoundMemberTy) { 9870 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 9871 Kind = FK_MemberFunction; 9872 CalleeType = Expr::findBoundMemberType(CalleeExpr); 9873 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 9874 CalleeType = Ptr->getPointeeType(); 9875 Kind = FK_FunctionPointer; 9876 } else { 9877 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 9878 Kind = FK_BlockPointer; 9879 } 9880 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 9881 9882 // Verify that this is a legal result type of a function. 9883 if (DestType->isArrayType() || DestType->isFunctionType()) { 9884 unsigned diagID = diag::err_func_returning_array_function; 9885 if (Kind == FK_BlockPointer) 9886 diagID = diag::err_block_returning_array_function; 9887 9888 S.Diag(E->getExprLoc(), diagID) 9889 << DestType->isFunctionType() << DestType; 9890 return ExprError(); 9891 } 9892 9893 // Otherwise, go ahead and set DestType as the call's result. 9894 E->setType(DestType.getNonLValueExprType(S.Context)); 9895 E->setValueKind(Expr::getValueKindForType(DestType)); 9896 assert(E->getObjectKind() == OK_Ordinary); 9897 9898 // Rebuild the function type, replacing the result type with DestType. 9899 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType)) 9900 DestType = S.Context.getFunctionType(DestType, 9901 Proto->arg_type_begin(), 9902 Proto->getNumArgs(), 9903 Proto->getExtProtoInfo()); 9904 else 9905 DestType = S.Context.getFunctionNoProtoType(DestType, 9906 FnType->getExtInfo()); 9907 9908 // Rebuild the appropriate pointer-to-function type. 9909 switch (Kind) { 9910 case FK_MemberFunction: 9911 // Nothing to do. 9912 break; 9913 9914 case FK_FunctionPointer: 9915 DestType = S.Context.getPointerType(DestType); 9916 break; 9917 9918 case FK_BlockPointer: 9919 DestType = S.Context.getBlockPointerType(DestType); 9920 break; 9921 } 9922 9923 // Finally, we can recurse. 9924 ExprResult CalleeResult = Visit(CalleeExpr); 9925 if (!CalleeResult.isUsable()) return ExprError(); 9926 E->setCallee(CalleeResult.take()); 9927 9928 // Bind a temporary if necessary. 9929 return S.MaybeBindToTemporary(E); 9930 } 9931 9932 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 9933 // Verify that this is a legal result type of a call. 9934 if (DestType->isArrayType() || DestType->isFunctionType()) { 9935 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 9936 << DestType->isFunctionType() << DestType; 9937 return ExprError(); 9938 } 9939 9940 // Rewrite the method result type if available. 9941 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 9942 assert(Method->getResultType() == S.Context.UnknownAnyTy); 9943 Method->setResultType(DestType); 9944 } 9945 9946 // Change the type of the message. 9947 E->setType(DestType.getNonReferenceType()); 9948 E->setValueKind(Expr::getValueKindForType(DestType)); 9949 9950 return S.MaybeBindToTemporary(E); 9951 } 9952 9953 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 9954 // The only case we should ever see here is a function-to-pointer decay. 9955 assert(E->getCastKind() == CK_FunctionToPointerDecay); 9956 assert(E->getValueKind() == VK_RValue); 9957 assert(E->getObjectKind() == OK_Ordinary); 9958 9959 E->setType(DestType); 9960 9961 // Rebuild the sub-expression as the pointee (function) type. 9962 DestType = DestType->castAs<PointerType>()->getPointeeType(); 9963 9964 ExprResult Result = Visit(E->getSubExpr()); 9965 if (!Result.isUsable()) return ExprError(); 9966 9967 E->setSubExpr(Result.take()); 9968 return S.Owned(E); 9969 } 9970 9971 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 9972 ExprValueKind ValueKind = VK_LValue; 9973 QualType Type = DestType; 9974 9975 // We know how to make this work for certain kinds of decls: 9976 9977 // - functions 9978 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 9979 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 9980 DestType = Ptr->getPointeeType(); 9981 ExprResult Result = resolveDecl(E, VD); 9982 if (Result.isInvalid()) return ExprError(); 9983 return S.ImpCastExprToType(Result.take(), Type, 9984 CK_FunctionToPointerDecay, VK_RValue); 9985 } 9986 9987 if (!Type->isFunctionType()) { 9988 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 9989 << VD << E->getSourceRange(); 9990 return ExprError(); 9991 } 9992 9993 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 9994 if (MD->isInstance()) { 9995 ValueKind = VK_RValue; 9996 Type = S.Context.BoundMemberTy; 9997 } 9998 9999 // Function references aren't l-values in C. 10000 if (!S.getLangOptions().CPlusPlus) 10001 ValueKind = VK_RValue; 10002 10003 // - variables 10004 } else if (isa<VarDecl>(VD)) { 10005 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 10006 Type = RefTy->getPointeeType(); 10007 } else if (Type->isFunctionType()) { 10008 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 10009 << VD << E->getSourceRange(); 10010 return ExprError(); 10011 } 10012 10013 // - nothing else 10014 } else { 10015 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 10016 << VD << E->getSourceRange(); 10017 return ExprError(); 10018 } 10019 10020 VD->setType(DestType); 10021 E->setType(Type); 10022 E->setValueKind(ValueKind); 10023 return S.Owned(E); 10024 } 10025 10026 /// Check a cast of an unknown-any type. We intentionally only 10027 /// trigger this for C-style casts. 10028 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 10029 Expr *CastExpr, CastKind &CastKind, 10030 ExprValueKind &VK, CXXCastPath &Path) { 10031 // Rewrite the casted expression from scratch. 10032 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 10033 if (!result.isUsable()) return ExprError(); 10034 10035 CastExpr = result.take(); 10036 VK = CastExpr->getValueKind(); 10037 CastKind = CK_NoOp; 10038 10039 return CastExpr; 10040 } 10041 10042 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 10043 Expr *orig = E; 10044 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 10045 while (true) { 10046 E = E->IgnoreParenImpCasts(); 10047 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 10048 E = call->getCallee(); 10049 diagID = diag::err_uncasted_call_of_unknown_any; 10050 } else { 10051 break; 10052 } 10053 } 10054 10055 SourceLocation loc; 10056 NamedDecl *d; 10057 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 10058 loc = ref->getLocation(); 10059 d = ref->getDecl(); 10060 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 10061 loc = mem->getMemberLoc(); 10062 d = mem->getMemberDecl(); 10063 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 10064 diagID = diag::err_uncasted_call_of_unknown_any; 10065 loc = msg->getSelectorStartLoc(); 10066 d = msg->getMethodDecl(); 10067 if (!d) { 10068 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 10069 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 10070 << orig->getSourceRange(); 10071 return ExprError(); 10072 } 10073 } else { 10074 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 10075 << E->getSourceRange(); 10076 return ExprError(); 10077 } 10078 10079 S.Diag(loc, diagID) << d << orig->getSourceRange(); 10080 10081 // Never recoverable. 10082 return ExprError(); 10083 } 10084 10085 /// Check for operands with placeholder types and complain if found. 10086 /// Returns true if there was an error and no recovery was possible. 10087 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 10088 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 10089 if (!placeholderType) return Owned(E); 10090 10091 switch (placeholderType->getKind()) { 10092 10093 // Overloaded expressions. 10094 case BuiltinType::Overload: { 10095 // Try to resolve a single function template specialization. 10096 // This is obligatory. 10097 ExprResult result = Owned(E); 10098 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) { 10099 return result; 10100 10101 // If that failed, try to recover with a call. 10102 } else { 10103 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable), 10104 /*complain*/ true); 10105 return result; 10106 } 10107 } 10108 10109 // Bound member functions. 10110 case BuiltinType::BoundMember: { 10111 ExprResult result = Owned(E); 10112 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function), 10113 /*complain*/ true); 10114 return result; 10115 } 10116 10117 // ARC unbridged casts. 10118 case BuiltinType::ARCUnbridgedCast: { 10119 Expr *realCast = stripARCUnbridgedCast(E); 10120 diagnoseARCUnbridgedCast(realCast); 10121 return Owned(realCast); 10122 } 10123 10124 // Expressions of unknown type. 10125 case BuiltinType::UnknownAny: 10126 return diagnoseUnknownAnyExpr(*this, E); 10127 10128 // Pseudo-objects. 10129 case BuiltinType::PseudoObject: 10130 return checkPseudoObjectRValue(E); 10131 10132 // Everything else should be impossible. 10133 #define BUILTIN_TYPE(Id, SingletonId) \ 10134 case BuiltinType::Id: 10135 #define PLACEHOLDER_TYPE(Id, SingletonId) 10136 #include "clang/AST/BuiltinTypes.def" 10137 break; 10138 } 10139 10140 llvm_unreachable("invalid placeholder type!"); 10141 } 10142 10143 bool Sema::CheckCaseExpression(Expr *E) { 10144 if (E->isTypeDependent()) 10145 return true; 10146 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 10147 return E->getType()->isIntegralOrEnumerationType(); 10148 return false; 10149 } 10150