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