SemaExpr.cpp revision 4e7f00c74487bca84993a1f35d0a26a84ed2b1a0
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 "TreeTransform.h" 16#include "clang/AST/ASTConsumer.h" 17#include "clang/AST/ASTContext.h" 18#include "clang/AST/ASTMutationListener.h" 19#include "clang/AST/CXXInheritance.h" 20#include "clang/AST/DeclObjC.h" 21#include "clang/AST/DeclTemplate.h" 22#include "clang/AST/EvaluatedExprVisitor.h" 23#include "clang/AST/Expr.h" 24#include "clang/AST/ExprCXX.h" 25#include "clang/AST/ExprObjC.h" 26#include "clang/AST/RecursiveASTVisitor.h" 27#include "clang/AST/TypeLoc.h" 28#include "clang/Basic/PartialDiagnostic.h" 29#include "clang/Basic/SourceManager.h" 30#include "clang/Basic/TargetInfo.h" 31#include "clang/Lex/LiteralSupport.h" 32#include "clang/Lex/Preprocessor.h" 33#include "clang/Sema/AnalysisBasedWarnings.h" 34#include "clang/Sema/DeclSpec.h" 35#include "clang/Sema/DelayedDiagnostic.h" 36#include "clang/Sema/Designator.h" 37#include "clang/Sema/Initialization.h" 38#include "clang/Sema/Lookup.h" 39#include "clang/Sema/ParsedTemplate.h" 40#include "clang/Sema/Scope.h" 41#include "clang/Sema/ScopeInfo.h" 42#include "clang/Sema/SemaFixItUtils.h" 43#include "clang/Sema/Template.h" 44using namespace clang; 45using namespace sema; 46 47/// \brief Determine whether the use of this declaration is valid, without 48/// emitting diagnostics. 49bool 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 // If the function has a deduced return type, and we can't deduce it, 60 // then we can't use it either. 61 if (getLangOpts().CPlusPlus1y && FD->getResultType()->isUndeducedType() && 62 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/false)) 63 return false; 64 } 65 66 // See if this function is unavailable. 67 if (D->getAvailability() == AR_Unavailable && 68 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 69 return false; 70 71 return true; 72} 73 74static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 75 // Warn if this is used but marked unused. 76 if (D->hasAttr<UnusedAttr>()) { 77 const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext()); 78 if (!DC->hasAttr<UnusedAttr>()) 79 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 80 } 81} 82 83static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S, 84 NamedDecl *D, SourceLocation Loc, 85 const ObjCInterfaceDecl *UnknownObjCClass) { 86 // See if this declaration is unavailable or deprecated. 87 std::string Message; 88 AvailabilityResult Result = D->getAvailability(&Message); 89 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) 90 if (Result == AR_Available) { 91 const DeclContext *DC = ECD->getDeclContext(); 92 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC)) 93 Result = TheEnumDecl->getAvailability(&Message); 94 } 95 96 const ObjCPropertyDecl *ObjCPDecl = 0; 97 if (Result == AR_Deprecated || Result == AR_Unavailable) { 98 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 99 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { 100 AvailabilityResult PDeclResult = PD->getAvailability(0); 101 if (PDeclResult == Result) 102 ObjCPDecl = PD; 103 } 104 } 105 } 106 107 switch (Result) { 108 case AR_Available: 109 case AR_NotYetIntroduced: 110 break; 111 112 case AR_Deprecated: 113 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass, ObjCPDecl); 114 break; 115 116 case AR_Unavailable: 117 if (S.getCurContextAvailability() != AR_Unavailable) { 118 if (Message.empty()) { 119 if (!UnknownObjCClass) { 120 S.Diag(Loc, diag::err_unavailable) << D->getDeclName(); 121 if (ObjCPDecl) 122 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute) 123 << ObjCPDecl->getDeclName() << 1; 124 } 125 else 126 S.Diag(Loc, diag::warn_unavailable_fwdclass_message) 127 << D->getDeclName(); 128 } 129 else 130 S.Diag(Loc, diag::err_unavailable_message) 131 << D->getDeclName() << Message; 132 S.Diag(D->getLocation(), diag::note_unavailable_here) 133 << isa<FunctionDecl>(D) << false; 134 if (ObjCPDecl) 135 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute) 136 << ObjCPDecl->getDeclName() << 1; 137 } 138 break; 139 } 140 return Result; 141} 142 143/// \brief Emit a note explaining that this function is deleted. 144void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 145 assert(Decl->isDeleted()); 146 147 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 148 149 if (Method && Method->isDeleted() && Method->isDefaulted()) { 150 // If the method was explicitly defaulted, point at that declaration. 151 if (!Method->isImplicit()) 152 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 153 154 // Try to diagnose why this special member function was implicitly 155 // deleted. This might fail, if that reason no longer applies. 156 CXXSpecialMember CSM = getSpecialMember(Method); 157 if (CSM != CXXInvalid) 158 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true); 159 160 return; 161 } 162 163 if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) { 164 if (CXXConstructorDecl *BaseCD = 165 const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) { 166 Diag(Decl->getLocation(), diag::note_inherited_deleted_here); 167 if (BaseCD->isDeleted()) { 168 NoteDeletedFunction(BaseCD); 169 } else { 170 // FIXME: An explanation of why exactly it can't be inherited 171 // would be nice. 172 Diag(BaseCD->getLocation(), diag::note_cannot_inherit); 173 } 174 return; 175 } 176 } 177 178 Diag(Decl->getLocation(), diag::note_unavailable_here) 179 << 1 << true; 180} 181 182/// \brief Determine whether a FunctionDecl was ever declared with an 183/// explicit storage class. 184static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 185 for (FunctionDecl::redecl_iterator I = D->redecls_begin(), 186 E = D->redecls_end(); 187 I != E; ++I) { 188 if (I->getStorageClass() != SC_None) 189 return true; 190 } 191 return false; 192} 193 194/// \brief Check whether we're in an extern inline function and referring to a 195/// variable or function with internal linkage (C11 6.7.4p3). 196/// 197/// This is only a warning because we used to silently accept this code, but 198/// in many cases it will not behave correctly. This is not enabled in C++ mode 199/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 200/// and so while there may still be user mistakes, most of the time we can't 201/// prove that there are errors. 202static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 203 const NamedDecl *D, 204 SourceLocation Loc) { 205 // This is disabled under C++; there are too many ways for this to fire in 206 // contexts where the warning is a false positive, or where it is technically 207 // correct but benign. 208 if (S.getLangOpts().CPlusPlus) 209 return; 210 211 // Check if this is an inlined function or method. 212 FunctionDecl *Current = S.getCurFunctionDecl(); 213 if (!Current) 214 return; 215 if (!Current->isInlined()) 216 return; 217 if (!Current->isExternallyVisible()) 218 return; 219 220 // Check if the decl has internal linkage. 221 if (D->getFormalLinkage() != InternalLinkage) 222 return; 223 224 // Downgrade from ExtWarn to Extension if 225 // (1) the supposedly external inline function is in the main file, 226 // and probably won't be included anywhere else. 227 // (2) the thing we're referencing is a pure function. 228 // (3) the thing we're referencing is another inline function. 229 // This last can give us false negatives, but it's better than warning on 230 // wrappers for simple C library functions. 231 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 232 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 233 if (!DowngradeWarning && UsedFn) 234 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 235 236 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline 237 : diag::warn_internal_in_extern_inline) 238 << /*IsVar=*/!UsedFn << D; 239 240 S.MaybeSuggestAddingStaticToDecl(Current); 241 242 S.Diag(D->getCanonicalDecl()->getLocation(), 243 diag::note_internal_decl_declared_here) 244 << D; 245} 246 247void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 248 const FunctionDecl *First = Cur->getFirstDecl(); 249 250 // Suggest "static" on the function, if possible. 251 if (!hasAnyExplicitStorageClass(First)) { 252 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 253 Diag(DeclBegin, diag::note_convert_inline_to_static) 254 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 255 } 256} 257 258/// \brief Determine whether the use of this declaration is valid, and 259/// emit any corresponding diagnostics. 260/// 261/// This routine diagnoses various problems with referencing 262/// declarations that can occur when using a declaration. For example, 263/// it might warn if a deprecated or unavailable declaration is being 264/// used, or produce an error (and return true) if a C++0x deleted 265/// function is being used. 266/// 267/// \returns true if there was an error (this declaration cannot be 268/// referenced), false otherwise. 269/// 270bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 271 const ObjCInterfaceDecl *UnknownObjCClass) { 272 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 273 // If there were any diagnostics suppressed by template argument deduction, 274 // emit them now. 275 SuppressedDiagnosticsMap::iterator 276 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 277 if (Pos != SuppressedDiagnostics.end()) { 278 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second; 279 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I) 280 Diag(Suppressed[I].first, Suppressed[I].second); 281 282 // Clear out the list of suppressed diagnostics, so that we don't emit 283 // them again for this specialization. However, we don't obsolete this 284 // entry from the table, because we want to avoid ever emitting these 285 // diagnostics again. 286 Suppressed.clear(); 287 } 288 } 289 290 // See if this is an auto-typed variable whose initializer we are parsing. 291 if (ParsingInitForAutoVars.count(D)) { 292 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 293 << D->getDeclName(); 294 return true; 295 } 296 297 // See if this is a deleted function. 298 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 299 if (FD->isDeleted()) { 300 Diag(Loc, diag::err_deleted_function_use); 301 NoteDeletedFunction(FD); 302 return true; 303 } 304 305 // If the function has a deduced return type, and we can't deduce it, 306 // then we can't use it either. 307 if (getLangOpts().CPlusPlus1y && FD->getResultType()->isUndeducedType() && 308 DeduceReturnType(FD, Loc)) 309 return true; 310 } 311 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass); 312 313 DiagnoseUnusedOfDecl(*this, D, Loc); 314 315 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 316 317 return false; 318} 319 320/// \brief Retrieve the message suffix that should be added to a 321/// diagnostic complaining about the given function being deleted or 322/// unavailable. 323std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 324 std::string Message; 325 if (FD->getAvailability(&Message)) 326 return ": " + Message; 327 328 return std::string(); 329} 330 331/// DiagnoseSentinelCalls - This routine checks whether a call or 332/// message-send is to a declaration with the sentinel attribute, and 333/// if so, it checks that the requirements of the sentinel are 334/// satisfied. 335void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 336 ArrayRef<Expr *> Args) { 337 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 338 if (!attr) 339 return; 340 341 // The number of formal parameters of the declaration. 342 unsigned numFormalParams; 343 344 // The kind of declaration. This is also an index into a %select in 345 // the diagnostic. 346 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 347 348 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 349 numFormalParams = MD->param_size(); 350 calleeType = CT_Method; 351 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 352 numFormalParams = FD->param_size(); 353 calleeType = CT_Function; 354 } else if (isa<VarDecl>(D)) { 355 QualType type = cast<ValueDecl>(D)->getType(); 356 const FunctionType *fn = 0; 357 if (const PointerType *ptr = type->getAs<PointerType>()) { 358 fn = ptr->getPointeeType()->getAs<FunctionType>(); 359 if (!fn) return; 360 calleeType = CT_Function; 361 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 362 fn = ptr->getPointeeType()->castAs<FunctionType>(); 363 calleeType = CT_Block; 364 } else { 365 return; 366 } 367 368 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 369 numFormalParams = proto->getNumArgs(); 370 } else { 371 numFormalParams = 0; 372 } 373 } else { 374 return; 375 } 376 377 // "nullPos" is the number of formal parameters at the end which 378 // effectively count as part of the variadic arguments. This is 379 // useful if you would prefer to not have *any* formal parameters, 380 // but the language forces you to have at least one. 381 unsigned nullPos = attr->getNullPos(); 382 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 383 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 384 385 // The number of arguments which should follow the sentinel. 386 unsigned numArgsAfterSentinel = attr->getSentinel(); 387 388 // If there aren't enough arguments for all the formal parameters, 389 // the sentinel, and the args after the sentinel, complain. 390 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 391 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 392 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 393 return; 394 } 395 396 // Otherwise, find the sentinel expression. 397 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 398 if (!sentinelExpr) return; 399 if (sentinelExpr->isValueDependent()) return; 400 if (Context.isSentinelNullExpr(sentinelExpr)) return; 401 402 // Pick a reasonable string to insert. Optimistically use 'nil' or 403 // 'NULL' if those are actually defined in the context. Only use 404 // 'nil' for ObjC methods, where it's much more likely that the 405 // variadic arguments form a list of object pointers. 406 SourceLocation MissingNilLoc 407 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd()); 408 std::string NullValue; 409 if (calleeType == CT_Method && 410 PP.getIdentifierInfo("nil")->hasMacroDefinition()) 411 NullValue = "nil"; 412 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition()) 413 NullValue = "NULL"; 414 else 415 NullValue = "(void*) 0"; 416 417 if (MissingNilLoc.isInvalid()) 418 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 419 else 420 Diag(MissingNilLoc, diag::warn_missing_sentinel) 421 << int(calleeType) 422 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 423 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 424} 425 426SourceRange Sema::getExprRange(Expr *E) const { 427 return E ? E->getSourceRange() : SourceRange(); 428} 429 430//===----------------------------------------------------------------------===// 431// Standard Promotions and Conversions 432//===----------------------------------------------------------------------===// 433 434/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 435ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) { 436 // Handle any placeholder expressions which made it here. 437 if (E->getType()->isPlaceholderType()) { 438 ExprResult result = CheckPlaceholderExpr(E); 439 if (result.isInvalid()) return ExprError(); 440 E = result.take(); 441 } 442 443 QualType Ty = E->getType(); 444 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 445 446 if (Ty->isFunctionType()) 447 E = ImpCastExprToType(E, Context.getPointerType(Ty), 448 CK_FunctionToPointerDecay).take(); 449 else if (Ty->isArrayType()) { 450 // In C90 mode, arrays only promote to pointers if the array expression is 451 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 452 // type 'array of type' is converted to an expression that has type 'pointer 453 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 454 // that has type 'array of type' ...". The relevant change is "an lvalue" 455 // (C90) to "an expression" (C99). 456 // 457 // C++ 4.2p1: 458 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 459 // T" can be converted to an rvalue of type "pointer to T". 460 // 461 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 462 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 463 CK_ArrayToPointerDecay).take(); 464 } 465 return Owned(E); 466} 467 468static void CheckForNullPointerDereference(Sema &S, Expr *E) { 469 // Check to see if we are dereferencing a null pointer. If so, 470 // and if not volatile-qualified, this is undefined behavior that the 471 // optimizer will delete, so warn about it. People sometimes try to use this 472 // to get a deterministic trap and are surprised by clang's behavior. This 473 // only handles the pattern "*null", which is a very syntactic check. 474 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 475 if (UO->getOpcode() == UO_Deref && 476 UO->getSubExpr()->IgnoreParenCasts()-> 477 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 478 !UO->getType().isVolatileQualified()) { 479 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 480 S.PDiag(diag::warn_indirection_through_null) 481 << UO->getSubExpr()->getSourceRange()); 482 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 483 S.PDiag(diag::note_indirection_through_null)); 484 } 485} 486 487static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 488 SourceLocation AssignLoc, 489 const Expr* RHS) { 490 const ObjCIvarDecl *IV = OIRE->getDecl(); 491 if (!IV) 492 return; 493 494 DeclarationName MemberName = IV->getDeclName(); 495 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 496 if (!Member || !Member->isStr("isa")) 497 return; 498 499 const Expr *Base = OIRE->getBase(); 500 QualType BaseType = Base->getType(); 501 if (OIRE->isArrow()) 502 BaseType = BaseType->getPointeeType(); 503 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 504 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 505 ObjCInterfaceDecl *ClassDeclared = 0; 506 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 507 if (!ClassDeclared->getSuperClass() 508 && (*ClassDeclared->ivar_begin()) == IV) { 509 if (RHS) { 510 NamedDecl *ObjectSetClass = 511 S.LookupSingleName(S.TUScope, 512 &S.Context.Idents.get("object_setClass"), 513 SourceLocation(), S.LookupOrdinaryName); 514 if (ObjectSetClass) { 515 SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd()); 516 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 517 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 518 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 519 AssignLoc), ",") << 520 FixItHint::CreateInsertion(RHSLocEnd, ")"); 521 } 522 else 523 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 524 } else { 525 NamedDecl *ObjectGetClass = 526 S.LookupSingleName(S.TUScope, 527 &S.Context.Idents.get("object_getClass"), 528 SourceLocation(), S.LookupOrdinaryName); 529 if (ObjectGetClass) 530 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 531 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 532 FixItHint::CreateReplacement( 533 SourceRange(OIRE->getOpLoc(), 534 OIRE->getLocEnd()), ")"); 535 else 536 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 537 } 538 S.Diag(IV->getLocation(), diag::note_ivar_decl); 539 } 540 } 541} 542 543ExprResult Sema::DefaultLvalueConversion(Expr *E) { 544 // Handle any placeholder expressions which made it here. 545 if (E->getType()->isPlaceholderType()) { 546 ExprResult result = CheckPlaceholderExpr(E); 547 if (result.isInvalid()) return ExprError(); 548 E = result.take(); 549 } 550 551 // C++ [conv.lval]p1: 552 // A glvalue of a non-function, non-array type T can be 553 // converted to a prvalue. 554 if (!E->isGLValue()) return Owned(E); 555 556 QualType T = E->getType(); 557 assert(!T.isNull() && "r-value conversion on typeless expression?"); 558 559 // We don't want to throw lvalue-to-rvalue casts on top of 560 // expressions of certain types in C++. 561 if (getLangOpts().CPlusPlus && 562 (E->getType() == Context.OverloadTy || 563 T->isDependentType() || 564 T->isRecordType())) 565 return Owned(E); 566 567 // The C standard is actually really unclear on this point, and 568 // DR106 tells us what the result should be but not why. It's 569 // generally best to say that void types just doesn't undergo 570 // lvalue-to-rvalue at all. Note that expressions of unqualified 571 // 'void' type are never l-values, but qualified void can be. 572 if (T->isVoidType()) 573 return Owned(E); 574 575 // OpenCL usually rejects direct accesses to values of 'half' type. 576 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 577 T->isHalfType()) { 578 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 579 << 0 << T; 580 return ExprError(); 581 } 582 583 CheckForNullPointerDereference(*this, E); 584 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 585 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 586 &Context.Idents.get("object_getClass"), 587 SourceLocation(), LookupOrdinaryName); 588 if (ObjectGetClass) 589 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 590 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 591 FixItHint::CreateReplacement( 592 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 593 else 594 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 595 } 596 else if (const ObjCIvarRefExpr *OIRE = 597 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 598 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/0); 599 600 // C++ [conv.lval]p1: 601 // [...] If T is a non-class type, the type of the prvalue is the 602 // cv-unqualified version of T. Otherwise, the type of the 603 // rvalue is T. 604 // 605 // C99 6.3.2.1p2: 606 // If the lvalue has qualified type, the value has the unqualified 607 // version of the type of the lvalue; otherwise, the value has the 608 // type of the lvalue. 609 if (T.hasQualifiers()) 610 T = T.getUnqualifiedType(); 611 612 UpdateMarkingForLValueToRValue(E); 613 614 // Loading a __weak object implicitly retains the value, so we need a cleanup to 615 // balance that. 616 if (getLangOpts().ObjCAutoRefCount && 617 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 618 ExprNeedsCleanups = true; 619 620 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, 621 E, 0, VK_RValue)); 622 623 // C11 6.3.2.1p2: 624 // ... if the lvalue has atomic type, the value has the non-atomic version 625 // of the type of the lvalue ... 626 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 627 T = Atomic->getValueType().getUnqualifiedType(); 628 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, 629 Res.get(), 0, VK_RValue)); 630 } 631 632 return Res; 633} 634 635ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) { 636 ExprResult Res = DefaultFunctionArrayConversion(E); 637 if (Res.isInvalid()) 638 return ExprError(); 639 Res = DefaultLvalueConversion(Res.take()); 640 if (Res.isInvalid()) 641 return ExprError(); 642 return Res; 643} 644 645 646/// UsualUnaryConversions - Performs various conversions that are common to most 647/// operators (C99 6.3). The conversions of array and function types are 648/// sometimes suppressed. For example, the array->pointer conversion doesn't 649/// apply if the array is an argument to the sizeof or address (&) operators. 650/// In these instances, this routine should *not* be called. 651ExprResult Sema::UsualUnaryConversions(Expr *E) { 652 // First, convert to an r-value. 653 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 654 if (Res.isInvalid()) 655 return ExprError(); 656 E = Res.take(); 657 658 QualType Ty = E->getType(); 659 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 660 661 // Half FP have to be promoted to float unless it is natively supported 662 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 663 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast); 664 665 // Try to perform integral promotions if the object has a theoretically 666 // promotable type. 667 if (Ty->isIntegralOrUnscopedEnumerationType()) { 668 // C99 6.3.1.1p2: 669 // 670 // The following may be used in an expression wherever an int or 671 // unsigned int may be used: 672 // - an object or expression with an integer type whose integer 673 // conversion rank is less than or equal to the rank of int 674 // and unsigned int. 675 // - A bit-field of type _Bool, int, signed int, or unsigned int. 676 // 677 // If an int can represent all values of the original type, the 678 // value is converted to an int; otherwise, it is converted to an 679 // unsigned int. These are called the integer promotions. All 680 // other types are unchanged by the integer promotions. 681 682 QualType PTy = Context.isPromotableBitField(E); 683 if (!PTy.isNull()) { 684 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take(); 685 return Owned(E); 686 } 687 if (Ty->isPromotableIntegerType()) { 688 QualType PT = Context.getPromotedIntegerType(Ty); 689 E = ImpCastExprToType(E, PT, CK_IntegralCast).take(); 690 return Owned(E); 691 } 692 } 693 return Owned(E); 694} 695 696/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 697/// do not have a prototype. Arguments that have type float or __fp16 698/// are promoted to double. All other argument types are converted by 699/// UsualUnaryConversions(). 700ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 701 QualType Ty = E->getType(); 702 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 703 704 ExprResult Res = UsualUnaryConversions(E); 705 if (Res.isInvalid()) 706 return ExprError(); 707 E = Res.take(); 708 709 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 710 // double. 711 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 712 if (BTy && (BTy->getKind() == BuiltinType::Half || 713 BTy->getKind() == BuiltinType::Float)) 714 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take(); 715 716 // C++ performs lvalue-to-rvalue conversion as a default argument 717 // promotion, even on class types, but note: 718 // C++11 [conv.lval]p2: 719 // When an lvalue-to-rvalue conversion occurs in an unevaluated 720 // operand or a subexpression thereof the value contained in the 721 // referenced object is not accessed. Otherwise, if the glvalue 722 // has a class type, the conversion copy-initializes a temporary 723 // of type T from the glvalue and the result of the conversion 724 // is a prvalue for the temporary. 725 // FIXME: add some way to gate this entire thing for correctness in 726 // potentially potentially evaluated contexts. 727 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 728 ExprResult Temp = PerformCopyInitialization( 729 InitializedEntity::InitializeTemporary(E->getType()), 730 E->getExprLoc(), 731 Owned(E)); 732 if (Temp.isInvalid()) 733 return ExprError(); 734 E = Temp.get(); 735 } 736 737 return Owned(E); 738} 739 740/// Determine the degree of POD-ness for an expression. 741/// Incomplete types are considered POD, since this check can be performed 742/// when we're in an unevaluated context. 743Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 744 if (Ty->isIncompleteType()) { 745 // C++11 [expr.call]p7: 746 // After these conversions, if the argument does not have arithmetic, 747 // enumeration, pointer, pointer to member, or class type, the program 748 // is ill-formed. 749 // 750 // Since we've already performed array-to-pointer and function-to-pointer 751 // decay, the only such type in C++ is cv void. This also handles 752 // initializer lists as variadic arguments. 753 if (Ty->isVoidType()) 754 return VAK_Invalid; 755 756 if (Ty->isObjCObjectType()) 757 return VAK_Invalid; 758 return VAK_Valid; 759 } 760 761 if (Ty.isCXX98PODType(Context)) 762 return VAK_Valid; 763 764 // C++11 [expr.call]p7: 765 // Passing a potentially-evaluated argument of class type (Clause 9) 766 // having a non-trivial copy constructor, a non-trivial move constructor, 767 // or a non-trivial destructor, with no corresponding parameter, 768 // is conditionally-supported with implementation-defined semantics. 769 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 770 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 771 if (!Record->hasNonTrivialCopyConstructor() && 772 !Record->hasNonTrivialMoveConstructor() && 773 !Record->hasNonTrivialDestructor()) 774 return VAK_ValidInCXX11; 775 776 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 777 return VAK_Valid; 778 779 if (Ty->isObjCObjectType()) 780 return VAK_Invalid; 781 782 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 783 // permitted to reject them. We should consider doing so. 784 return VAK_Undefined; 785} 786 787void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 788 // Don't allow one to pass an Objective-C interface to a vararg. 789 const QualType &Ty = E->getType(); 790 VarArgKind VAK = isValidVarArgType(Ty); 791 792 // Complain about passing non-POD types through varargs. 793 switch (VAK) { 794 case VAK_Valid: 795 break; 796 797 case VAK_ValidInCXX11: 798 DiagRuntimeBehavior( 799 E->getLocStart(), 0, 800 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 801 << E->getType() << CT); 802 break; 803 804 case VAK_Undefined: 805 DiagRuntimeBehavior( 806 E->getLocStart(), 0, 807 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 808 << getLangOpts().CPlusPlus11 << Ty << CT); 809 break; 810 811 case VAK_Invalid: 812 if (Ty->isObjCObjectType()) 813 DiagRuntimeBehavior( 814 E->getLocStart(), 0, 815 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 816 << Ty << CT); 817 else 818 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 819 << isa<InitListExpr>(E) << Ty << CT; 820 break; 821 } 822} 823 824/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 825/// will create a trap if the resulting type is not a POD type. 826ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 827 FunctionDecl *FDecl) { 828 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 829 // Strip the unbridged-cast placeholder expression off, if applicable. 830 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 831 (CT == VariadicMethod || 832 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 833 E = stripARCUnbridgedCast(E); 834 835 // Otherwise, do normal placeholder checking. 836 } else { 837 ExprResult ExprRes = CheckPlaceholderExpr(E); 838 if (ExprRes.isInvalid()) 839 return ExprError(); 840 E = ExprRes.take(); 841 } 842 } 843 844 ExprResult ExprRes = DefaultArgumentPromotion(E); 845 if (ExprRes.isInvalid()) 846 return ExprError(); 847 E = ExprRes.take(); 848 849 // Diagnostics regarding non-POD argument types are 850 // emitted along with format string checking in Sema::CheckFunctionCall(). 851 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 852 // Turn this into a trap. 853 CXXScopeSpec SS; 854 SourceLocation TemplateKWLoc; 855 UnqualifiedId Name; 856 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 857 E->getLocStart()); 858 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 859 Name, true, false); 860 if (TrapFn.isInvalid()) 861 return ExprError(); 862 863 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 864 E->getLocStart(), None, 865 E->getLocEnd()); 866 if (Call.isInvalid()) 867 return ExprError(); 868 869 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 870 Call.get(), E); 871 if (Comma.isInvalid()) 872 return ExprError(); 873 return Comma.get(); 874 } 875 876 if (!getLangOpts().CPlusPlus && 877 RequireCompleteType(E->getExprLoc(), E->getType(), 878 diag::err_call_incomplete_argument)) 879 return ExprError(); 880 881 return Owned(E); 882} 883 884/// \brief Converts an integer to complex float type. Helper function of 885/// UsualArithmeticConversions() 886/// 887/// \return false if the integer expression is an integer type and is 888/// successfully converted to the complex type. 889static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 890 ExprResult &ComplexExpr, 891 QualType IntTy, 892 QualType ComplexTy, 893 bool SkipCast) { 894 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 895 if (SkipCast) return false; 896 if (IntTy->isIntegerType()) { 897 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 898 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating); 899 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy, 900 CK_FloatingRealToComplex); 901 } else { 902 assert(IntTy->isComplexIntegerType()); 903 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy, 904 CK_IntegralComplexToFloatingComplex); 905 } 906 return false; 907} 908 909/// \brief Takes two complex float types and converts them to the same type. 910/// Helper function of UsualArithmeticConversions() 911static QualType 912handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS, 913 ExprResult &RHS, QualType LHSType, 914 QualType RHSType, 915 bool IsCompAssign) { 916 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 917 918 if (order < 0) { 919 // _Complex float -> _Complex double 920 if (!IsCompAssign) 921 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast); 922 return RHSType; 923 } 924 if (order > 0) 925 // _Complex float -> _Complex double 926 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast); 927 return LHSType; 928} 929 930/// \brief Converts otherExpr to complex float and promotes complexExpr if 931/// necessary. Helper function of UsualArithmeticConversions() 932static QualType handleOtherComplexFloatConversion(Sema &S, 933 ExprResult &ComplexExpr, 934 ExprResult &OtherExpr, 935 QualType ComplexTy, 936 QualType OtherTy, 937 bool ConvertComplexExpr, 938 bool ConvertOtherExpr) { 939 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy); 940 941 // If just the complexExpr is complex, the otherExpr needs to be converted, 942 // and the complexExpr might need to be promoted. 943 if (order > 0) { // complexExpr is wider 944 // float -> _Complex double 945 if (ConvertOtherExpr) { 946 QualType fp = cast<ComplexType>(ComplexTy)->getElementType(); 947 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast); 948 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy, 949 CK_FloatingRealToComplex); 950 } 951 return ComplexTy; 952 } 953 954 // otherTy is at least as wide. Find its corresponding complex type. 955 QualType result = (order == 0 ? ComplexTy : 956 S.Context.getComplexType(OtherTy)); 957 958 // double -> _Complex double 959 if (ConvertOtherExpr) 960 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result, 961 CK_FloatingRealToComplex); 962 963 // _Complex float -> _Complex double 964 if (ConvertComplexExpr && order < 0) 965 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result, 966 CK_FloatingComplexCast); 967 968 return result; 969} 970 971/// \brief Handle arithmetic conversion with complex types. Helper function of 972/// UsualArithmeticConversions() 973static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 974 ExprResult &RHS, QualType LHSType, 975 QualType RHSType, 976 bool IsCompAssign) { 977 // if we have an integer operand, the result is the complex type. 978 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 979 /*skipCast*/false)) 980 return LHSType; 981 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 982 /*skipCast*/IsCompAssign)) 983 return RHSType; 984 985 // This handles complex/complex, complex/float, or float/complex. 986 // When both operands are complex, the shorter operand is converted to the 987 // type of the longer, and that is the type of the result. This corresponds 988 // to what is done when combining two real floating-point operands. 989 // The fun begins when size promotion occur across type domains. 990 // From H&S 6.3.4: When one operand is complex and the other is a real 991 // floating-point type, the less precise type is converted, within it's 992 // real or complex domain, to the precision of the other type. For example, 993 // when combining a "long double" with a "double _Complex", the 994 // "double _Complex" is promoted to "long double _Complex". 995 996 bool LHSComplexFloat = LHSType->isComplexType(); 997 bool RHSComplexFloat = RHSType->isComplexType(); 998 999 // If both are complex, just cast to the more precise type. 1000 if (LHSComplexFloat && RHSComplexFloat) 1001 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS, 1002 LHSType, RHSType, 1003 IsCompAssign); 1004 1005 // If only one operand is complex, promote it if necessary and convert the 1006 // other operand to complex. 1007 if (LHSComplexFloat) 1008 return handleOtherComplexFloatConversion( 1009 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign, 1010 /*convertOtherExpr*/ true); 1011 1012 assert(RHSComplexFloat); 1013 return handleOtherComplexFloatConversion( 1014 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true, 1015 /*convertOtherExpr*/ !IsCompAssign); 1016} 1017 1018/// \brief Hande arithmetic conversion from integer to float. Helper function 1019/// of UsualArithmeticConversions() 1020static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1021 ExprResult &IntExpr, 1022 QualType FloatTy, QualType IntTy, 1023 bool ConvertFloat, bool ConvertInt) { 1024 if (IntTy->isIntegerType()) { 1025 if (ConvertInt) 1026 // Convert intExpr to the lhs floating point type. 1027 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy, 1028 CK_IntegralToFloating); 1029 return FloatTy; 1030 } 1031 1032 // Convert both sides to the appropriate complex float. 1033 assert(IntTy->isComplexIntegerType()); 1034 QualType result = S.Context.getComplexType(FloatTy); 1035 1036 // _Complex int -> _Complex float 1037 if (ConvertInt) 1038 IntExpr = S.ImpCastExprToType(IntExpr.take(), result, 1039 CK_IntegralComplexToFloatingComplex); 1040 1041 // float -> _Complex float 1042 if (ConvertFloat) 1043 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result, 1044 CK_FloatingRealToComplex); 1045 1046 return result; 1047} 1048 1049/// \brief Handle arithmethic conversion with floating point types. Helper 1050/// function of UsualArithmeticConversions() 1051static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1052 ExprResult &RHS, QualType LHSType, 1053 QualType RHSType, bool IsCompAssign) { 1054 bool LHSFloat = LHSType->isRealFloatingType(); 1055 bool RHSFloat = RHSType->isRealFloatingType(); 1056 1057 // If we have two real floating types, convert the smaller operand 1058 // to the bigger result. 1059 if (LHSFloat && RHSFloat) { 1060 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1061 if (order > 0) { 1062 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast); 1063 return LHSType; 1064 } 1065 1066 assert(order < 0 && "illegal float comparison"); 1067 if (!IsCompAssign) 1068 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast); 1069 return RHSType; 1070 } 1071 1072 if (LHSFloat) 1073 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1074 /*convertFloat=*/!IsCompAssign, 1075 /*convertInt=*/ true); 1076 assert(RHSFloat); 1077 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1078 /*convertInt=*/ true, 1079 /*convertFloat=*/!IsCompAssign); 1080} 1081 1082typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1083 1084namespace { 1085/// These helper callbacks are placed in an anonymous namespace to 1086/// permit their use as function template parameters. 1087ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1088 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1089} 1090 1091ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1092 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1093 CK_IntegralComplexCast); 1094} 1095} 1096 1097/// \brief Handle integer arithmetic conversions. Helper function of 1098/// UsualArithmeticConversions() 1099template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1100static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1101 ExprResult &RHS, QualType LHSType, 1102 QualType RHSType, bool IsCompAssign) { 1103 // The rules for this case are in C99 6.3.1.8 1104 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1105 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1106 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1107 if (LHSSigned == RHSSigned) { 1108 // Same signedness; use the higher-ranked type 1109 if (order >= 0) { 1110 RHS = (*doRHSCast)(S, RHS.take(), LHSType); 1111 return LHSType; 1112 } else if (!IsCompAssign) 1113 LHS = (*doLHSCast)(S, LHS.take(), RHSType); 1114 return RHSType; 1115 } else if (order != (LHSSigned ? 1 : -1)) { 1116 // The unsigned type has greater than or equal rank to the 1117 // signed type, so use the unsigned type 1118 if (RHSSigned) { 1119 RHS = (*doRHSCast)(S, RHS.take(), LHSType); 1120 return LHSType; 1121 } else if (!IsCompAssign) 1122 LHS = (*doLHSCast)(S, LHS.take(), RHSType); 1123 return RHSType; 1124 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1125 // The two types are different widths; if we are here, that 1126 // means the signed type is larger than the unsigned type, so 1127 // use the signed type. 1128 if (LHSSigned) { 1129 RHS = (*doRHSCast)(S, RHS.take(), LHSType); 1130 return LHSType; 1131 } else if (!IsCompAssign) 1132 LHS = (*doLHSCast)(S, LHS.take(), RHSType); 1133 return RHSType; 1134 } else { 1135 // The signed type is higher-ranked than the unsigned type, 1136 // but isn't actually any bigger (like unsigned int and long 1137 // on most 32-bit systems). Use the unsigned type corresponding 1138 // to the signed type. 1139 QualType result = 1140 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1141 RHS = (*doRHSCast)(S, RHS.take(), result); 1142 if (!IsCompAssign) 1143 LHS = (*doLHSCast)(S, LHS.take(), result); 1144 return result; 1145 } 1146} 1147 1148/// \brief Handle conversions with GCC complex int extension. Helper function 1149/// of UsualArithmeticConversions() 1150static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1151 ExprResult &RHS, QualType LHSType, 1152 QualType RHSType, 1153 bool IsCompAssign) { 1154 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1155 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1156 1157 if (LHSComplexInt && RHSComplexInt) { 1158 QualType LHSEltType = LHSComplexInt->getElementType(); 1159 QualType RHSEltType = RHSComplexInt->getElementType(); 1160 QualType ScalarType = 1161 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1162 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1163 1164 return S.Context.getComplexType(ScalarType); 1165 } 1166 1167 if (LHSComplexInt) { 1168 QualType LHSEltType = LHSComplexInt->getElementType(); 1169 QualType ScalarType = 1170 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1171 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1172 QualType ComplexType = S.Context.getComplexType(ScalarType); 1173 RHS = S.ImpCastExprToType(RHS.take(), ComplexType, 1174 CK_IntegralRealToComplex); 1175 1176 return ComplexType; 1177 } 1178 1179 assert(RHSComplexInt); 1180 1181 QualType RHSEltType = RHSComplexInt->getElementType(); 1182 QualType ScalarType = 1183 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1184 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1185 QualType ComplexType = S.Context.getComplexType(ScalarType); 1186 1187 if (!IsCompAssign) 1188 LHS = S.ImpCastExprToType(LHS.take(), ComplexType, 1189 CK_IntegralRealToComplex); 1190 return ComplexType; 1191} 1192 1193/// UsualArithmeticConversions - Performs various conversions that are common to 1194/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1195/// routine returns the first non-arithmetic type found. The client is 1196/// responsible for emitting appropriate error diagnostics. 1197QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1198 bool IsCompAssign) { 1199 if (!IsCompAssign) { 1200 LHS = UsualUnaryConversions(LHS.take()); 1201 if (LHS.isInvalid()) 1202 return QualType(); 1203 } 1204 1205 RHS = UsualUnaryConversions(RHS.take()); 1206 if (RHS.isInvalid()) 1207 return QualType(); 1208 1209 // For conversion purposes, we ignore any qualifiers. 1210 // For example, "const float" and "float" are equivalent. 1211 QualType LHSType = 1212 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1213 QualType RHSType = 1214 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1215 1216 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1217 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1218 LHSType = AtomicLHS->getValueType(); 1219 1220 // If both types are identical, no conversion is needed. 1221 if (LHSType == RHSType) 1222 return LHSType; 1223 1224 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1225 // The caller can deal with this (e.g. pointer + int). 1226 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1227 return QualType(); 1228 1229 // Apply unary and bitfield promotions to the LHS's type. 1230 QualType LHSUnpromotedType = LHSType; 1231 if (LHSType->isPromotableIntegerType()) 1232 LHSType = Context.getPromotedIntegerType(LHSType); 1233 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1234 if (!LHSBitfieldPromoteTy.isNull()) 1235 LHSType = LHSBitfieldPromoteTy; 1236 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1237 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast); 1238 1239 // If both types are identical, no conversion is needed. 1240 if (LHSType == RHSType) 1241 return LHSType; 1242 1243 // At this point, we have two different arithmetic types. 1244 1245 // Handle complex types first (C99 6.3.1.8p1). 1246 if (LHSType->isComplexType() || RHSType->isComplexType()) 1247 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1248 IsCompAssign); 1249 1250 // Now handle "real" floating types (i.e. float, double, long double). 1251 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1252 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1253 IsCompAssign); 1254 1255 // Handle GCC complex int extension. 1256 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1257 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1258 IsCompAssign); 1259 1260 // Finally, we have two differing integer types. 1261 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1262 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1263} 1264 1265 1266//===----------------------------------------------------------------------===// 1267// Semantic Analysis for various Expression Types 1268//===----------------------------------------------------------------------===// 1269 1270 1271ExprResult 1272Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1273 SourceLocation DefaultLoc, 1274 SourceLocation RParenLoc, 1275 Expr *ControllingExpr, 1276 ArrayRef<ParsedType> ArgTypes, 1277 ArrayRef<Expr *> ArgExprs) { 1278 unsigned NumAssocs = ArgTypes.size(); 1279 assert(NumAssocs == ArgExprs.size()); 1280 1281 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1282 for (unsigned i = 0; i < NumAssocs; ++i) { 1283 if (ArgTypes[i]) 1284 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1285 else 1286 Types[i] = 0; 1287 } 1288 1289 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1290 ControllingExpr, 1291 llvm::makeArrayRef(Types, NumAssocs), 1292 ArgExprs); 1293 delete [] Types; 1294 return ER; 1295} 1296 1297ExprResult 1298Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1299 SourceLocation DefaultLoc, 1300 SourceLocation RParenLoc, 1301 Expr *ControllingExpr, 1302 ArrayRef<TypeSourceInfo *> Types, 1303 ArrayRef<Expr *> Exprs) { 1304 unsigned NumAssocs = Types.size(); 1305 assert(NumAssocs == Exprs.size()); 1306 if (ControllingExpr->getType()->isPlaceholderType()) { 1307 ExprResult result = CheckPlaceholderExpr(ControllingExpr); 1308 if (result.isInvalid()) return ExprError(); 1309 ControllingExpr = result.take(); 1310 } 1311 1312 bool TypeErrorFound = false, 1313 IsResultDependent = ControllingExpr->isTypeDependent(), 1314 ContainsUnexpandedParameterPack 1315 = ControllingExpr->containsUnexpandedParameterPack(); 1316 1317 for (unsigned i = 0; i < NumAssocs; ++i) { 1318 if (Exprs[i]->containsUnexpandedParameterPack()) 1319 ContainsUnexpandedParameterPack = true; 1320 1321 if (Types[i]) { 1322 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1323 ContainsUnexpandedParameterPack = true; 1324 1325 if (Types[i]->getType()->isDependentType()) { 1326 IsResultDependent = true; 1327 } else { 1328 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1329 // complete object type other than a variably modified type." 1330 unsigned D = 0; 1331 if (Types[i]->getType()->isIncompleteType()) 1332 D = diag::err_assoc_type_incomplete; 1333 else if (!Types[i]->getType()->isObjectType()) 1334 D = diag::err_assoc_type_nonobject; 1335 else if (Types[i]->getType()->isVariablyModifiedType()) 1336 D = diag::err_assoc_type_variably_modified; 1337 1338 if (D != 0) { 1339 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1340 << Types[i]->getTypeLoc().getSourceRange() 1341 << Types[i]->getType(); 1342 TypeErrorFound = true; 1343 } 1344 1345 // C11 6.5.1.1p2 "No two generic associations in the same generic 1346 // selection shall specify compatible types." 1347 for (unsigned j = i+1; j < NumAssocs; ++j) 1348 if (Types[j] && !Types[j]->getType()->isDependentType() && 1349 Context.typesAreCompatible(Types[i]->getType(), 1350 Types[j]->getType())) { 1351 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1352 diag::err_assoc_compatible_types) 1353 << Types[j]->getTypeLoc().getSourceRange() 1354 << Types[j]->getType() 1355 << Types[i]->getType(); 1356 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1357 diag::note_compat_assoc) 1358 << Types[i]->getTypeLoc().getSourceRange() 1359 << Types[i]->getType(); 1360 TypeErrorFound = true; 1361 } 1362 } 1363 } 1364 } 1365 if (TypeErrorFound) 1366 return ExprError(); 1367 1368 // If we determined that the generic selection is result-dependent, don't 1369 // try to compute the result expression. 1370 if (IsResultDependent) 1371 return Owned(new (Context) GenericSelectionExpr( 1372 Context, KeyLoc, ControllingExpr, 1373 Types, Exprs, 1374 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack)); 1375 1376 SmallVector<unsigned, 1> CompatIndices; 1377 unsigned DefaultIndex = -1U; 1378 for (unsigned i = 0; i < NumAssocs; ++i) { 1379 if (!Types[i]) 1380 DefaultIndex = i; 1381 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1382 Types[i]->getType())) 1383 CompatIndices.push_back(i); 1384 } 1385 1386 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1387 // type compatible with at most one of the types named in its generic 1388 // association list." 1389 if (CompatIndices.size() > 1) { 1390 // We strip parens here because the controlling expression is typically 1391 // parenthesized in macro definitions. 1392 ControllingExpr = ControllingExpr->IgnoreParens(); 1393 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1394 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1395 << (unsigned) CompatIndices.size(); 1396 for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(), 1397 E = CompatIndices.end(); I != E; ++I) { 1398 Diag(Types[*I]->getTypeLoc().getBeginLoc(), 1399 diag::note_compat_assoc) 1400 << Types[*I]->getTypeLoc().getSourceRange() 1401 << Types[*I]->getType(); 1402 } 1403 return ExprError(); 1404 } 1405 1406 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1407 // its controlling expression shall have type compatible with exactly one of 1408 // the types named in its generic association list." 1409 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1410 // We strip parens here because the controlling expression is typically 1411 // parenthesized in macro definitions. 1412 ControllingExpr = ControllingExpr->IgnoreParens(); 1413 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1414 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1415 return ExprError(); 1416 } 1417 1418 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1419 // type name that is compatible with the type of the controlling expression, 1420 // then the result expression of the generic selection is the expression 1421 // in that generic association. Otherwise, the result expression of the 1422 // generic selection is the expression in the default generic association." 1423 unsigned ResultIndex = 1424 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1425 1426 return Owned(new (Context) GenericSelectionExpr( 1427 Context, KeyLoc, ControllingExpr, 1428 Types, Exprs, 1429 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack, 1430 ResultIndex)); 1431} 1432 1433/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1434/// location of the token and the offset of the ud-suffix within it. 1435static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1436 unsigned Offset) { 1437 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1438 S.getLangOpts()); 1439} 1440 1441/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1442/// the corresponding cooked (non-raw) literal operator, and build a call to it. 1443static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1444 IdentifierInfo *UDSuffix, 1445 SourceLocation UDSuffixLoc, 1446 ArrayRef<Expr*> Args, 1447 SourceLocation LitEndLoc) { 1448 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1449 1450 QualType ArgTy[2]; 1451 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1452 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1453 if (ArgTy[ArgIdx]->isArrayType()) 1454 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1455 } 1456 1457 DeclarationName OpName = 1458 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1459 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1460 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1461 1462 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1463 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1464 /*AllowRaw*/false, /*AllowTemplate*/false, 1465 /*AllowStringTemplate*/false) == Sema::LOLR_Error) 1466 return ExprError(); 1467 1468 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1469} 1470 1471/// ActOnStringLiteral - The specified tokens were lexed as pasted string 1472/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1473/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1474/// multiple tokens. However, the common case is that StringToks points to one 1475/// string. 1476/// 1477ExprResult 1478Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks, 1479 Scope *UDLScope) { 1480 assert(NumStringToks && "Must have at least one string!"); 1481 1482 StringLiteralParser Literal(StringToks, NumStringToks, PP); 1483 if (Literal.hadError) 1484 return ExprError(); 1485 1486 SmallVector<SourceLocation, 4> StringTokLocs; 1487 for (unsigned i = 0; i != NumStringToks; ++i) 1488 StringTokLocs.push_back(StringToks[i].getLocation()); 1489 1490 QualType CharTy = Context.CharTy; 1491 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1492 if (Literal.isWide()) { 1493 CharTy = Context.getWideCharType(); 1494 Kind = StringLiteral::Wide; 1495 } else if (Literal.isUTF8()) { 1496 Kind = StringLiteral::UTF8; 1497 } else if (Literal.isUTF16()) { 1498 CharTy = Context.Char16Ty; 1499 Kind = StringLiteral::UTF16; 1500 } else if (Literal.isUTF32()) { 1501 CharTy = Context.Char32Ty; 1502 Kind = StringLiteral::UTF32; 1503 } else if (Literal.isPascal()) { 1504 CharTy = Context.UnsignedCharTy; 1505 } 1506 1507 QualType CharTyConst = CharTy; 1508 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1509 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1510 CharTyConst.addConst(); 1511 1512 // Get an array type for the string, according to C99 6.4.5. This includes 1513 // the nul terminator character as well as the string length for pascal 1514 // strings. 1515 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1516 llvm::APInt(32, Literal.GetNumStringChars()+1), 1517 ArrayType::Normal, 0); 1518 1519 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1520 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1521 Kind, Literal.Pascal, StrTy, 1522 &StringTokLocs[0], 1523 StringTokLocs.size()); 1524 if (Literal.getUDSuffix().empty()) 1525 return Owned(Lit); 1526 1527 // We're building a user-defined literal. 1528 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1529 SourceLocation UDSuffixLoc = 1530 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1531 Literal.getUDSuffixOffset()); 1532 1533 // Make sure we're allowed user-defined literals here. 1534 if (!UDLScope) 1535 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1536 1537 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1538 // operator "" X (str, len) 1539 QualType SizeType = Context.getSizeType(); 1540 1541 DeclarationName OpName = 1542 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1543 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1544 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1545 1546 QualType ArgTy[] = { 1547 Context.getArrayDecayedType(StrTy), SizeType 1548 }; 1549 1550 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1551 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1552 /*AllowRaw*/false, /*AllowTemplate*/false, 1553 /*AllowStringTemplate*/true)) { 1554 1555 case LOLR_Cooked: { 1556 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1557 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1558 StringTokLocs[0]); 1559 Expr *Args[] = { Lit, LenArg }; 1560 1561 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1562 } 1563 1564 case LOLR_StringTemplate: { 1565 TemplateArgumentListInfo ExplicitArgs; 1566 1567 unsigned CharBits = Context.getIntWidth(CharTy); 1568 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1569 llvm::APSInt Value(CharBits, CharIsUnsigned); 1570 1571 TemplateArgument TypeArg(CharTy); 1572 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1573 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1574 1575 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1576 Value = Lit->getCodeUnit(I); 1577 TemplateArgument Arg(Context, Value, CharTy); 1578 TemplateArgumentLocInfo ArgInfo; 1579 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1580 } 1581 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1582 &ExplicitArgs); 1583 } 1584 case LOLR_Raw: 1585 case LOLR_Template: 1586 llvm_unreachable("unexpected literal operator lookup result"); 1587 case LOLR_Error: 1588 return ExprError(); 1589 } 1590 llvm_unreachable("unexpected literal operator lookup result"); 1591} 1592 1593ExprResult 1594Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1595 SourceLocation Loc, 1596 const CXXScopeSpec *SS) { 1597 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1598 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1599} 1600 1601/// BuildDeclRefExpr - Build an expression that references a 1602/// declaration that does not require a closure capture. 1603ExprResult 1604Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1605 const DeclarationNameInfo &NameInfo, 1606 const CXXScopeSpec *SS, NamedDecl *FoundD, 1607 const TemplateArgumentListInfo *TemplateArgs) { 1608 if (getLangOpts().CUDA) 1609 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 1610 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) { 1611 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller), 1612 CalleeTarget = IdentifyCUDATarget(Callee); 1613 if (CheckCUDATarget(CallerTarget, CalleeTarget)) { 1614 Diag(NameInfo.getLoc(), diag::err_ref_bad_target) 1615 << CalleeTarget << D->getIdentifier() << CallerTarget; 1616 Diag(D->getLocation(), diag::note_previous_decl) 1617 << D->getIdentifier(); 1618 return ExprError(); 1619 } 1620 } 1621 1622 bool refersToEnclosingScope = 1623 (CurContext != D->getDeclContext() && 1624 D->getDeclContext()->isFunctionOrMethod()) || 1625 (isa<VarDecl>(D) && 1626 cast<VarDecl>(D)->isInitCapture()); 1627 1628 DeclRefExpr *E; 1629 if (isa<VarTemplateSpecializationDecl>(D)) { 1630 VarTemplateSpecializationDecl *VarSpec = 1631 cast<VarTemplateSpecializationDecl>(D); 1632 1633 E = DeclRefExpr::Create( 1634 Context, 1635 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(), 1636 VarSpec->getTemplateKeywordLoc(), D, refersToEnclosingScope, 1637 NameInfo.getLoc(), Ty, VK, FoundD, TemplateArgs); 1638 } else { 1639 assert(!TemplateArgs && "No template arguments for non-variable" 1640 " template specialization referrences"); 1641 E = DeclRefExpr::Create( 1642 Context, 1643 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(), 1644 SourceLocation(), D, refersToEnclosingScope, NameInfo, Ty, VK, FoundD); 1645 } 1646 1647 MarkDeclRefReferenced(E); 1648 1649 if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) && 1650 Ty.getObjCLifetime() == Qualifiers::OCL_Weak) { 1651 DiagnosticsEngine::Level Level = 1652 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 1653 E->getLocStart()); 1654 if (Level != DiagnosticsEngine::Ignored) 1655 recordUseOfEvaluatedWeak(E); 1656 } 1657 1658 // Just in case we're building an illegal pointer-to-member. 1659 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1660 if (FD && FD->isBitField()) 1661 E->setObjectKind(OK_BitField); 1662 1663 return Owned(E); 1664} 1665 1666/// Decomposes the given name into a DeclarationNameInfo, its location, and 1667/// possibly a list of template arguments. 1668/// 1669/// If this produces template arguments, it is permitted to call 1670/// DecomposeTemplateName. 1671/// 1672/// This actually loses a lot of source location information for 1673/// non-standard name kinds; we should consider preserving that in 1674/// some way. 1675void 1676Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1677 TemplateArgumentListInfo &Buffer, 1678 DeclarationNameInfo &NameInfo, 1679 const TemplateArgumentListInfo *&TemplateArgs) { 1680 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1681 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1682 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1683 1684 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1685 Id.TemplateId->NumArgs); 1686 translateTemplateArguments(TemplateArgsPtr, Buffer); 1687 1688 TemplateName TName = Id.TemplateId->Template.get(); 1689 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1690 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1691 TemplateArgs = &Buffer; 1692 } else { 1693 NameInfo = GetNameFromUnqualifiedId(Id); 1694 TemplateArgs = 0; 1695 } 1696} 1697 1698/// Diagnose an empty lookup. 1699/// 1700/// \return false if new lookup candidates were found 1701bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1702 CorrectionCandidateCallback &CCC, 1703 TemplateArgumentListInfo *ExplicitTemplateArgs, 1704 ArrayRef<Expr *> Args) { 1705 DeclarationName Name = R.getLookupName(); 1706 1707 unsigned diagnostic = diag::err_undeclared_var_use; 1708 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1709 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1710 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1711 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1712 diagnostic = diag::err_undeclared_use; 1713 diagnostic_suggest = diag::err_undeclared_use_suggest; 1714 } 1715 1716 // If the original lookup was an unqualified lookup, fake an 1717 // unqualified lookup. This is useful when (for example) the 1718 // original lookup would not have found something because it was a 1719 // dependent name. 1720 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty()) 1721 ? CurContext : 0; 1722 while (DC) { 1723 if (isa<CXXRecordDecl>(DC)) { 1724 LookupQualifiedName(R, DC); 1725 1726 if (!R.empty()) { 1727 // Don't give errors about ambiguities in this lookup. 1728 R.suppressDiagnostics(); 1729 1730 // During a default argument instantiation the CurContext points 1731 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1732 // function parameter list, hence add an explicit check. 1733 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1734 ActiveTemplateInstantiations.back().Kind == 1735 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1736 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1737 bool isInstance = CurMethod && 1738 CurMethod->isInstance() && 1739 DC == CurMethod->getParent() && !isDefaultArgument; 1740 1741 1742 // Give a code modification hint to insert 'this->'. 1743 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1744 // Actually quite difficult! 1745 if (getLangOpts().MicrosoftMode) 1746 diagnostic = diag::warn_found_via_dependent_bases_lookup; 1747 if (isInstance) { 1748 Diag(R.getNameLoc(), diagnostic) << Name 1749 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1750 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>( 1751 CallsUndergoingInstantiation.back()->getCallee()); 1752 1753 CXXMethodDecl *DepMethod; 1754 if (CurMethod->isDependentContext()) 1755 DepMethod = CurMethod; 1756 else if (CurMethod->getTemplatedKind() == 1757 FunctionDecl::TK_FunctionTemplateSpecialization) 1758 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()-> 1759 getInstantiatedFromMemberTemplate()->getTemplatedDecl()); 1760 else 1761 DepMethod = cast<CXXMethodDecl>( 1762 CurMethod->getInstantiatedFromMemberFunction()); 1763 assert(DepMethod && "No template pattern found"); 1764 1765 QualType DepThisType = DepMethod->getThisType(Context); 1766 CheckCXXThisCapture(R.getNameLoc()); 1767 CXXThisExpr *DepThis = new (Context) CXXThisExpr( 1768 R.getNameLoc(), DepThisType, false); 1769 TemplateArgumentListInfo TList; 1770 if (ULE->hasExplicitTemplateArgs()) 1771 ULE->copyTemplateArgumentsInto(TList); 1772 1773 CXXScopeSpec SS; 1774 SS.Adopt(ULE->getQualifierLoc()); 1775 CXXDependentScopeMemberExpr *DepExpr = 1776 CXXDependentScopeMemberExpr::Create( 1777 Context, DepThis, DepThisType, true, SourceLocation(), 1778 SS.getWithLocInContext(Context), 1779 ULE->getTemplateKeywordLoc(), 0, 1780 R.getLookupNameInfo(), 1781 ULE->hasExplicitTemplateArgs() ? &TList : 0); 1782 CallsUndergoingInstantiation.back()->setCallee(DepExpr); 1783 } else { 1784 Diag(R.getNameLoc(), diagnostic) << Name; 1785 } 1786 1787 // Do we really want to note all of these? 1788 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 1789 Diag((*I)->getLocation(), diag::note_dependent_var_use); 1790 1791 // Return true if we are inside a default argument instantiation 1792 // and the found name refers to an instance member function, otherwise 1793 // the function calling DiagnoseEmptyLookup will try to create an 1794 // implicit member call and this is wrong for default argument. 1795 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1796 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1797 return true; 1798 } 1799 1800 // Tell the callee to try to recover. 1801 return false; 1802 } 1803 1804 R.clear(); 1805 } 1806 1807 // In Microsoft mode, if we are performing lookup from within a friend 1808 // function definition declared at class scope then we must set 1809 // DC to the lexical parent to be able to search into the parent 1810 // class. 1811 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) && 1812 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1813 DC->getLexicalParent()->isRecord()) 1814 DC = DC->getLexicalParent(); 1815 else 1816 DC = DC->getParent(); 1817 } 1818 1819 // We didn't find anything, so try to correct for a typo. 1820 TypoCorrection Corrected; 1821 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 1822 S, &SS, CCC))) { 1823 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1824 bool DroppedSpecifier = 1825 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1826 R.setLookupName(Corrected.getCorrection()); 1827 1828 bool AcceptableWithRecovery = false; 1829 bool AcceptableWithoutRecovery = false; 1830 NamedDecl *ND = Corrected.getCorrectionDecl(); 1831 if (ND) { 1832 if (Corrected.isOverloaded()) { 1833 OverloadCandidateSet OCS(R.getNameLoc()); 1834 OverloadCandidateSet::iterator Best; 1835 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 1836 CDEnd = Corrected.end(); 1837 CD != CDEnd; ++CD) { 1838 if (FunctionTemplateDecl *FTD = 1839 dyn_cast<FunctionTemplateDecl>(*CD)) 1840 AddTemplateOverloadCandidate( 1841 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1842 Args, OCS); 1843 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 1844 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1845 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1846 Args, OCS); 1847 } 1848 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1849 case OR_Success: 1850 ND = Best->Function; 1851 Corrected.setCorrectionDecl(ND); 1852 break; 1853 default: 1854 // FIXME: Arbitrarily pick the first declaration for the note. 1855 Corrected.setCorrectionDecl(ND); 1856 break; 1857 } 1858 } 1859 R.addDecl(ND); 1860 1861 AcceptableWithRecovery = 1862 isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND); 1863 // FIXME: If we ended up with a typo for a type name or 1864 // Objective-C class name, we're in trouble because the parser 1865 // is in the wrong place to recover. Suggest the typo 1866 // correction, but don't make it a fix-it since we're not going 1867 // to recover well anyway. 1868 AcceptableWithoutRecovery = 1869 isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 1870 } else { 1871 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1872 // because we aren't able to recover. 1873 AcceptableWithoutRecovery = true; 1874 } 1875 1876 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1877 unsigned NoteID = (Corrected.getCorrectionDecl() && 1878 isa<ImplicitParamDecl>(Corrected.getCorrectionDecl())) 1879 ? diag::note_implicit_param_decl 1880 : diag::note_previous_decl; 1881 if (SS.isEmpty()) 1882 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1883 PDiag(NoteID), AcceptableWithRecovery); 1884 else 1885 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1886 << Name << computeDeclContext(SS, false) 1887 << DroppedSpecifier << SS.getRange(), 1888 PDiag(NoteID), AcceptableWithRecovery); 1889 1890 // Tell the callee whether to try to recover. 1891 return !AcceptableWithRecovery; 1892 } 1893 } 1894 R.clear(); 1895 1896 // Emit a special diagnostic for failed member lookups. 1897 // FIXME: computing the declaration context might fail here (?) 1898 if (!SS.isEmpty()) { 1899 Diag(R.getNameLoc(), diag::err_no_member) 1900 << Name << computeDeclContext(SS, false) 1901 << SS.getRange(); 1902 return true; 1903 } 1904 1905 // Give up, we can't recover. 1906 Diag(R.getNameLoc(), diagnostic) << Name; 1907 return true; 1908} 1909 1910ExprResult Sema::ActOnIdExpression(Scope *S, 1911 CXXScopeSpec &SS, 1912 SourceLocation TemplateKWLoc, 1913 UnqualifiedId &Id, 1914 bool HasTrailingLParen, 1915 bool IsAddressOfOperand, 1916 CorrectionCandidateCallback *CCC, 1917 bool IsInlineAsmIdentifier) { 1918 assert(!(IsAddressOfOperand && HasTrailingLParen) && 1919 "cannot be direct & operand and have a trailing lparen"); 1920 if (SS.isInvalid()) 1921 return ExprError(); 1922 1923 TemplateArgumentListInfo TemplateArgsBuffer; 1924 1925 // Decompose the UnqualifiedId into the following data. 1926 DeclarationNameInfo NameInfo; 1927 const TemplateArgumentListInfo *TemplateArgs; 1928 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 1929 1930 DeclarationName Name = NameInfo.getName(); 1931 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1932 SourceLocation NameLoc = NameInfo.getLoc(); 1933 1934 // C++ [temp.dep.expr]p3: 1935 // An id-expression is type-dependent if it contains: 1936 // -- an identifier that was declared with a dependent type, 1937 // (note: handled after lookup) 1938 // -- a template-id that is dependent, 1939 // (note: handled in BuildTemplateIdExpr) 1940 // -- a conversion-function-id that specifies a dependent type, 1941 // -- a nested-name-specifier that contains a class-name that 1942 // names a dependent type. 1943 // Determine whether this is a member of an unknown specialization; 1944 // we need to handle these differently. 1945 bool DependentID = false; 1946 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 1947 Name.getCXXNameType()->isDependentType()) { 1948 DependentID = true; 1949 } else if (SS.isSet()) { 1950 if (DeclContext *DC = computeDeclContext(SS, false)) { 1951 if (RequireCompleteDeclContext(SS, DC)) 1952 return ExprError(); 1953 } else { 1954 DependentID = true; 1955 } 1956 } 1957 1958 if (DependentID) 1959 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1960 IsAddressOfOperand, TemplateArgs); 1961 1962 // Perform the required lookup. 1963 LookupResult R(*this, NameInfo, 1964 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 1965 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 1966 if (TemplateArgs) { 1967 // Lookup the template name again to correctly establish the context in 1968 // which it was found. This is really unfortunate as we already did the 1969 // lookup to determine that it was a template name in the first place. If 1970 // this becomes a performance hit, we can work harder to preserve those 1971 // results until we get here but it's likely not worth it. 1972 bool MemberOfUnknownSpecialization; 1973 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 1974 MemberOfUnknownSpecialization); 1975 1976 if (MemberOfUnknownSpecialization || 1977 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 1978 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1979 IsAddressOfOperand, TemplateArgs); 1980 } else { 1981 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 1982 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 1983 1984 // If the result might be in a dependent base class, this is a dependent 1985 // id-expression. 1986 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 1987 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1988 IsAddressOfOperand, TemplateArgs); 1989 1990 // If this reference is in an Objective-C method, then we need to do 1991 // some special Objective-C lookup, too. 1992 if (IvarLookupFollowUp) { 1993 ExprResult E(LookupInObjCMethod(R, S, II, true)); 1994 if (E.isInvalid()) 1995 return ExprError(); 1996 1997 if (Expr *Ex = E.takeAs<Expr>()) 1998 return Owned(Ex); 1999 } 2000 } 2001 2002 if (R.isAmbiguous()) 2003 return ExprError(); 2004 2005 // Determine whether this name might be a candidate for 2006 // argument-dependent lookup. 2007 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2008 2009 if (R.empty() && !ADL) { 2010 2011 // Otherwise, this could be an implicitly declared function reference (legal 2012 // in C90, extension in C99, forbidden in C++). 2013 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2014 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2015 if (D) R.addDecl(D); 2016 } 2017 2018 // If this name wasn't predeclared and if this is not a function 2019 // call, diagnose the problem. 2020 if (R.empty()) { 2021 // In Microsoft mode, if we are inside a template class member function 2022 // whose parent class has dependent base classes, and we can't resolve 2023 // an identifier, then assume the identifier is a member of a dependent 2024 // base class. The goal is to postpone name lookup to instantiation time 2025 // to be able to search into the type dependent base classes. 2026 // FIXME: If we want 100% compatibility with MSVC, we will have delay all 2027 // unqualified name lookup. Any name lookup during template parsing means 2028 // clang might find something that MSVC doesn't. For now, we only handle 2029 // the common case of members of a dependent base class. 2030 if (getLangOpts().MicrosoftMode) { 2031 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext); 2032 if (MD && MD->isInstance() && MD->getParent()->hasAnyDependentBases()) { 2033 assert(SS.isEmpty() && "qualifiers should be already handled"); 2034 QualType ThisType = MD->getThisType(Context); 2035 // Since the 'this' expression is synthesized, we don't need to 2036 // perform the double-lookup check. 2037 NamedDecl *FirstQualifierInScope = 0; 2038 return Owned(CXXDependentScopeMemberExpr::Create( 2039 Context, /*This=*/0, ThisType, /*IsArrow=*/true, 2040 /*Op=*/SourceLocation(), SS.getWithLocInContext(Context), 2041 TemplateKWLoc, FirstQualifierInScope, NameInfo, TemplateArgs)); 2042 } 2043 } 2044 2045 // Don't diagnose an empty lookup for inline assmebly. 2046 if (IsInlineAsmIdentifier) 2047 return ExprError(); 2048 2049 CorrectionCandidateCallback DefaultValidator; 2050 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator)) 2051 return ExprError(); 2052 2053 assert(!R.empty() && 2054 "DiagnoseEmptyLookup returned false but added no results"); 2055 2056 // If we found an Objective-C instance variable, let 2057 // LookupInObjCMethod build the appropriate expression to 2058 // reference the ivar. 2059 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2060 R.clear(); 2061 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2062 // In a hopelessly buggy code, Objective-C instance variable 2063 // lookup fails and no expression will be built to reference it. 2064 if (!E.isInvalid() && !E.get()) 2065 return ExprError(); 2066 return E; 2067 } 2068 } 2069 } 2070 2071 // This is guaranteed from this point on. 2072 assert(!R.empty() || ADL); 2073 2074 // Check whether this might be a C++ implicit instance member access. 2075 // C++ [class.mfct.non-static]p3: 2076 // When an id-expression that is not part of a class member access 2077 // syntax and not used to form a pointer to member is used in the 2078 // body of a non-static member function of class X, if name lookup 2079 // resolves the name in the id-expression to a non-static non-type 2080 // member of some class C, the id-expression is transformed into a 2081 // class member access expression using (*this) as the 2082 // postfix-expression to the left of the . operator. 2083 // 2084 // But we don't actually need to do this for '&' operands if R 2085 // resolved to a function or overloaded function set, because the 2086 // expression is ill-formed if it actually works out to be a 2087 // non-static member function: 2088 // 2089 // C++ [expr.ref]p4: 2090 // Otherwise, if E1.E2 refers to a non-static member function. . . 2091 // [t]he expression can be used only as the left-hand operand of a 2092 // member function call. 2093 // 2094 // There are other safeguards against such uses, but it's important 2095 // to get this right here so that we don't end up making a 2096 // spuriously dependent expression if we're inside a dependent 2097 // instance method. 2098 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2099 bool MightBeImplicitMember; 2100 if (!IsAddressOfOperand) 2101 MightBeImplicitMember = true; 2102 else if (!SS.isEmpty()) 2103 MightBeImplicitMember = false; 2104 else if (R.isOverloadedResult()) 2105 MightBeImplicitMember = false; 2106 else if (R.isUnresolvableResult()) 2107 MightBeImplicitMember = true; 2108 else 2109 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2110 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2111 isa<MSPropertyDecl>(R.getFoundDecl()); 2112 2113 if (MightBeImplicitMember) 2114 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2115 R, TemplateArgs); 2116 } 2117 2118 if (TemplateArgs || TemplateKWLoc.isValid()) { 2119 2120 // In C++1y, if this is a variable template id, then check it 2121 // in BuildTemplateIdExpr(). 2122 // The single lookup result must be a variable template declaration. 2123 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2124 Id.TemplateId->Kind == TNK_Var_template) { 2125 assert(R.getAsSingle<VarTemplateDecl>() && 2126 "There should only be one declaration found."); 2127 } 2128 2129 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2130 } 2131 2132 return BuildDeclarationNameExpr(SS, R, ADL); 2133} 2134 2135/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2136/// declaration name, generally during template instantiation. 2137/// There's a large number of things which don't need to be done along 2138/// this path. 2139ExprResult 2140Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 2141 const DeclarationNameInfo &NameInfo, 2142 bool IsAddressOfOperand) { 2143 DeclContext *DC = computeDeclContext(SS, false); 2144 if (!DC) 2145 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2146 NameInfo, /*TemplateArgs=*/0); 2147 2148 if (RequireCompleteDeclContext(SS, DC)) 2149 return ExprError(); 2150 2151 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2152 LookupQualifiedName(R, DC); 2153 2154 if (R.isAmbiguous()) 2155 return ExprError(); 2156 2157 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2158 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2159 NameInfo, /*TemplateArgs=*/0); 2160 2161 if (R.empty()) { 2162 Diag(NameInfo.getLoc(), diag::err_no_member) 2163 << NameInfo.getName() << DC << SS.getRange(); 2164 return ExprError(); 2165 } 2166 2167 // Defend against this resolving to an implicit member access. We usually 2168 // won't get here if this might be a legitimate a class member (we end up in 2169 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2170 // a pointer-to-member or in an unevaluated context in C++11. 2171 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2172 return BuildPossibleImplicitMemberExpr(SS, 2173 /*TemplateKWLoc=*/SourceLocation(), 2174 R, /*TemplateArgs=*/0); 2175 2176 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2177} 2178 2179/// LookupInObjCMethod - The parser has read a name in, and Sema has 2180/// detected that we're currently inside an ObjC method. Perform some 2181/// additional lookup. 2182/// 2183/// Ideally, most of this would be done by lookup, but there's 2184/// actually quite a lot of extra work involved. 2185/// 2186/// Returns a null sentinel to indicate trivial success. 2187ExprResult 2188Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2189 IdentifierInfo *II, bool AllowBuiltinCreation) { 2190 SourceLocation Loc = Lookup.getNameLoc(); 2191 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2192 2193 // Check for error condition which is already reported. 2194 if (!CurMethod) 2195 return ExprError(); 2196 2197 // There are two cases to handle here. 1) scoped lookup could have failed, 2198 // in which case we should look for an ivar. 2) scoped lookup could have 2199 // found a decl, but that decl is outside the current instance method (i.e. 2200 // a global variable). In these two cases, we do a lookup for an ivar with 2201 // this name, if the lookup sucedes, we replace it our current decl. 2202 2203 // If we're in a class method, we don't normally want to look for 2204 // ivars. But if we don't find anything else, and there's an 2205 // ivar, that's an error. 2206 bool IsClassMethod = CurMethod->isClassMethod(); 2207 2208 bool LookForIvars; 2209 if (Lookup.empty()) 2210 LookForIvars = true; 2211 else if (IsClassMethod) 2212 LookForIvars = false; 2213 else 2214 LookForIvars = (Lookup.isSingleResult() && 2215 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2216 ObjCInterfaceDecl *IFace = 0; 2217 if (LookForIvars) { 2218 IFace = CurMethod->getClassInterface(); 2219 ObjCInterfaceDecl *ClassDeclared; 2220 ObjCIvarDecl *IV = 0; 2221 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2222 // Diagnose using an ivar in a class method. 2223 if (IsClassMethod) 2224 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2225 << IV->getDeclName()); 2226 2227 // If we're referencing an invalid decl, just return this as a silent 2228 // error node. The error diagnostic was already emitted on the decl. 2229 if (IV->isInvalidDecl()) 2230 return ExprError(); 2231 2232 // Check if referencing a field with __attribute__((deprecated)). 2233 if (DiagnoseUseOfDecl(IV, Loc)) 2234 return ExprError(); 2235 2236 // Diagnose the use of an ivar outside of the declaring class. 2237 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2238 !declaresSameEntity(ClassDeclared, IFace) && 2239 !getLangOpts().DebuggerSupport) 2240 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2241 2242 // FIXME: This should use a new expr for a direct reference, don't 2243 // turn this into Self->ivar, just return a BareIVarExpr or something. 2244 IdentifierInfo &II = Context.Idents.get("self"); 2245 UnqualifiedId SelfName; 2246 SelfName.setIdentifier(&II, SourceLocation()); 2247 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2248 CXXScopeSpec SelfScopeSpec; 2249 SourceLocation TemplateKWLoc; 2250 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2251 SelfName, false, false); 2252 if (SelfExpr.isInvalid()) 2253 return ExprError(); 2254 2255 SelfExpr = DefaultLvalueConversion(SelfExpr.take()); 2256 if (SelfExpr.isInvalid()) 2257 return ExprError(); 2258 2259 MarkAnyDeclReferenced(Loc, IV, true); 2260 // Mark this ivar 'referenced' in this method, if it is a backing ivar 2261 // of a property and current method is one of its property accessor. 2262 const ObjCPropertyDecl *PDecl; 2263 const ObjCIvarDecl *BIV = GetIvarBackingPropertyAccessor(CurMethod, PDecl); 2264 if (BIV && BIV == IV) 2265 IV->setBackingIvarReferencedInAccessor(true); 2266 2267 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2268 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2269 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2270 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2271 2272 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(), 2273 Loc, IV->getLocation(), 2274 SelfExpr.take(), 2275 true, true); 2276 2277 if (getLangOpts().ObjCAutoRefCount) { 2278 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2279 DiagnosticsEngine::Level Level = 2280 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc); 2281 if (Level != DiagnosticsEngine::Ignored) 2282 recordUseOfEvaluatedWeak(Result); 2283 } 2284 if (CurContext->isClosure()) 2285 Diag(Loc, diag::warn_implicitly_retains_self) 2286 << FixItHint::CreateInsertion(Loc, "self->"); 2287 } 2288 2289 return Owned(Result); 2290 } 2291 } else if (CurMethod->isInstanceMethod()) { 2292 // We should warn if a local variable hides an ivar. 2293 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2294 ObjCInterfaceDecl *ClassDeclared; 2295 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2296 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2297 declaresSameEntity(IFace, ClassDeclared)) 2298 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2299 } 2300 } 2301 } else if (Lookup.isSingleResult() && 2302 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2303 // If accessing a stand-alone ivar in a class method, this is an error. 2304 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2305 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2306 << IV->getDeclName()); 2307 } 2308 2309 if (Lookup.empty() && II && AllowBuiltinCreation) { 2310 // FIXME. Consolidate this with similar code in LookupName. 2311 if (unsigned BuiltinID = II->getBuiltinID()) { 2312 if (!(getLangOpts().CPlusPlus && 2313 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2314 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2315 S, Lookup.isForRedeclaration(), 2316 Lookup.getNameLoc()); 2317 if (D) Lookup.addDecl(D); 2318 } 2319 } 2320 } 2321 // Sentinel value saying that we didn't do anything special. 2322 return Owned((Expr*) 0); 2323} 2324 2325/// \brief Cast a base object to a member's actual type. 2326/// 2327/// Logically this happens in three phases: 2328/// 2329/// * First we cast from the base type to the naming class. 2330/// The naming class is the class into which we were looking 2331/// when we found the member; it's the qualifier type if a 2332/// qualifier was provided, and otherwise it's the base type. 2333/// 2334/// * Next we cast from the naming class to the declaring class. 2335/// If the member we found was brought into a class's scope by 2336/// a using declaration, this is that class; otherwise it's 2337/// the class declaring the member. 2338/// 2339/// * Finally we cast from the declaring class to the "true" 2340/// declaring class of the member. This conversion does not 2341/// obey access control. 2342ExprResult 2343Sema::PerformObjectMemberConversion(Expr *From, 2344 NestedNameSpecifier *Qualifier, 2345 NamedDecl *FoundDecl, 2346 NamedDecl *Member) { 2347 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2348 if (!RD) 2349 return Owned(From); 2350 2351 QualType DestRecordType; 2352 QualType DestType; 2353 QualType FromRecordType; 2354 QualType FromType = From->getType(); 2355 bool PointerConversions = false; 2356 if (isa<FieldDecl>(Member)) { 2357 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2358 2359 if (FromType->getAs<PointerType>()) { 2360 DestType = Context.getPointerType(DestRecordType); 2361 FromRecordType = FromType->getPointeeType(); 2362 PointerConversions = true; 2363 } else { 2364 DestType = DestRecordType; 2365 FromRecordType = FromType; 2366 } 2367 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2368 if (Method->isStatic()) 2369 return Owned(From); 2370 2371 DestType = Method->getThisType(Context); 2372 DestRecordType = DestType->getPointeeType(); 2373 2374 if (FromType->getAs<PointerType>()) { 2375 FromRecordType = FromType->getPointeeType(); 2376 PointerConversions = true; 2377 } else { 2378 FromRecordType = FromType; 2379 DestType = DestRecordType; 2380 } 2381 } else { 2382 // No conversion necessary. 2383 return Owned(From); 2384 } 2385 2386 if (DestType->isDependentType() || FromType->isDependentType()) 2387 return Owned(From); 2388 2389 // If the unqualified types are the same, no conversion is necessary. 2390 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2391 return Owned(From); 2392 2393 SourceRange FromRange = From->getSourceRange(); 2394 SourceLocation FromLoc = FromRange.getBegin(); 2395 2396 ExprValueKind VK = From->getValueKind(); 2397 2398 // C++ [class.member.lookup]p8: 2399 // [...] Ambiguities can often be resolved by qualifying a name with its 2400 // class name. 2401 // 2402 // If the member was a qualified name and the qualified referred to a 2403 // specific base subobject type, we'll cast to that intermediate type 2404 // first and then to the object in which the member is declared. That allows 2405 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2406 // 2407 // class Base { public: int x; }; 2408 // class Derived1 : public Base { }; 2409 // class Derived2 : public Base { }; 2410 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2411 // 2412 // void VeryDerived::f() { 2413 // x = 17; // error: ambiguous base subobjects 2414 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2415 // } 2416 if (Qualifier && Qualifier->getAsType()) { 2417 QualType QType = QualType(Qualifier->getAsType(), 0); 2418 assert(QType->isRecordType() && "lookup done with non-record type"); 2419 2420 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2421 2422 // In C++98, the qualifier type doesn't actually have to be a base 2423 // type of the object type, in which case we just ignore it. 2424 // Otherwise build the appropriate casts. 2425 if (IsDerivedFrom(FromRecordType, QRecordType)) { 2426 CXXCastPath BasePath; 2427 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2428 FromLoc, FromRange, &BasePath)) 2429 return ExprError(); 2430 2431 if (PointerConversions) 2432 QType = Context.getPointerType(QType); 2433 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2434 VK, &BasePath).take(); 2435 2436 FromType = QType; 2437 FromRecordType = QRecordType; 2438 2439 // If the qualifier type was the same as the destination type, 2440 // we're done. 2441 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2442 return Owned(From); 2443 } 2444 } 2445 2446 bool IgnoreAccess = false; 2447 2448 // If we actually found the member through a using declaration, cast 2449 // down to the using declaration's type. 2450 // 2451 // Pointer equality is fine here because only one declaration of a 2452 // class ever has member declarations. 2453 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2454 assert(isa<UsingShadowDecl>(FoundDecl)); 2455 QualType URecordType = Context.getTypeDeclType( 2456 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2457 2458 // We only need to do this if the naming-class to declaring-class 2459 // conversion is non-trivial. 2460 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2461 assert(IsDerivedFrom(FromRecordType, URecordType)); 2462 CXXCastPath BasePath; 2463 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2464 FromLoc, FromRange, &BasePath)) 2465 return ExprError(); 2466 2467 QualType UType = URecordType; 2468 if (PointerConversions) 2469 UType = Context.getPointerType(UType); 2470 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2471 VK, &BasePath).take(); 2472 FromType = UType; 2473 FromRecordType = URecordType; 2474 } 2475 2476 // We don't do access control for the conversion from the 2477 // declaring class to the true declaring class. 2478 IgnoreAccess = true; 2479 } 2480 2481 CXXCastPath BasePath; 2482 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2483 FromLoc, FromRange, &BasePath, 2484 IgnoreAccess)) 2485 return ExprError(); 2486 2487 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2488 VK, &BasePath); 2489} 2490 2491bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2492 const LookupResult &R, 2493 bool HasTrailingLParen) { 2494 // Only when used directly as the postfix-expression of a call. 2495 if (!HasTrailingLParen) 2496 return false; 2497 2498 // Never if a scope specifier was provided. 2499 if (SS.isSet()) 2500 return false; 2501 2502 // Only in C++ or ObjC++. 2503 if (!getLangOpts().CPlusPlus) 2504 return false; 2505 2506 // Turn off ADL when we find certain kinds of declarations during 2507 // normal lookup: 2508 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2509 NamedDecl *D = *I; 2510 2511 // C++0x [basic.lookup.argdep]p3: 2512 // -- a declaration of a class member 2513 // Since using decls preserve this property, we check this on the 2514 // original decl. 2515 if (D->isCXXClassMember()) 2516 return false; 2517 2518 // C++0x [basic.lookup.argdep]p3: 2519 // -- a block-scope function declaration that is not a 2520 // using-declaration 2521 // NOTE: we also trigger this for function templates (in fact, we 2522 // don't check the decl type at all, since all other decl types 2523 // turn off ADL anyway). 2524 if (isa<UsingShadowDecl>(D)) 2525 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2526 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2527 return false; 2528 2529 // C++0x [basic.lookup.argdep]p3: 2530 // -- a declaration that is neither a function or a function 2531 // template 2532 // And also for builtin functions. 2533 if (isa<FunctionDecl>(D)) { 2534 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2535 2536 // But also builtin functions. 2537 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2538 return false; 2539 } else if (!isa<FunctionTemplateDecl>(D)) 2540 return false; 2541 } 2542 2543 return true; 2544} 2545 2546 2547/// Diagnoses obvious problems with the use of the given declaration 2548/// as an expression. This is only actually called for lookups that 2549/// were not overloaded, and it doesn't promise that the declaration 2550/// will in fact be used. 2551static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2552 if (isa<TypedefNameDecl>(D)) { 2553 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2554 return true; 2555 } 2556 2557 if (isa<ObjCInterfaceDecl>(D)) { 2558 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2559 return true; 2560 } 2561 2562 if (isa<NamespaceDecl>(D)) { 2563 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2564 return true; 2565 } 2566 2567 return false; 2568} 2569 2570ExprResult 2571Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2572 LookupResult &R, 2573 bool NeedsADL) { 2574 // If this is a single, fully-resolved result and we don't need ADL, 2575 // just build an ordinary singleton decl ref. 2576 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2577 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2578 R.getRepresentativeDecl()); 2579 2580 // We only need to check the declaration if there's exactly one 2581 // result, because in the overloaded case the results can only be 2582 // functions and function templates. 2583 if (R.isSingleResult() && 2584 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2585 return ExprError(); 2586 2587 // Otherwise, just build an unresolved lookup expression. Suppress 2588 // any lookup-related diagnostics; we'll hash these out later, when 2589 // we've picked a target. 2590 R.suppressDiagnostics(); 2591 2592 UnresolvedLookupExpr *ULE 2593 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2594 SS.getWithLocInContext(Context), 2595 R.getLookupNameInfo(), 2596 NeedsADL, R.isOverloadedResult(), 2597 R.begin(), R.end()); 2598 2599 return Owned(ULE); 2600} 2601 2602/// \brief Complete semantic analysis for a reference to the given declaration. 2603ExprResult Sema::BuildDeclarationNameExpr( 2604 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2605 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs) { 2606 assert(D && "Cannot refer to a NULL declaration"); 2607 assert(!isa<FunctionTemplateDecl>(D) && 2608 "Cannot refer unambiguously to a function template"); 2609 2610 SourceLocation Loc = NameInfo.getLoc(); 2611 if (CheckDeclInExpr(*this, Loc, D)) 2612 return ExprError(); 2613 2614 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2615 // Specifically diagnose references to class templates that are missing 2616 // a template argument list. 2617 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2618 << Template << SS.getRange(); 2619 Diag(Template->getLocation(), diag::note_template_decl_here); 2620 return ExprError(); 2621 } 2622 2623 // Make sure that we're referring to a value. 2624 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2625 if (!VD) { 2626 Diag(Loc, diag::err_ref_non_value) 2627 << D << SS.getRange(); 2628 Diag(D->getLocation(), diag::note_declared_at); 2629 return ExprError(); 2630 } 2631 2632 // Check whether this declaration can be used. Note that we suppress 2633 // this check when we're going to perform argument-dependent lookup 2634 // on this function name, because this might not be the function 2635 // that overload resolution actually selects. 2636 if (DiagnoseUseOfDecl(VD, Loc)) 2637 return ExprError(); 2638 2639 // Only create DeclRefExpr's for valid Decl's. 2640 if (VD->isInvalidDecl()) 2641 return ExprError(); 2642 2643 // Handle members of anonymous structs and unions. If we got here, 2644 // and the reference is to a class member indirect field, then this 2645 // must be the subject of a pointer-to-member expression. 2646 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2647 if (!indirectField->isCXXClassMember()) 2648 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2649 indirectField); 2650 2651 { 2652 QualType type = VD->getType(); 2653 ExprValueKind valueKind = VK_RValue; 2654 2655 switch (D->getKind()) { 2656 // Ignore all the non-ValueDecl kinds. 2657#define ABSTRACT_DECL(kind) 2658#define VALUE(type, base) 2659#define DECL(type, base) \ 2660 case Decl::type: 2661#include "clang/AST/DeclNodes.inc" 2662 llvm_unreachable("invalid value decl kind"); 2663 2664 // These shouldn't make it here. 2665 case Decl::ObjCAtDefsField: 2666 case Decl::ObjCIvar: 2667 llvm_unreachable("forming non-member reference to ivar?"); 2668 2669 // Enum constants are always r-values and never references. 2670 // Unresolved using declarations are dependent. 2671 case Decl::EnumConstant: 2672 case Decl::UnresolvedUsingValue: 2673 valueKind = VK_RValue; 2674 break; 2675 2676 // Fields and indirect fields that got here must be for 2677 // pointer-to-member expressions; we just call them l-values for 2678 // internal consistency, because this subexpression doesn't really 2679 // exist in the high-level semantics. 2680 case Decl::Field: 2681 case Decl::IndirectField: 2682 assert(getLangOpts().CPlusPlus && 2683 "building reference to field in C?"); 2684 2685 // These can't have reference type in well-formed programs, but 2686 // for internal consistency we do this anyway. 2687 type = type.getNonReferenceType(); 2688 valueKind = VK_LValue; 2689 break; 2690 2691 // Non-type template parameters are either l-values or r-values 2692 // depending on the type. 2693 case Decl::NonTypeTemplateParm: { 2694 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2695 type = reftype->getPointeeType(); 2696 valueKind = VK_LValue; // even if the parameter is an r-value reference 2697 break; 2698 } 2699 2700 // For non-references, we need to strip qualifiers just in case 2701 // the template parameter was declared as 'const int' or whatever. 2702 valueKind = VK_RValue; 2703 type = type.getUnqualifiedType(); 2704 break; 2705 } 2706 2707 case Decl::Var: 2708 case Decl::VarTemplateSpecialization: 2709 case Decl::VarTemplatePartialSpecialization: 2710 // In C, "extern void blah;" is valid and is an r-value. 2711 if (!getLangOpts().CPlusPlus && 2712 !type.hasQualifiers() && 2713 type->isVoidType()) { 2714 valueKind = VK_RValue; 2715 break; 2716 } 2717 // fallthrough 2718 2719 case Decl::ImplicitParam: 2720 case Decl::ParmVar: { 2721 // These are always l-values. 2722 valueKind = VK_LValue; 2723 type = type.getNonReferenceType(); 2724 2725 // FIXME: Does the addition of const really only apply in 2726 // potentially-evaluated contexts? Since the variable isn't actually 2727 // captured in an unevaluated context, it seems that the answer is no. 2728 if (!isUnevaluatedContext()) { 2729 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2730 if (!CapturedType.isNull()) 2731 type = CapturedType; 2732 } 2733 2734 break; 2735 } 2736 2737 case Decl::Function: { 2738 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2739 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2740 type = Context.BuiltinFnTy; 2741 valueKind = VK_RValue; 2742 break; 2743 } 2744 } 2745 2746 const FunctionType *fty = type->castAs<FunctionType>(); 2747 2748 // If we're referring to a function with an __unknown_anytype 2749 // result type, make the entire expression __unknown_anytype. 2750 if (fty->getResultType() == Context.UnknownAnyTy) { 2751 type = Context.UnknownAnyTy; 2752 valueKind = VK_RValue; 2753 break; 2754 } 2755 2756 // Functions are l-values in C++. 2757 if (getLangOpts().CPlusPlus) { 2758 valueKind = VK_LValue; 2759 break; 2760 } 2761 2762 // C99 DR 316 says that, if a function type comes from a 2763 // function definition (without a prototype), that type is only 2764 // used for checking compatibility. Therefore, when referencing 2765 // the function, we pretend that we don't have the full function 2766 // type. 2767 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2768 isa<FunctionProtoType>(fty)) 2769 type = Context.getFunctionNoProtoType(fty->getResultType(), 2770 fty->getExtInfo()); 2771 2772 // Functions are r-values in C. 2773 valueKind = VK_RValue; 2774 break; 2775 } 2776 2777 case Decl::MSProperty: 2778 valueKind = VK_LValue; 2779 break; 2780 2781 case Decl::CXXMethod: 2782 // If we're referring to a method with an __unknown_anytype 2783 // result type, make the entire expression __unknown_anytype. 2784 // This should only be possible with a type written directly. 2785 if (const FunctionProtoType *proto 2786 = dyn_cast<FunctionProtoType>(VD->getType())) 2787 if (proto->getResultType() == Context.UnknownAnyTy) { 2788 type = Context.UnknownAnyTy; 2789 valueKind = VK_RValue; 2790 break; 2791 } 2792 2793 // C++ methods are l-values if static, r-values if non-static. 2794 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2795 valueKind = VK_LValue; 2796 break; 2797 } 2798 // fallthrough 2799 2800 case Decl::CXXConversion: 2801 case Decl::CXXDestructor: 2802 case Decl::CXXConstructor: 2803 valueKind = VK_RValue; 2804 break; 2805 } 2806 2807 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 2808 TemplateArgs); 2809 } 2810} 2811 2812ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 2813 PredefinedExpr::IdentType IT) { 2814 // Pick the current block, lambda, captured statement or function. 2815 Decl *currentDecl = 0; 2816 if (const BlockScopeInfo *BSI = getCurBlock()) 2817 currentDecl = BSI->TheDecl; 2818 else if (const LambdaScopeInfo *LSI = getCurLambda()) 2819 currentDecl = LSI->CallOperator; 2820 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 2821 currentDecl = CSI->TheCapturedDecl; 2822 else 2823 currentDecl = getCurFunctionOrMethodDecl(); 2824 2825 if (!currentDecl) { 2826 Diag(Loc, diag::ext_predef_outside_function); 2827 currentDecl = Context.getTranslationUnitDecl(); 2828 } 2829 2830 QualType ResTy; 2831 if (cast<DeclContext>(currentDecl)->isDependentContext()) 2832 ResTy = Context.DependentTy; 2833 else { 2834 // Pre-defined identifiers are of type char[x], where x is the length of 2835 // the string. 2836 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length(); 2837 2838 llvm::APInt LengthI(32, Length + 1); 2839 if (IT == PredefinedExpr::LFunction) 2840 ResTy = Context.WideCharTy.withConst(); 2841 else 2842 ResTy = Context.CharTy.withConst(); 2843 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); 2844 } 2845 2846 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT)); 2847} 2848 2849ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 2850 PredefinedExpr::IdentType IT; 2851 2852 switch (Kind) { 2853 default: llvm_unreachable("Unknown simple primary expr!"); 2854 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 2855 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 2856 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 2857 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 2858 } 2859 2860 return BuildPredefinedExpr(Loc, IT); 2861} 2862 2863ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 2864 SmallString<16> CharBuffer; 2865 bool Invalid = false; 2866 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 2867 if (Invalid) 2868 return ExprError(); 2869 2870 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 2871 PP, Tok.getKind()); 2872 if (Literal.hadError()) 2873 return ExprError(); 2874 2875 QualType Ty; 2876 if (Literal.isWide()) 2877 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 2878 else if (Literal.isUTF16()) 2879 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 2880 else if (Literal.isUTF32()) 2881 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 2882 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 2883 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 2884 else 2885 Ty = Context.CharTy; // 'x' -> char in C++ 2886 2887 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 2888 if (Literal.isWide()) 2889 Kind = CharacterLiteral::Wide; 2890 else if (Literal.isUTF16()) 2891 Kind = CharacterLiteral::UTF16; 2892 else if (Literal.isUTF32()) 2893 Kind = CharacterLiteral::UTF32; 2894 2895 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 2896 Tok.getLocation()); 2897 2898 if (Literal.getUDSuffix().empty()) 2899 return Owned(Lit); 2900 2901 // We're building a user-defined literal. 2902 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 2903 SourceLocation UDSuffixLoc = 2904 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 2905 2906 // Make sure we're allowed user-defined literals here. 2907 if (!UDLScope) 2908 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 2909 2910 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 2911 // operator "" X (ch) 2912 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 2913 Lit, Tok.getLocation()); 2914} 2915 2916ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 2917 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 2918 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 2919 Context.IntTy, Loc)); 2920} 2921 2922static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 2923 QualType Ty, SourceLocation Loc) { 2924 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 2925 2926 using llvm::APFloat; 2927 APFloat Val(Format); 2928 2929 APFloat::opStatus result = Literal.GetFloatValue(Val); 2930 2931 // Overflow is always an error, but underflow is only an error if 2932 // we underflowed to zero (APFloat reports denormals as underflow). 2933 if ((result & APFloat::opOverflow) || 2934 ((result & APFloat::opUnderflow) && Val.isZero())) { 2935 unsigned diagnostic; 2936 SmallString<20> buffer; 2937 if (result & APFloat::opOverflow) { 2938 diagnostic = diag::warn_float_overflow; 2939 APFloat::getLargest(Format).toString(buffer); 2940 } else { 2941 diagnostic = diag::warn_float_underflow; 2942 APFloat::getSmallest(Format).toString(buffer); 2943 } 2944 2945 S.Diag(Loc, diagnostic) 2946 << Ty 2947 << StringRef(buffer.data(), buffer.size()); 2948 } 2949 2950 bool isExact = (result == APFloat::opOK); 2951 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 2952} 2953 2954ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 2955 // Fast path for a single digit (which is quite common). A single digit 2956 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 2957 if (Tok.getLength() == 1) { 2958 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 2959 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 2960 } 2961 2962 SmallString<128> SpellingBuffer; 2963 // NumericLiteralParser wants to overread by one character. Add padding to 2964 // the buffer in case the token is copied to the buffer. If getSpelling() 2965 // returns a StringRef to the memory buffer, it should have a null char at 2966 // the EOF, so it is also safe. 2967 SpellingBuffer.resize(Tok.getLength() + 1); 2968 2969 // Get the spelling of the token, which eliminates trigraphs, etc. 2970 bool Invalid = false; 2971 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 2972 if (Invalid) 2973 return ExprError(); 2974 2975 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 2976 if (Literal.hadError) 2977 return ExprError(); 2978 2979 if (Literal.hasUDSuffix()) { 2980 // We're building a user-defined literal. 2981 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 2982 SourceLocation UDSuffixLoc = 2983 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 2984 2985 // Make sure we're allowed user-defined literals here. 2986 if (!UDLScope) 2987 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 2988 2989 QualType CookedTy; 2990 if (Literal.isFloatingLiteral()) { 2991 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 2992 // long double, the literal is treated as a call of the form 2993 // operator "" X (f L) 2994 CookedTy = Context.LongDoubleTy; 2995 } else { 2996 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 2997 // unsigned long long, the literal is treated as a call of the form 2998 // operator "" X (n ULL) 2999 CookedTy = Context.UnsignedLongLongTy; 3000 } 3001 3002 DeclarationName OpName = 3003 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3004 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3005 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3006 3007 SourceLocation TokLoc = Tok.getLocation(); 3008 3009 // Perform literal operator lookup to determine if we're building a raw 3010 // literal or a cooked one. 3011 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3012 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3013 /*AllowRaw*/true, /*AllowTemplate*/true, 3014 /*AllowStringTemplate*/false)) { 3015 case LOLR_Error: 3016 return ExprError(); 3017 3018 case LOLR_Cooked: { 3019 Expr *Lit; 3020 if (Literal.isFloatingLiteral()) { 3021 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3022 } else { 3023 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3024 if (Literal.GetIntegerValue(ResultVal)) 3025 Diag(Tok.getLocation(), diag::err_integer_too_large); 3026 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3027 Tok.getLocation()); 3028 } 3029 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3030 } 3031 3032 case LOLR_Raw: { 3033 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3034 // literal is treated as a call of the form 3035 // operator "" X ("n") 3036 unsigned Length = Literal.getUDSuffixOffset(); 3037 QualType StrTy = Context.getConstantArrayType( 3038 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3039 ArrayType::Normal, 0); 3040 Expr *Lit = StringLiteral::Create( 3041 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3042 /*Pascal*/false, StrTy, &TokLoc, 1); 3043 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3044 } 3045 3046 case LOLR_Template: { 3047 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3048 // template), L is treated as a call fo the form 3049 // operator "" X <'c1', 'c2', ... 'ck'>() 3050 // where n is the source character sequence c1 c2 ... ck. 3051 TemplateArgumentListInfo ExplicitArgs; 3052 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3053 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3054 llvm::APSInt Value(CharBits, CharIsUnsigned); 3055 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3056 Value = TokSpelling[I]; 3057 TemplateArgument Arg(Context, Value, Context.CharTy); 3058 TemplateArgumentLocInfo ArgInfo; 3059 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3060 } 3061 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3062 &ExplicitArgs); 3063 } 3064 case LOLR_StringTemplate: 3065 llvm_unreachable("unexpected literal operator lookup result"); 3066 } 3067 } 3068 3069 Expr *Res; 3070 3071 if (Literal.isFloatingLiteral()) { 3072 QualType Ty; 3073 if (Literal.isFloat) 3074 Ty = Context.FloatTy; 3075 else if (!Literal.isLong) 3076 Ty = Context.DoubleTy; 3077 else 3078 Ty = Context.LongDoubleTy; 3079 3080 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3081 3082 if (Ty == Context.DoubleTy) { 3083 if (getLangOpts().SinglePrecisionConstants) { 3084 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 3085 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) { 3086 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3087 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 3088 } 3089 } 3090 } else if (!Literal.isIntegerLiteral()) { 3091 return ExprError(); 3092 } else { 3093 QualType Ty; 3094 3095 // 'long long' is a C99 or C++11 feature. 3096 if (!getLangOpts().C99 && Literal.isLongLong) { 3097 if (getLangOpts().CPlusPlus) 3098 Diag(Tok.getLocation(), 3099 getLangOpts().CPlusPlus11 ? 3100 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3101 else 3102 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3103 } 3104 3105 // Get the value in the widest-possible width. 3106 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3107 // The microsoft literal suffix extensions support 128-bit literals, which 3108 // may be wider than [u]intmax_t. 3109 // FIXME: Actually, they don't. We seem to have accidentally invented the 3110 // i128 suffix. 3111 if (Literal.isMicrosoftInteger && MaxWidth < 128 && 3112 PP.getTargetInfo().hasInt128Type()) 3113 MaxWidth = 128; 3114 llvm::APInt ResultVal(MaxWidth, 0); 3115 3116 if (Literal.GetIntegerValue(ResultVal)) { 3117 // If this value didn't fit into uintmax_t, error and force to ull. 3118 Diag(Tok.getLocation(), diag::err_integer_too_large); 3119 Ty = Context.UnsignedLongLongTy; 3120 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3121 "long long is not intmax_t?"); 3122 } else { 3123 // If this value fits into a ULL, try to figure out what else it fits into 3124 // according to the rules of C99 6.4.4.1p5. 3125 3126 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3127 // be an unsigned int. 3128 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3129 3130 // Check from smallest to largest, picking the smallest type we can. 3131 unsigned Width = 0; 3132 if (!Literal.isLong && !Literal.isLongLong) { 3133 // Are int/unsigned possibilities? 3134 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3135 3136 // Does it fit in a unsigned int? 3137 if (ResultVal.isIntN(IntSize)) { 3138 // Does it fit in a signed int? 3139 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3140 Ty = Context.IntTy; 3141 else if (AllowUnsigned) 3142 Ty = Context.UnsignedIntTy; 3143 Width = IntSize; 3144 } 3145 } 3146 3147 // Are long/unsigned long possibilities? 3148 if (Ty.isNull() && !Literal.isLongLong) { 3149 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3150 3151 // Does it fit in a unsigned long? 3152 if (ResultVal.isIntN(LongSize)) { 3153 // Does it fit in a signed long? 3154 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3155 Ty = Context.LongTy; 3156 else if (AllowUnsigned) 3157 Ty = Context.UnsignedLongTy; 3158 Width = LongSize; 3159 } 3160 } 3161 3162 // Check long long if needed. 3163 if (Ty.isNull()) { 3164 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3165 3166 // Does it fit in a unsigned long long? 3167 if (ResultVal.isIntN(LongLongSize)) { 3168 // Does it fit in a signed long long? 3169 // To be compatible with MSVC, hex integer literals ending with the 3170 // LL or i64 suffix are always signed in Microsoft mode. 3171 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3172 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 3173 Ty = Context.LongLongTy; 3174 else if (AllowUnsigned) 3175 Ty = Context.UnsignedLongLongTy; 3176 Width = LongLongSize; 3177 } 3178 } 3179 3180 // If it doesn't fit in unsigned long long, and we're using Microsoft 3181 // extensions, then its a 128-bit integer literal. 3182 if (Ty.isNull() && Literal.isMicrosoftInteger && 3183 PP.getTargetInfo().hasInt128Type()) { 3184 if (Literal.isUnsigned) 3185 Ty = Context.UnsignedInt128Ty; 3186 else 3187 Ty = Context.Int128Ty; 3188 Width = 128; 3189 } 3190 3191 // If we still couldn't decide a type, we probably have something that 3192 // does not fit in a signed long long, but has no U suffix. 3193 if (Ty.isNull()) { 3194 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed); 3195 Ty = Context.UnsignedLongLongTy; 3196 Width = Context.getTargetInfo().getLongLongWidth(); 3197 } 3198 3199 if (ResultVal.getBitWidth() != Width) 3200 ResultVal = ResultVal.trunc(Width); 3201 } 3202 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3203 } 3204 3205 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3206 if (Literal.isImaginary) 3207 Res = new (Context) ImaginaryLiteral(Res, 3208 Context.getComplexType(Res->getType())); 3209 3210 return Owned(Res); 3211} 3212 3213ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3214 assert((E != 0) && "ActOnParenExpr() missing expr"); 3215 return Owned(new (Context) ParenExpr(L, R, E)); 3216} 3217 3218static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3219 SourceLocation Loc, 3220 SourceRange ArgRange) { 3221 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3222 // scalar or vector data type argument..." 3223 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3224 // type (C99 6.2.5p18) or void. 3225 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3226 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3227 << T << ArgRange; 3228 return true; 3229 } 3230 3231 assert((T->isVoidType() || !T->isIncompleteType()) && 3232 "Scalar types should always be complete"); 3233 return false; 3234} 3235 3236static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3237 SourceLocation Loc, 3238 SourceRange ArgRange, 3239 UnaryExprOrTypeTrait TraitKind) { 3240 // Invalid types must be hard errors for SFINAE in C++. 3241 if (S.LangOpts.CPlusPlus) 3242 return true; 3243 3244 // C99 6.5.3.4p1: 3245 if (T->isFunctionType() && 3246 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3247 // sizeof(function)/alignof(function) is allowed as an extension. 3248 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3249 << TraitKind << ArgRange; 3250 return false; 3251 } 3252 3253 // Allow sizeof(void)/alignof(void) as an extension. 3254 if (T->isVoidType()) { 3255 S.Diag(Loc, diag::ext_sizeof_alignof_void_type) << TraitKind << ArgRange; 3256 return false; 3257 } 3258 3259 return true; 3260} 3261 3262static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3263 SourceLocation Loc, 3264 SourceRange ArgRange, 3265 UnaryExprOrTypeTrait TraitKind) { 3266 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3267 // runtime doesn't allow it. 3268 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3269 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3270 << T << (TraitKind == UETT_SizeOf) 3271 << ArgRange; 3272 return true; 3273 } 3274 3275 return false; 3276} 3277 3278/// \brief Check whether E is a pointer from a decayed array type (the decayed 3279/// pointer type is equal to T) and emit a warning if it is. 3280static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3281 Expr *E) { 3282 // Don't warn if the operation changed the type. 3283 if (T != E->getType()) 3284 return; 3285 3286 // Now look for array decays. 3287 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3288 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3289 return; 3290 3291 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3292 << ICE->getType() 3293 << ICE->getSubExpr()->getType(); 3294} 3295 3296/// \brief Check the constrains on expression operands to unary type expression 3297/// and type traits. 3298/// 3299/// Completes any types necessary and validates the constraints on the operand 3300/// expression. The logic mostly mirrors the type-based overload, but may modify 3301/// the expression as it completes the type for that expression through template 3302/// instantiation, etc. 3303bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3304 UnaryExprOrTypeTrait ExprKind) { 3305 QualType ExprTy = E->getType(); 3306 assert(!ExprTy->isReferenceType()); 3307 3308 if (ExprKind == UETT_VecStep) 3309 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3310 E->getSourceRange()); 3311 3312 // Whitelist some types as extensions 3313 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3314 E->getSourceRange(), ExprKind)) 3315 return false; 3316 3317 if (RequireCompleteExprType(E, 3318 diag::err_sizeof_alignof_incomplete_type, 3319 ExprKind, E->getSourceRange())) 3320 return true; 3321 3322 // Completing the expression's type may have changed it. 3323 ExprTy = E->getType(); 3324 assert(!ExprTy->isReferenceType()); 3325 3326 if (ExprTy->isFunctionType()) { 3327 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3328 << ExprKind << E->getSourceRange(); 3329 return true; 3330 } 3331 3332 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3333 E->getSourceRange(), ExprKind)) 3334 return true; 3335 3336 if (ExprKind == UETT_SizeOf) { 3337 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3338 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3339 QualType OType = PVD->getOriginalType(); 3340 QualType Type = PVD->getType(); 3341 if (Type->isPointerType() && OType->isArrayType()) { 3342 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3343 << Type << OType; 3344 Diag(PVD->getLocation(), diag::note_declared_at); 3345 } 3346 } 3347 } 3348 3349 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3350 // decays into a pointer and returns an unintended result. This is most 3351 // likely a typo for "sizeof(array) op x". 3352 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3353 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3354 BO->getLHS()); 3355 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3356 BO->getRHS()); 3357 } 3358 } 3359 3360 return false; 3361} 3362 3363/// \brief Check the constraints on operands to unary expression and type 3364/// traits. 3365/// 3366/// This will complete any types necessary, and validate the various constraints 3367/// on those operands. 3368/// 3369/// The UsualUnaryConversions() function is *not* called by this routine. 3370/// C99 6.3.2.1p[2-4] all state: 3371/// Except when it is the operand of the sizeof operator ... 3372/// 3373/// C++ [expr.sizeof]p4 3374/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3375/// standard conversions are not applied to the operand of sizeof. 3376/// 3377/// This policy is followed for all of the unary trait expressions. 3378bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3379 SourceLocation OpLoc, 3380 SourceRange ExprRange, 3381 UnaryExprOrTypeTrait ExprKind) { 3382 if (ExprType->isDependentType()) 3383 return false; 3384 3385 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 3386 // the result is the size of the referenced type." 3387 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 3388 // result shall be the alignment of the referenced type." 3389 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3390 ExprType = Ref->getPointeeType(); 3391 3392 if (ExprKind == UETT_VecStep) 3393 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3394 3395 // Whitelist some types as extensions 3396 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3397 ExprKind)) 3398 return false; 3399 3400 if (RequireCompleteType(OpLoc, ExprType, 3401 diag::err_sizeof_alignof_incomplete_type, 3402 ExprKind, ExprRange)) 3403 return true; 3404 3405 if (ExprType->isFunctionType()) { 3406 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3407 << ExprKind << ExprRange; 3408 return true; 3409 } 3410 3411 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3412 ExprKind)) 3413 return true; 3414 3415 return false; 3416} 3417 3418static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3419 E = E->IgnoreParens(); 3420 3421 // Cannot know anything else if the expression is dependent. 3422 if (E->isTypeDependent()) 3423 return false; 3424 3425 if (E->getObjectKind() == OK_BitField) { 3426 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) 3427 << 1 << E->getSourceRange(); 3428 return true; 3429 } 3430 3431 ValueDecl *D = 0; 3432 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3433 D = DRE->getDecl(); 3434 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3435 D = ME->getMemberDecl(); 3436 } 3437 3438 // If it's a field, require the containing struct to have a 3439 // complete definition so that we can compute the layout. 3440 // 3441 // This requires a very particular set of circumstances. For a 3442 // field to be contained within an incomplete type, we must in the 3443 // process of parsing that type. To have an expression refer to a 3444 // field, it must be an id-expression or a member-expression, but 3445 // the latter are always ill-formed when the base type is 3446 // incomplete, including only being partially complete. An 3447 // id-expression can never refer to a field in C because fields 3448 // are not in the ordinary namespace. In C++, an id-expression 3449 // can implicitly be a member access, but only if there's an 3450 // implicit 'this' value, and all such contexts are subject to 3451 // delayed parsing --- except for trailing return types in C++11. 3452 // And if an id-expression referring to a field occurs in a 3453 // context that lacks a 'this' value, it's ill-formed --- except, 3454 // agian, in C++11, where such references are allowed in an 3455 // unevaluated context. So C++11 introduces some new complexity. 3456 // 3457 // For the record, since __alignof__ on expressions is a GCC 3458 // extension, GCC seems to permit this but always gives the 3459 // nonsensical answer 0. 3460 // 3461 // We don't really need the layout here --- we could instead just 3462 // directly check for all the appropriate alignment-lowing 3463 // attributes --- but that would require duplicating a lot of 3464 // logic that just isn't worth duplicating for such a marginal 3465 // use-case. 3466 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3467 // Fast path this check, since we at least know the record has a 3468 // definition if we can find a member of it. 3469 if (!FD->getParent()->isCompleteDefinition()) { 3470 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3471 << E->getSourceRange(); 3472 return true; 3473 } 3474 3475 // Otherwise, if it's a field, and the field doesn't have 3476 // reference type, then it must have a complete type (or be a 3477 // flexible array member, which we explicitly want to 3478 // white-list anyway), which makes the following checks trivial. 3479 if (!FD->getType()->isReferenceType()) 3480 return false; 3481 } 3482 3483 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3484} 3485 3486bool Sema::CheckVecStepExpr(Expr *E) { 3487 E = E->IgnoreParens(); 3488 3489 // Cannot know anything else if the expression is dependent. 3490 if (E->isTypeDependent()) 3491 return false; 3492 3493 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3494} 3495 3496/// \brief Build a sizeof or alignof expression given a type operand. 3497ExprResult 3498Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3499 SourceLocation OpLoc, 3500 UnaryExprOrTypeTrait ExprKind, 3501 SourceRange R) { 3502 if (!TInfo) 3503 return ExprError(); 3504 3505 QualType T = TInfo->getType(); 3506 3507 if (!T->isDependentType() && 3508 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3509 return ExprError(); 3510 3511 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3512 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo, 3513 Context.getSizeType(), 3514 OpLoc, R.getEnd())); 3515} 3516 3517/// \brief Build a sizeof or alignof expression given an expression 3518/// operand. 3519ExprResult 3520Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3521 UnaryExprOrTypeTrait ExprKind) { 3522 ExprResult PE = CheckPlaceholderExpr(E); 3523 if (PE.isInvalid()) 3524 return ExprError(); 3525 3526 E = PE.get(); 3527 3528 // Verify that the operand is valid. 3529 bool isInvalid = false; 3530 if (E->isTypeDependent()) { 3531 // Delay type-checking for type-dependent expressions. 3532 } else if (ExprKind == UETT_AlignOf) { 3533 isInvalid = CheckAlignOfExpr(*this, E); 3534 } else if (ExprKind == UETT_VecStep) { 3535 isInvalid = CheckVecStepExpr(E); 3536 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 3537 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0; 3538 isInvalid = true; 3539 } else { 3540 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3541 } 3542 3543 if (isInvalid) 3544 return ExprError(); 3545 3546 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3547 PE = TransformToPotentiallyEvaluated(E); 3548 if (PE.isInvalid()) return ExprError(); 3549 E = PE.take(); 3550 } 3551 3552 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3553 return Owned(new (Context) UnaryExprOrTypeTraitExpr( 3554 ExprKind, E, Context.getSizeType(), OpLoc, 3555 E->getSourceRange().getEnd())); 3556} 3557 3558/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 3559/// expr and the same for @c alignof and @c __alignof 3560/// Note that the ArgRange is invalid if isType is false. 3561ExprResult 3562Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 3563 UnaryExprOrTypeTrait ExprKind, bool IsType, 3564 void *TyOrEx, const SourceRange &ArgRange) { 3565 // If error parsing type, ignore. 3566 if (TyOrEx == 0) return ExprError(); 3567 3568 if (IsType) { 3569 TypeSourceInfo *TInfo; 3570 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 3571 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 3572 } 3573 3574 Expr *ArgEx = (Expr *)TyOrEx; 3575 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 3576 return Result; 3577} 3578 3579static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 3580 bool IsReal) { 3581 if (V.get()->isTypeDependent()) 3582 return S.Context.DependentTy; 3583 3584 // _Real and _Imag are only l-values for normal l-values. 3585 if (V.get()->getObjectKind() != OK_Ordinary) { 3586 V = S.DefaultLvalueConversion(V.take()); 3587 if (V.isInvalid()) 3588 return QualType(); 3589 } 3590 3591 // These operators return the element type of a complex type. 3592 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 3593 return CT->getElementType(); 3594 3595 // Otherwise they pass through real integer and floating point types here. 3596 if (V.get()->getType()->isArithmeticType()) 3597 return V.get()->getType(); 3598 3599 // Test for placeholders. 3600 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 3601 if (PR.isInvalid()) return QualType(); 3602 if (PR.get() != V.get()) { 3603 V = PR; 3604 return CheckRealImagOperand(S, V, Loc, IsReal); 3605 } 3606 3607 // Reject anything else. 3608 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 3609 << (IsReal ? "__real" : "__imag"); 3610 return QualType(); 3611} 3612 3613 3614 3615ExprResult 3616Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 3617 tok::TokenKind Kind, Expr *Input) { 3618 UnaryOperatorKind Opc; 3619 switch (Kind) { 3620 default: llvm_unreachable("Unknown unary op!"); 3621 case tok::plusplus: Opc = UO_PostInc; break; 3622 case tok::minusminus: Opc = UO_PostDec; break; 3623 } 3624 3625 // Since this might is a postfix expression, get rid of ParenListExprs. 3626 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 3627 if (Result.isInvalid()) return ExprError(); 3628 Input = Result.take(); 3629 3630 return BuildUnaryOp(S, OpLoc, Opc, Input); 3631} 3632 3633/// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 3634/// 3635/// \return true on error 3636static bool checkArithmeticOnObjCPointer(Sema &S, 3637 SourceLocation opLoc, 3638 Expr *op) { 3639 assert(op->getType()->isObjCObjectPointerType()); 3640 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic()) 3641 return false; 3642 3643 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 3644 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 3645 << op->getSourceRange(); 3646 return true; 3647} 3648 3649ExprResult 3650Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 3651 Expr *idx, SourceLocation rbLoc) { 3652 // Since this might be a postfix expression, get rid of ParenListExprs. 3653 if (isa<ParenListExpr>(base)) { 3654 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 3655 if (result.isInvalid()) return ExprError(); 3656 base = result.take(); 3657 } 3658 3659 // Handle any non-overload placeholder types in the base and index 3660 // expressions. We can't handle overloads here because the other 3661 // operand might be an overloadable type, in which case the overload 3662 // resolution for the operator overload should get the first crack 3663 // at the overload. 3664 if (base->getType()->isNonOverloadPlaceholderType()) { 3665 ExprResult result = CheckPlaceholderExpr(base); 3666 if (result.isInvalid()) return ExprError(); 3667 base = result.take(); 3668 } 3669 if (idx->getType()->isNonOverloadPlaceholderType()) { 3670 ExprResult result = CheckPlaceholderExpr(idx); 3671 if (result.isInvalid()) return ExprError(); 3672 idx = result.take(); 3673 } 3674 3675 // Build an unanalyzed expression if either operand is type-dependent. 3676 if (getLangOpts().CPlusPlus && 3677 (base->isTypeDependent() || idx->isTypeDependent())) { 3678 return Owned(new (Context) ArraySubscriptExpr(base, idx, 3679 Context.DependentTy, 3680 VK_LValue, OK_Ordinary, 3681 rbLoc)); 3682 } 3683 3684 // Use C++ overloaded-operator rules if either operand has record 3685 // type. The spec says to do this if either type is *overloadable*, 3686 // but enum types can't declare subscript operators or conversion 3687 // operators, so there's nothing interesting for overload resolution 3688 // to do if there aren't any record types involved. 3689 // 3690 // ObjC pointers have their own subscripting logic that is not tied 3691 // to overload resolution and so should not take this path. 3692 if (getLangOpts().CPlusPlus && 3693 (base->getType()->isRecordType() || 3694 (!base->getType()->isObjCObjectPointerType() && 3695 idx->getType()->isRecordType()))) { 3696 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 3697 } 3698 3699 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 3700} 3701 3702ExprResult 3703Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 3704 Expr *Idx, SourceLocation RLoc) { 3705 Expr *LHSExp = Base; 3706 Expr *RHSExp = Idx; 3707 3708 // Perform default conversions. 3709 if (!LHSExp->getType()->getAs<VectorType>()) { 3710 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 3711 if (Result.isInvalid()) 3712 return ExprError(); 3713 LHSExp = Result.take(); 3714 } 3715 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 3716 if (Result.isInvalid()) 3717 return ExprError(); 3718 RHSExp = Result.take(); 3719 3720 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 3721 ExprValueKind VK = VK_LValue; 3722 ExprObjectKind OK = OK_Ordinary; 3723 3724 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 3725 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 3726 // in the subscript position. As a result, we need to derive the array base 3727 // and index from the expression types. 3728 Expr *BaseExpr, *IndexExpr; 3729 QualType ResultType; 3730 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 3731 BaseExpr = LHSExp; 3732 IndexExpr = RHSExp; 3733 ResultType = Context.DependentTy; 3734 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 3735 BaseExpr = LHSExp; 3736 IndexExpr = RHSExp; 3737 ResultType = PTy->getPointeeType(); 3738 } else if (const ObjCObjectPointerType *PTy = 3739 LHSTy->getAs<ObjCObjectPointerType>()) { 3740 BaseExpr = LHSExp; 3741 IndexExpr = RHSExp; 3742 3743 // Use custom logic if this should be the pseudo-object subscript 3744 // expression. 3745 if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic()) 3746 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0); 3747 3748 ResultType = PTy->getPointeeType(); 3749 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) { 3750 Diag(LLoc, diag::err_subscript_nonfragile_interface) 3751 << ResultType << BaseExpr->getSourceRange(); 3752 return ExprError(); 3753 } 3754 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 3755 // Handle the uncommon case of "123[Ptr]". 3756 BaseExpr = RHSExp; 3757 IndexExpr = LHSExp; 3758 ResultType = PTy->getPointeeType(); 3759 } else if (const ObjCObjectPointerType *PTy = 3760 RHSTy->getAs<ObjCObjectPointerType>()) { 3761 // Handle the uncommon case of "123[Ptr]". 3762 BaseExpr = RHSExp; 3763 IndexExpr = LHSExp; 3764 ResultType = PTy->getPointeeType(); 3765 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) { 3766 Diag(LLoc, diag::err_subscript_nonfragile_interface) 3767 << ResultType << BaseExpr->getSourceRange(); 3768 return ExprError(); 3769 } 3770 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 3771 BaseExpr = LHSExp; // vectors: V[123] 3772 IndexExpr = RHSExp; 3773 VK = LHSExp->getValueKind(); 3774 if (VK != VK_RValue) 3775 OK = OK_VectorComponent; 3776 3777 // FIXME: need to deal with const... 3778 ResultType = VTy->getElementType(); 3779 } else if (LHSTy->isArrayType()) { 3780 // If we see an array that wasn't promoted by 3781 // DefaultFunctionArrayLvalueConversion, it must be an array that 3782 // wasn't promoted because of the C90 rule that doesn't 3783 // allow promoting non-lvalue arrays. Warn, then 3784 // force the promotion here. 3785 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3786 LHSExp->getSourceRange(); 3787 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 3788 CK_ArrayToPointerDecay).take(); 3789 LHSTy = LHSExp->getType(); 3790 3791 BaseExpr = LHSExp; 3792 IndexExpr = RHSExp; 3793 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 3794 } else if (RHSTy->isArrayType()) { 3795 // Same as previous, except for 123[f().a] case 3796 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3797 RHSExp->getSourceRange(); 3798 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 3799 CK_ArrayToPointerDecay).take(); 3800 RHSTy = RHSExp->getType(); 3801 3802 BaseExpr = RHSExp; 3803 IndexExpr = LHSExp; 3804 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 3805 } else { 3806 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 3807 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 3808 } 3809 // C99 6.5.2.1p1 3810 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 3811 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 3812 << IndexExpr->getSourceRange()); 3813 3814 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 3815 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 3816 && !IndexExpr->isTypeDependent()) 3817 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 3818 3819 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 3820 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 3821 // type. Note that Functions are not objects, and that (in C99 parlance) 3822 // incomplete types are not object types. 3823 if (ResultType->isFunctionType()) { 3824 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 3825 << ResultType << BaseExpr->getSourceRange(); 3826 return ExprError(); 3827 } 3828 3829 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 3830 // GNU extension: subscripting on pointer to void 3831 Diag(LLoc, diag::ext_gnu_subscript_void_type) 3832 << BaseExpr->getSourceRange(); 3833 3834 // C forbids expressions of unqualified void type from being l-values. 3835 // See IsCForbiddenLValueType. 3836 if (!ResultType.hasQualifiers()) VK = VK_RValue; 3837 } else if (!ResultType->isDependentType() && 3838 RequireCompleteType(LLoc, ResultType, 3839 diag::err_subscript_incomplete_type, BaseExpr)) 3840 return ExprError(); 3841 3842 assert(VK == VK_RValue || LangOpts.CPlusPlus || 3843 !ResultType.isCForbiddenLValueType()); 3844 3845 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 3846 ResultType, VK, OK, RLoc)); 3847} 3848 3849ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 3850 FunctionDecl *FD, 3851 ParmVarDecl *Param) { 3852 if (Param->hasUnparsedDefaultArg()) { 3853 Diag(CallLoc, 3854 diag::err_use_of_default_argument_to_function_declared_later) << 3855 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 3856 Diag(UnparsedDefaultArgLocs[Param], 3857 diag::note_default_argument_declared_here); 3858 return ExprError(); 3859 } 3860 3861 if (Param->hasUninstantiatedDefaultArg()) { 3862 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 3863 3864 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 3865 Param); 3866 3867 // Instantiate the expression. 3868 MultiLevelTemplateArgumentList MutiLevelArgList 3869 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true); 3870 3871 InstantiatingTemplate Inst(*this, CallLoc, Param, 3872 MutiLevelArgList.getInnermost()); 3873 if (Inst.isInvalid()) 3874 return ExprError(); 3875 3876 ExprResult Result; 3877 { 3878 // C++ [dcl.fct.default]p5: 3879 // The names in the [default argument] expression are bound, and 3880 // the semantic constraints are checked, at the point where the 3881 // default argument expression appears. 3882 ContextRAII SavedContext(*this, FD); 3883 LocalInstantiationScope Local(*this); 3884 Result = SubstExpr(UninstExpr, MutiLevelArgList); 3885 } 3886 if (Result.isInvalid()) 3887 return ExprError(); 3888 3889 // Check the expression as an initializer for the parameter. 3890 InitializedEntity Entity 3891 = InitializedEntity::InitializeParameter(Context, Param); 3892 InitializationKind Kind 3893 = InitializationKind::CreateCopy(Param->getLocation(), 3894 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 3895 Expr *ResultE = Result.takeAs<Expr>(); 3896 3897 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 3898 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 3899 if (Result.isInvalid()) 3900 return ExprError(); 3901 3902 Expr *Arg = Result.takeAs<Expr>(); 3903 CheckCompletedExpr(Arg, Param->getOuterLocStart()); 3904 // Build the default argument expression. 3905 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg)); 3906 } 3907 3908 // If the default expression creates temporaries, we need to 3909 // push them to the current stack of expression temporaries so they'll 3910 // be properly destroyed. 3911 // FIXME: We should really be rebuilding the default argument with new 3912 // bound temporaries; see the comment in PR5810. 3913 // We don't need to do that with block decls, though, because 3914 // blocks in default argument expression can never capture anything. 3915 if (isa<ExprWithCleanups>(Param->getInit())) { 3916 // Set the "needs cleanups" bit regardless of whether there are 3917 // any explicit objects. 3918 ExprNeedsCleanups = true; 3919 3920 // Append all the objects to the cleanup list. Right now, this 3921 // should always be a no-op, because blocks in default argument 3922 // expressions should never be able to capture anything. 3923 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() && 3924 "default argument expression has capturing blocks?"); 3925 } 3926 3927 // We already type-checked the argument, so we know it works. 3928 // Just mark all of the declarations in this potentially-evaluated expression 3929 // as being "referenced". 3930 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 3931 /*SkipLocalVariables=*/true); 3932 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param)); 3933} 3934 3935 3936Sema::VariadicCallType 3937Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 3938 Expr *Fn) { 3939 if (Proto && Proto->isVariadic()) { 3940 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 3941 return VariadicConstructor; 3942 else if (Fn && Fn->getType()->isBlockPointerType()) 3943 return VariadicBlock; 3944 else if (FDecl) { 3945 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 3946 if (Method->isInstance()) 3947 return VariadicMethod; 3948 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 3949 return VariadicMethod; 3950 return VariadicFunction; 3951 } 3952 return VariadicDoesNotApply; 3953} 3954 3955namespace { 3956class FunctionCallCCC : public FunctionCallFilterCCC { 3957public: 3958 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 3959 unsigned NumArgs, bool HasExplicitTemplateArgs) 3960 : FunctionCallFilterCCC(SemaRef, NumArgs, HasExplicitTemplateArgs), 3961 FunctionName(FuncName) {} 3962 3963 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 3964 if (!candidate.getCorrectionSpecifier() || 3965 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 3966 return false; 3967 } 3968 3969 return FunctionCallFilterCCC::ValidateCandidate(candidate); 3970 } 3971 3972private: 3973 const IdentifierInfo *const FunctionName; 3974}; 3975} 3976 3977static TypoCorrection TryTypoCorrectionForCall(Sema &S, 3978 DeclarationNameInfo FuncName, 3979 ArrayRef<Expr *> Args) { 3980 FunctionCallCCC CCC(S, FuncName.getName().getAsIdentifierInfo(), 3981 Args.size(), false); 3982 if (TypoCorrection Corrected = 3983 S.CorrectTypo(FuncName, Sema::LookupOrdinaryName, 3984 S.getScopeForContext(S.CurContext), NULL, CCC)) { 3985 if (NamedDecl *ND = Corrected.getCorrectionDecl()) { 3986 if (Corrected.isOverloaded()) { 3987 OverloadCandidateSet OCS(FuncName.getLoc()); 3988 OverloadCandidateSet::iterator Best; 3989 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 3990 CDEnd = Corrected.end(); 3991 CD != CDEnd; ++CD) { 3992 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 3993 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 3994 OCS); 3995 } 3996 switch (OCS.BestViableFunction(S, FuncName.getLoc(), Best)) { 3997 case OR_Success: 3998 ND = Best->Function; 3999 Corrected.setCorrectionDecl(ND); 4000 break; 4001 default: 4002 break; 4003 } 4004 } 4005 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) { 4006 return Corrected; 4007 } 4008 } 4009 } 4010 return TypoCorrection(); 4011} 4012 4013/// ConvertArgumentsForCall - Converts the arguments specified in 4014/// Args/NumArgs to the parameter types of the function FDecl with 4015/// function prototype Proto. Call is the call expression itself, and 4016/// Fn is the function expression. For a C++ member function, this 4017/// routine does not attempt to convert the object argument. Returns 4018/// true if the call is ill-formed. 4019bool 4020Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4021 FunctionDecl *FDecl, 4022 const FunctionProtoType *Proto, 4023 ArrayRef<Expr *> Args, 4024 SourceLocation RParenLoc, 4025 bool IsExecConfig) { 4026 // Bail out early if calling a builtin with custom typechecking. 4027 // We don't need to do this in the 4028 if (FDecl) 4029 if (unsigned ID = FDecl->getBuiltinID()) 4030 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4031 return false; 4032 4033 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4034 // assignment, to the types of the corresponding parameter, ... 4035 unsigned NumArgsInProto = Proto->getNumArgs(); 4036 bool Invalid = false; 4037 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto; 4038 unsigned FnKind = Fn->getType()->isBlockPointerType() 4039 ? 1 /* block */ 4040 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4041 : 0 /* function */); 4042 4043 // If too few arguments are available (and we don't have default 4044 // arguments for the remaining parameters), don't make the call. 4045 if (Args.size() < NumArgsInProto) { 4046 if (Args.size() < MinArgs) { 4047 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4048 TypoCorrection TC; 4049 if (FDecl && (TC = TryTypoCorrectionForCall( 4050 *this, DeclarationNameInfo(FDecl->getDeclName(), 4051 (ME ? ME->getMemberLoc() 4052 : Fn->getLocStart())), 4053 Args))) { 4054 unsigned diag_id = 4055 MinArgs == NumArgsInProto && !Proto->isVariadic() 4056 ? diag::err_typecheck_call_too_few_args_suggest 4057 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4058 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4059 << static_cast<unsigned>(Args.size()) 4060 << Fn->getSourceRange()); 4061 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4062 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic() 4063 ? diag::err_typecheck_call_too_few_args_one 4064 : diag::err_typecheck_call_too_few_args_at_least_one) 4065 << FnKind 4066 << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4067 else 4068 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic() 4069 ? diag::err_typecheck_call_too_few_args 4070 : diag::err_typecheck_call_too_few_args_at_least) 4071 << FnKind 4072 << MinArgs << static_cast<unsigned>(Args.size()) 4073 << Fn->getSourceRange(); 4074 4075 // Emit the location of the prototype. 4076 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4077 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4078 << FDecl; 4079 4080 return true; 4081 } 4082 Call->setNumArgs(Context, NumArgsInProto); 4083 } 4084 4085 // If too many are passed and not variadic, error on the extras and drop 4086 // them. 4087 if (Args.size() > NumArgsInProto) { 4088 if (!Proto->isVariadic()) { 4089 TypoCorrection TC; 4090 if (FDecl && (TC = TryTypoCorrectionForCall( 4091 *this, DeclarationNameInfo(FDecl->getDeclName(), 4092 Fn->getLocStart()), 4093 Args))) { 4094 unsigned diag_id = 4095 MinArgs == NumArgsInProto && !Proto->isVariadic() 4096 ? diag::err_typecheck_call_too_many_args_suggest 4097 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4098 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumArgsInProto 4099 << static_cast<unsigned>(Args.size()) 4100 << Fn->getSourceRange()); 4101 } else if (NumArgsInProto == 1 && FDecl && 4102 FDecl->getParamDecl(0)->getDeclName()) 4103 Diag(Args[NumArgsInProto]->getLocStart(), 4104 MinArgs == NumArgsInProto 4105 ? diag::err_typecheck_call_too_many_args_one 4106 : diag::err_typecheck_call_too_many_args_at_most_one) 4107 << FnKind 4108 << FDecl->getParamDecl(0) << static_cast<unsigned>(Args.size()) 4109 << Fn->getSourceRange() 4110 << SourceRange(Args[NumArgsInProto]->getLocStart(), 4111 Args.back()->getLocEnd()); 4112 else 4113 Diag(Args[NumArgsInProto]->getLocStart(), 4114 MinArgs == NumArgsInProto 4115 ? diag::err_typecheck_call_too_many_args 4116 : diag::err_typecheck_call_too_many_args_at_most) 4117 << FnKind 4118 << NumArgsInProto << static_cast<unsigned>(Args.size()) 4119 << Fn->getSourceRange() 4120 << SourceRange(Args[NumArgsInProto]->getLocStart(), 4121 Args.back()->getLocEnd()); 4122 4123 // Emit the location of the prototype. 4124 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4125 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4126 << FDecl; 4127 4128 // This deletes the extra arguments. 4129 Call->setNumArgs(Context, NumArgsInProto); 4130 return true; 4131 } 4132 } 4133 SmallVector<Expr *, 8> AllArgs; 4134 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4135 4136 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4137 Proto, 0, Args, AllArgs, CallType); 4138 if (Invalid) 4139 return true; 4140 unsigned TotalNumArgs = AllArgs.size(); 4141 for (unsigned i = 0; i < TotalNumArgs; ++i) 4142 Call->setArg(i, AllArgs[i]); 4143 4144 return false; 4145} 4146 4147bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, 4148 FunctionDecl *FDecl, 4149 const FunctionProtoType *Proto, 4150 unsigned FirstProtoArg, 4151 ArrayRef<Expr *> Args, 4152 SmallVectorImpl<Expr *> &AllArgs, 4153 VariadicCallType CallType, 4154 bool AllowExplicit, 4155 bool IsListInitialization) { 4156 unsigned NumArgsInProto = Proto->getNumArgs(); 4157 unsigned NumArgsToCheck = Args.size(); 4158 bool Invalid = false; 4159 if (Args.size() != NumArgsInProto) 4160 // Use default arguments for missing arguments 4161 NumArgsToCheck = NumArgsInProto; 4162 unsigned ArgIx = 0; 4163 // Continue to check argument types (even if we have too few/many args). 4164 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) { 4165 QualType ProtoArgType = Proto->getArgType(i); 4166 4167 Expr *Arg; 4168 ParmVarDecl *Param; 4169 if (ArgIx < Args.size()) { 4170 Arg = Args[ArgIx++]; 4171 4172 if (RequireCompleteType(Arg->getLocStart(), 4173 ProtoArgType, 4174 diag::err_call_incomplete_argument, Arg)) 4175 return true; 4176 4177 // Pass the argument 4178 Param = 0; 4179 if (FDecl && i < FDecl->getNumParams()) 4180 Param = FDecl->getParamDecl(i); 4181 4182 // Strip the unbridged-cast placeholder expression off, if applicable. 4183 bool CFAudited = false; 4184 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4185 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4186 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4187 Arg = stripARCUnbridgedCast(Arg); 4188 else if (getLangOpts().ObjCAutoRefCount && 4189 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4190 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4191 CFAudited = true; 4192 4193 InitializedEntity Entity = Param ? 4194 InitializedEntity::InitializeParameter(Context, Param, ProtoArgType) 4195 : InitializedEntity::InitializeParameter(Context, ProtoArgType, 4196 Proto->isArgConsumed(i)); 4197 4198 // Remember that parameter belongs to a CF audited API. 4199 if (CFAudited) 4200 Entity.setParameterCFAudited(); 4201 4202 ExprResult ArgE = PerformCopyInitialization(Entity, 4203 SourceLocation(), 4204 Owned(Arg), 4205 IsListInitialization, 4206 AllowExplicit); 4207 if (ArgE.isInvalid()) 4208 return true; 4209 4210 Arg = ArgE.takeAs<Expr>(); 4211 } else { 4212 assert(FDecl && "can't use default arguments without a known callee"); 4213 Param = FDecl->getParamDecl(i); 4214 4215 ExprResult ArgExpr = 4216 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4217 if (ArgExpr.isInvalid()) 4218 return true; 4219 4220 Arg = ArgExpr.takeAs<Expr>(); 4221 } 4222 4223 // Check for array bounds violations for each argument to the call. This 4224 // check only triggers warnings when the argument isn't a more complex Expr 4225 // with its own checking, such as a BinaryOperator. 4226 CheckArrayAccess(Arg); 4227 4228 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4229 CheckStaticArrayArgument(CallLoc, Param, Arg); 4230 4231 AllArgs.push_back(Arg); 4232 } 4233 4234 // If this is a variadic call, handle args passed through "...". 4235 if (CallType != VariadicDoesNotApply) { 4236 // Assume that extern "C" functions with variadic arguments that 4237 // return __unknown_anytype aren't *really* variadic. 4238 if (Proto->getResultType() == Context.UnknownAnyTy && 4239 FDecl && FDecl->isExternC()) { 4240 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4241 QualType paramType; // ignored 4242 ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType); 4243 Invalid |= arg.isInvalid(); 4244 AllArgs.push_back(arg.take()); 4245 } 4246 4247 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4248 } else { 4249 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4250 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, 4251 FDecl); 4252 Invalid |= Arg.isInvalid(); 4253 AllArgs.push_back(Arg.take()); 4254 } 4255 } 4256 4257 // Check for array bounds violations. 4258 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) 4259 CheckArrayAccess(Args[i]); 4260 } 4261 return Invalid; 4262} 4263 4264static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4265 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4266 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4267 TL = DTL.getOriginalLoc(); 4268 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4269 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4270 << ATL.getLocalSourceRange(); 4271} 4272 4273/// CheckStaticArrayArgument - If the given argument corresponds to a static 4274/// array parameter, check that it is non-null, and that if it is formed by 4275/// array-to-pointer decay, the underlying array is sufficiently large. 4276/// 4277/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4278/// array type derivation, then for each call to the function, the value of the 4279/// corresponding actual argument shall provide access to the first element of 4280/// an array with at least as many elements as specified by the size expression. 4281void 4282Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4283 ParmVarDecl *Param, 4284 const Expr *ArgExpr) { 4285 // Static array parameters are not supported in C++. 4286 if (!Param || getLangOpts().CPlusPlus) 4287 return; 4288 4289 QualType OrigTy = Param->getOriginalType(); 4290 4291 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4292 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4293 return; 4294 4295 if (ArgExpr->isNullPointerConstant(Context, 4296 Expr::NPC_NeverValueDependent)) { 4297 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4298 DiagnoseCalleeStaticArrayParam(*this, Param); 4299 return; 4300 } 4301 4302 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4303 if (!CAT) 4304 return; 4305 4306 const ConstantArrayType *ArgCAT = 4307 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4308 if (!ArgCAT) 4309 return; 4310 4311 if (ArgCAT->getSize().ult(CAT->getSize())) { 4312 Diag(CallLoc, diag::warn_static_array_too_small) 4313 << ArgExpr->getSourceRange() 4314 << (unsigned) ArgCAT->getSize().getZExtValue() 4315 << (unsigned) CAT->getSize().getZExtValue(); 4316 DiagnoseCalleeStaticArrayParam(*this, Param); 4317 } 4318} 4319 4320/// Given a function expression of unknown-any type, try to rebuild it 4321/// to have a function type. 4322static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4323 4324/// Is the given type a placeholder that we need to lower out 4325/// immediately during argument processing? 4326static bool isPlaceholderToRemoveAsArg(QualType type) { 4327 // Placeholders are never sugared. 4328 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4329 if (!placeholder) return false; 4330 4331 switch (placeholder->getKind()) { 4332 // Ignore all the non-placeholder types. 4333#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4334#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4335#include "clang/AST/BuiltinTypes.def" 4336 return false; 4337 4338 // We cannot lower out overload sets; they might validly be resolved 4339 // by the call machinery. 4340 case BuiltinType::Overload: 4341 return false; 4342 4343 // Unbridged casts in ARC can be handled in some call positions and 4344 // should be left in place. 4345 case BuiltinType::ARCUnbridgedCast: 4346 return false; 4347 4348 // Pseudo-objects should be converted as soon as possible. 4349 case BuiltinType::PseudoObject: 4350 return true; 4351 4352 // The debugger mode could theoretically but currently does not try 4353 // to resolve unknown-typed arguments based on known parameter types. 4354 case BuiltinType::UnknownAny: 4355 return true; 4356 4357 // These are always invalid as call arguments and should be reported. 4358 case BuiltinType::BoundMember: 4359 case BuiltinType::BuiltinFn: 4360 return true; 4361 } 4362 llvm_unreachable("bad builtin type kind"); 4363} 4364 4365/// Check an argument list for placeholders that we won't try to 4366/// handle later. 4367static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 4368 // Apply this processing to all the arguments at once instead of 4369 // dying at the first failure. 4370 bool hasInvalid = false; 4371 for (size_t i = 0, e = args.size(); i != e; i++) { 4372 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 4373 ExprResult result = S.CheckPlaceholderExpr(args[i]); 4374 if (result.isInvalid()) hasInvalid = true; 4375 else args[i] = result.take(); 4376 } 4377 } 4378 return hasInvalid; 4379} 4380 4381/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 4382/// This provides the location of the left/right parens and a list of comma 4383/// locations. 4384ExprResult 4385Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 4386 MultiExprArg ArgExprs, SourceLocation RParenLoc, 4387 Expr *ExecConfig, bool IsExecConfig) { 4388 // Since this might be a postfix expression, get rid of ParenListExprs. 4389 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 4390 if (Result.isInvalid()) return ExprError(); 4391 Fn = Result.take(); 4392 4393 if (checkArgsForPlaceholders(*this, ArgExprs)) 4394 return ExprError(); 4395 4396 if (getLangOpts().CPlusPlus) { 4397 // If this is a pseudo-destructor expression, build the call immediately. 4398 if (isa<CXXPseudoDestructorExpr>(Fn)) { 4399 if (!ArgExprs.empty()) { 4400 // Pseudo-destructor calls should not have any arguments. 4401 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 4402 << FixItHint::CreateRemoval( 4403 SourceRange(ArgExprs[0]->getLocStart(), 4404 ArgExprs.back()->getLocEnd())); 4405 } 4406 4407 return Owned(new (Context) CallExpr(Context, Fn, None, 4408 Context.VoidTy, VK_RValue, 4409 RParenLoc)); 4410 } 4411 if (Fn->getType() == Context.PseudoObjectTy) { 4412 ExprResult result = CheckPlaceholderExpr(Fn); 4413 if (result.isInvalid()) return ExprError(); 4414 Fn = result.take(); 4415 } 4416 4417 // Determine whether this is a dependent call inside a C++ template, 4418 // in which case we won't do any semantic analysis now. 4419 // FIXME: Will need to cache the results of name lookup (including ADL) in 4420 // Fn. 4421 bool Dependent = false; 4422 if (Fn->isTypeDependent()) 4423 Dependent = true; 4424 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 4425 Dependent = true; 4426 4427 if (Dependent) { 4428 if (ExecConfig) { 4429 return Owned(new (Context) CUDAKernelCallExpr( 4430 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 4431 Context.DependentTy, VK_RValue, RParenLoc)); 4432 } else { 4433 return Owned(new (Context) CallExpr(Context, Fn, ArgExprs, 4434 Context.DependentTy, VK_RValue, 4435 RParenLoc)); 4436 } 4437 } 4438 4439 // Determine whether this is a call to an object (C++ [over.call.object]). 4440 if (Fn->getType()->isRecordType()) 4441 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, 4442 ArgExprs, RParenLoc)); 4443 4444 if (Fn->getType() == Context.UnknownAnyTy) { 4445 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4446 if (result.isInvalid()) return ExprError(); 4447 Fn = result.take(); 4448 } 4449 4450 if (Fn->getType() == Context.BoundMemberTy) { 4451 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 4452 } 4453 } 4454 4455 // Check for overloaded calls. This can happen even in C due to extensions. 4456 if (Fn->getType() == Context.OverloadTy) { 4457 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 4458 4459 // We aren't supposed to apply this logic for if there's an '&' involved. 4460 if (!find.HasFormOfMemberPointer) { 4461 OverloadExpr *ovl = find.Expression; 4462 if (isa<UnresolvedLookupExpr>(ovl)) { 4463 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl); 4464 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs, 4465 RParenLoc, ExecConfig); 4466 } else { 4467 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, 4468 RParenLoc); 4469 } 4470 } 4471 } 4472 4473 // If we're directly calling a function, get the appropriate declaration. 4474 if (Fn->getType() == Context.UnknownAnyTy) { 4475 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4476 if (result.isInvalid()) return ExprError(); 4477 Fn = result.take(); 4478 } 4479 4480 Expr *NakedFn = Fn->IgnoreParens(); 4481 4482 NamedDecl *NDecl = 0; 4483 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) 4484 if (UnOp->getOpcode() == UO_AddrOf) 4485 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 4486 4487 if (isa<DeclRefExpr>(NakedFn)) 4488 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 4489 else if (isa<MemberExpr>(NakedFn)) 4490 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 4491 4492 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 4493 ExecConfig, IsExecConfig); 4494} 4495 4496ExprResult 4497Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 4498 MultiExprArg ExecConfig, SourceLocation GGGLoc) { 4499 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl(); 4500 if (!ConfigDecl) 4501 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use) 4502 << "cudaConfigureCall"); 4503 QualType ConfigQTy = ConfigDecl->getType(); 4504 4505 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr( 4506 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc); 4507 MarkFunctionReferenced(LLLLoc, ConfigDecl); 4508 4509 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0, 4510 /*IsExecConfig=*/true); 4511} 4512 4513/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 4514/// 4515/// __builtin_astype( value, dst type ) 4516/// 4517ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 4518 SourceLocation BuiltinLoc, 4519 SourceLocation RParenLoc) { 4520 ExprValueKind VK = VK_RValue; 4521 ExprObjectKind OK = OK_Ordinary; 4522 QualType DstTy = GetTypeFromParser(ParsedDestTy); 4523 QualType SrcTy = E->getType(); 4524 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 4525 return ExprError(Diag(BuiltinLoc, 4526 diag::err_invalid_astype_of_different_size) 4527 << DstTy 4528 << SrcTy 4529 << E->getSourceRange()); 4530 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, 4531 RParenLoc)); 4532} 4533 4534/// ActOnConvertVectorExpr - create a new convert-vector expression from the 4535/// provided arguments. 4536/// 4537/// __builtin_convertvector( value, dst type ) 4538/// 4539ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 4540 SourceLocation BuiltinLoc, 4541 SourceLocation RParenLoc) { 4542 TypeSourceInfo *TInfo; 4543 GetTypeFromParser(ParsedDestTy, &TInfo); 4544 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 4545} 4546 4547/// BuildResolvedCallExpr - Build a call to a resolved expression, 4548/// i.e. an expression not of \p OverloadTy. The expression should 4549/// unary-convert to an expression of function-pointer or 4550/// block-pointer type. 4551/// 4552/// \param NDecl the declaration being called, if available 4553ExprResult 4554Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 4555 SourceLocation LParenLoc, 4556 ArrayRef<Expr *> Args, 4557 SourceLocation RParenLoc, 4558 Expr *Config, bool IsExecConfig) { 4559 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 4560 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 4561 4562 // Promote the function operand. 4563 // We special-case function promotion here because we only allow promoting 4564 // builtin functions to function pointers in the callee of a call. 4565 ExprResult Result; 4566 if (BuiltinID && 4567 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 4568 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 4569 CK_BuiltinFnToFnPtr).take(); 4570 } else { 4571 Result = UsualUnaryConversions(Fn); 4572 } 4573 if (Result.isInvalid()) 4574 return ExprError(); 4575 Fn = Result.take(); 4576 4577 // Make the call expr early, before semantic checks. This guarantees cleanup 4578 // of arguments and function on error. 4579 CallExpr *TheCall; 4580 if (Config) 4581 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 4582 cast<CallExpr>(Config), Args, 4583 Context.BoolTy, VK_RValue, 4584 RParenLoc); 4585 else 4586 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 4587 VK_RValue, RParenLoc); 4588 4589 // Bail out early if calling a builtin with custom typechecking. 4590 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 4591 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 4592 4593 retry: 4594 const FunctionType *FuncT; 4595 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 4596 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 4597 // have type pointer to function". 4598 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 4599 if (FuncT == 0) 4600 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4601 << Fn->getType() << Fn->getSourceRange()); 4602 } else if (const BlockPointerType *BPT = 4603 Fn->getType()->getAs<BlockPointerType>()) { 4604 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 4605 } else { 4606 // Handle calls to expressions of unknown-any type. 4607 if (Fn->getType() == Context.UnknownAnyTy) { 4608 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 4609 if (rewrite.isInvalid()) return ExprError(); 4610 Fn = rewrite.take(); 4611 TheCall->setCallee(Fn); 4612 goto retry; 4613 } 4614 4615 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4616 << Fn->getType() << Fn->getSourceRange()); 4617 } 4618 4619 if (getLangOpts().CUDA) { 4620 if (Config) { 4621 // CUDA: Kernel calls must be to global functions 4622 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 4623 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 4624 << FDecl->getName() << Fn->getSourceRange()); 4625 4626 // CUDA: Kernel function must have 'void' return type 4627 if (!FuncT->getResultType()->isVoidType()) 4628 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 4629 << Fn->getType() << Fn->getSourceRange()); 4630 } else { 4631 // CUDA: Calls to global functions must be configured 4632 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 4633 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 4634 << FDecl->getName() << Fn->getSourceRange()); 4635 } 4636 } 4637 4638 // Check for a valid return type 4639 if (CheckCallReturnType(FuncT->getResultType(), 4640 Fn->getLocStart(), TheCall, 4641 FDecl)) 4642 return ExprError(); 4643 4644 // We know the result type of the call, set it. 4645 TheCall->setType(FuncT->getCallResultType(Context)); 4646 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType())); 4647 4648 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 4649 if (Proto) { 4650 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 4651 IsExecConfig)) 4652 return ExprError(); 4653 } else { 4654 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 4655 4656 if (FDecl) { 4657 // Check if we have too few/too many template arguments, based 4658 // on our knowledge of the function definition. 4659 const FunctionDecl *Def = 0; 4660 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 4661 Proto = Def->getType()->getAs<FunctionProtoType>(); 4662 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 4663 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 4664 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 4665 } 4666 4667 // If the function we're calling isn't a function prototype, but we have 4668 // a function prototype from a prior declaratiom, use that prototype. 4669 if (!FDecl->hasPrototype()) 4670 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 4671 } 4672 4673 // Promote the arguments (C99 6.5.2.2p6). 4674 for (unsigned i = 0, e = Args.size(); i != e; i++) { 4675 Expr *Arg = Args[i]; 4676 4677 if (Proto && i < Proto->getNumArgs()) { 4678 InitializedEntity Entity 4679 = InitializedEntity::InitializeParameter(Context, 4680 Proto->getArgType(i), 4681 Proto->isArgConsumed(i)); 4682 ExprResult ArgE = PerformCopyInitialization(Entity, 4683 SourceLocation(), 4684 Owned(Arg)); 4685 if (ArgE.isInvalid()) 4686 return true; 4687 4688 Arg = ArgE.takeAs<Expr>(); 4689 4690 } else { 4691 ExprResult ArgE = DefaultArgumentPromotion(Arg); 4692 4693 if (ArgE.isInvalid()) 4694 return true; 4695 4696 Arg = ArgE.takeAs<Expr>(); 4697 } 4698 4699 if (RequireCompleteType(Arg->getLocStart(), 4700 Arg->getType(), 4701 diag::err_call_incomplete_argument, Arg)) 4702 return ExprError(); 4703 4704 TheCall->setArg(i, Arg); 4705 } 4706 } 4707 4708 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4709 if (!Method->isStatic()) 4710 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 4711 << Fn->getSourceRange()); 4712 4713 // Check for sentinels 4714 if (NDecl) 4715 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 4716 4717 // Do special checking on direct calls to functions. 4718 if (FDecl) { 4719 if (CheckFunctionCall(FDecl, TheCall, Proto)) 4720 return ExprError(); 4721 4722 if (BuiltinID) 4723 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 4724 } else if (NDecl) { 4725 if (CheckPointerCall(NDecl, TheCall, Proto)) 4726 return ExprError(); 4727 } else { 4728 if (CheckOtherCall(TheCall, Proto)) 4729 return ExprError(); 4730 } 4731 4732 return MaybeBindToTemporary(TheCall); 4733} 4734 4735ExprResult 4736Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 4737 SourceLocation RParenLoc, Expr *InitExpr) { 4738 assert(Ty && "ActOnCompoundLiteral(): missing type"); 4739 // FIXME: put back this assert when initializers are worked out. 4740 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 4741 4742 TypeSourceInfo *TInfo; 4743 QualType literalType = GetTypeFromParser(Ty, &TInfo); 4744 if (!TInfo) 4745 TInfo = Context.getTrivialTypeSourceInfo(literalType); 4746 4747 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 4748} 4749 4750ExprResult 4751Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 4752 SourceLocation RParenLoc, Expr *LiteralExpr) { 4753 QualType literalType = TInfo->getType(); 4754 4755 if (literalType->isArrayType()) { 4756 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 4757 diag::err_illegal_decl_array_incomplete_type, 4758 SourceRange(LParenLoc, 4759 LiteralExpr->getSourceRange().getEnd()))) 4760 return ExprError(); 4761 if (literalType->isVariableArrayType()) 4762 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 4763 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 4764 } else if (!literalType->isDependentType() && 4765 RequireCompleteType(LParenLoc, literalType, 4766 diag::err_typecheck_decl_incomplete_type, 4767 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 4768 return ExprError(); 4769 4770 InitializedEntity Entity 4771 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 4772 InitializationKind Kind 4773 = InitializationKind::CreateCStyleCast(LParenLoc, 4774 SourceRange(LParenLoc, RParenLoc), 4775 /*InitList=*/true); 4776 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 4777 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 4778 &literalType); 4779 if (Result.isInvalid()) 4780 return ExprError(); 4781 LiteralExpr = Result.get(); 4782 4783 bool isFileScope = getCurFunctionOrMethodDecl() == 0; 4784 if (isFileScope && 4785 !LiteralExpr->isTypeDependent() && 4786 !LiteralExpr->isValueDependent() && 4787 !literalType->isDependentType()) { // 6.5.2.5p3 4788 if (CheckForConstantInitializer(LiteralExpr, literalType)) 4789 return ExprError(); 4790 } 4791 4792 // In C, compound literals are l-values for some reason. 4793 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 4794 4795 return MaybeBindToTemporary( 4796 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 4797 VK, LiteralExpr, isFileScope)); 4798} 4799 4800ExprResult 4801Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 4802 SourceLocation RBraceLoc) { 4803 // Immediately handle non-overload placeholders. Overloads can be 4804 // resolved contextually, but everything else here can't. 4805 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 4806 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 4807 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 4808 4809 // Ignore failures; dropping the entire initializer list because 4810 // of one failure would be terrible for indexing/etc. 4811 if (result.isInvalid()) continue; 4812 4813 InitArgList[I] = result.take(); 4814 } 4815 } 4816 4817 // Semantic analysis for initializers is done by ActOnDeclarator() and 4818 // CheckInitializer() - it requires knowledge of the object being intialized. 4819 4820 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 4821 RBraceLoc); 4822 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 4823 return Owned(E); 4824} 4825 4826/// Do an explicit extend of the given block pointer if we're in ARC. 4827static void maybeExtendBlockObject(Sema &S, ExprResult &E) { 4828 assert(E.get()->getType()->isBlockPointerType()); 4829 assert(E.get()->isRValue()); 4830 4831 // Only do this in an r-value context. 4832 if (!S.getLangOpts().ObjCAutoRefCount) return; 4833 4834 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), 4835 CK_ARCExtendBlockObject, E.get(), 4836 /*base path*/ 0, VK_RValue); 4837 S.ExprNeedsCleanups = true; 4838} 4839 4840/// Prepare a conversion of the given expression to an ObjC object 4841/// pointer type. 4842CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 4843 QualType type = E.get()->getType(); 4844 if (type->isObjCObjectPointerType()) { 4845 return CK_BitCast; 4846 } else if (type->isBlockPointerType()) { 4847 maybeExtendBlockObject(*this, E); 4848 return CK_BlockPointerToObjCPointerCast; 4849 } else { 4850 assert(type->isPointerType()); 4851 return CK_CPointerToObjCPointerCast; 4852 } 4853} 4854 4855/// Prepares for a scalar cast, performing all the necessary stages 4856/// except the final cast and returning the kind required. 4857CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 4858 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 4859 // Also, callers should have filtered out the invalid cases with 4860 // pointers. Everything else should be possible. 4861 4862 QualType SrcTy = Src.get()->getType(); 4863 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 4864 return CK_NoOp; 4865 4866 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 4867 case Type::STK_MemberPointer: 4868 llvm_unreachable("member pointer type in C"); 4869 4870 case Type::STK_CPointer: 4871 case Type::STK_BlockPointer: 4872 case Type::STK_ObjCObjectPointer: 4873 switch (DestTy->getScalarTypeKind()) { 4874 case Type::STK_CPointer: 4875 return CK_BitCast; 4876 case Type::STK_BlockPointer: 4877 return (SrcKind == Type::STK_BlockPointer 4878 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 4879 case Type::STK_ObjCObjectPointer: 4880 if (SrcKind == Type::STK_ObjCObjectPointer) 4881 return CK_BitCast; 4882 if (SrcKind == Type::STK_CPointer) 4883 return CK_CPointerToObjCPointerCast; 4884 maybeExtendBlockObject(*this, Src); 4885 return CK_BlockPointerToObjCPointerCast; 4886 case Type::STK_Bool: 4887 return CK_PointerToBoolean; 4888 case Type::STK_Integral: 4889 return CK_PointerToIntegral; 4890 case Type::STK_Floating: 4891 case Type::STK_FloatingComplex: 4892 case Type::STK_IntegralComplex: 4893 case Type::STK_MemberPointer: 4894 llvm_unreachable("illegal cast from pointer"); 4895 } 4896 llvm_unreachable("Should have returned before this"); 4897 4898 case Type::STK_Bool: // casting from bool is like casting from an integer 4899 case Type::STK_Integral: 4900 switch (DestTy->getScalarTypeKind()) { 4901 case Type::STK_CPointer: 4902 case Type::STK_ObjCObjectPointer: 4903 case Type::STK_BlockPointer: 4904 if (Src.get()->isNullPointerConstant(Context, 4905 Expr::NPC_ValueDependentIsNull)) 4906 return CK_NullToPointer; 4907 return CK_IntegralToPointer; 4908 case Type::STK_Bool: 4909 return CK_IntegralToBoolean; 4910 case Type::STK_Integral: 4911 return CK_IntegralCast; 4912 case Type::STK_Floating: 4913 return CK_IntegralToFloating; 4914 case Type::STK_IntegralComplex: 4915 Src = ImpCastExprToType(Src.take(), 4916 DestTy->castAs<ComplexType>()->getElementType(), 4917 CK_IntegralCast); 4918 return CK_IntegralRealToComplex; 4919 case Type::STK_FloatingComplex: 4920 Src = ImpCastExprToType(Src.take(), 4921 DestTy->castAs<ComplexType>()->getElementType(), 4922 CK_IntegralToFloating); 4923 return CK_FloatingRealToComplex; 4924 case Type::STK_MemberPointer: 4925 llvm_unreachable("member pointer type in C"); 4926 } 4927 llvm_unreachable("Should have returned before this"); 4928 4929 case Type::STK_Floating: 4930 switch (DestTy->getScalarTypeKind()) { 4931 case Type::STK_Floating: 4932 return CK_FloatingCast; 4933 case Type::STK_Bool: 4934 return CK_FloatingToBoolean; 4935 case Type::STK_Integral: 4936 return CK_FloatingToIntegral; 4937 case Type::STK_FloatingComplex: 4938 Src = ImpCastExprToType(Src.take(), 4939 DestTy->castAs<ComplexType>()->getElementType(), 4940 CK_FloatingCast); 4941 return CK_FloatingRealToComplex; 4942 case Type::STK_IntegralComplex: 4943 Src = ImpCastExprToType(Src.take(), 4944 DestTy->castAs<ComplexType>()->getElementType(), 4945 CK_FloatingToIntegral); 4946 return CK_IntegralRealToComplex; 4947 case Type::STK_CPointer: 4948 case Type::STK_ObjCObjectPointer: 4949 case Type::STK_BlockPointer: 4950 llvm_unreachable("valid float->pointer cast?"); 4951 case Type::STK_MemberPointer: 4952 llvm_unreachable("member pointer type in C"); 4953 } 4954 llvm_unreachable("Should have returned before this"); 4955 4956 case Type::STK_FloatingComplex: 4957 switch (DestTy->getScalarTypeKind()) { 4958 case Type::STK_FloatingComplex: 4959 return CK_FloatingComplexCast; 4960 case Type::STK_IntegralComplex: 4961 return CK_FloatingComplexToIntegralComplex; 4962 case Type::STK_Floating: { 4963 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 4964 if (Context.hasSameType(ET, DestTy)) 4965 return CK_FloatingComplexToReal; 4966 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal); 4967 return CK_FloatingCast; 4968 } 4969 case Type::STK_Bool: 4970 return CK_FloatingComplexToBoolean; 4971 case Type::STK_Integral: 4972 Src = ImpCastExprToType(Src.take(), 4973 SrcTy->castAs<ComplexType>()->getElementType(), 4974 CK_FloatingComplexToReal); 4975 return CK_FloatingToIntegral; 4976 case Type::STK_CPointer: 4977 case Type::STK_ObjCObjectPointer: 4978 case Type::STK_BlockPointer: 4979 llvm_unreachable("valid complex float->pointer cast?"); 4980 case Type::STK_MemberPointer: 4981 llvm_unreachable("member pointer type in C"); 4982 } 4983 llvm_unreachable("Should have returned before this"); 4984 4985 case Type::STK_IntegralComplex: 4986 switch (DestTy->getScalarTypeKind()) { 4987 case Type::STK_FloatingComplex: 4988 return CK_IntegralComplexToFloatingComplex; 4989 case Type::STK_IntegralComplex: 4990 return CK_IntegralComplexCast; 4991 case Type::STK_Integral: { 4992 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 4993 if (Context.hasSameType(ET, DestTy)) 4994 return CK_IntegralComplexToReal; 4995 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal); 4996 return CK_IntegralCast; 4997 } 4998 case Type::STK_Bool: 4999 return CK_IntegralComplexToBoolean; 5000 case Type::STK_Floating: 5001 Src = ImpCastExprToType(Src.take(), 5002 SrcTy->castAs<ComplexType>()->getElementType(), 5003 CK_IntegralComplexToReal); 5004 return CK_IntegralToFloating; 5005 case Type::STK_CPointer: 5006 case Type::STK_ObjCObjectPointer: 5007 case Type::STK_BlockPointer: 5008 llvm_unreachable("valid complex int->pointer cast?"); 5009 case Type::STK_MemberPointer: 5010 llvm_unreachable("member pointer type in C"); 5011 } 5012 llvm_unreachable("Should have returned before this"); 5013 } 5014 5015 llvm_unreachable("Unhandled scalar cast"); 5016} 5017 5018bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5019 CastKind &Kind) { 5020 assert(VectorTy->isVectorType() && "Not a vector type!"); 5021 5022 if (Ty->isVectorType() || Ty->isIntegerType()) { 5023 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty)) 5024 return Diag(R.getBegin(), 5025 Ty->isVectorType() ? 5026 diag::err_invalid_conversion_between_vectors : 5027 diag::err_invalid_conversion_between_vector_and_integer) 5028 << VectorTy << Ty << R; 5029 } else 5030 return Diag(R.getBegin(), 5031 diag::err_invalid_conversion_between_vector_and_scalar) 5032 << VectorTy << Ty << R; 5033 5034 Kind = CK_BitCast; 5035 return false; 5036} 5037 5038ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5039 Expr *CastExpr, CastKind &Kind) { 5040 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5041 5042 QualType SrcTy = CastExpr->getType(); 5043 5044 // If SrcTy is a VectorType, the total size must match to explicitly cast to 5045 // an ExtVectorType. 5046 // In OpenCL, casts between vectors of different types are not allowed. 5047 // (See OpenCL 6.2). 5048 if (SrcTy->isVectorType()) { 5049 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy) 5050 || (getLangOpts().OpenCL && 5051 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 5052 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 5053 << DestTy << SrcTy << R; 5054 return ExprError(); 5055 } 5056 Kind = CK_BitCast; 5057 return Owned(CastExpr); 5058 } 5059 5060 // All non-pointer scalars can be cast to ExtVector type. The appropriate 5061 // conversion will take place first from scalar to elt type, and then 5062 // splat from elt type to vector. 5063 if (SrcTy->isPointerType()) 5064 return Diag(R.getBegin(), 5065 diag::err_invalid_conversion_between_vector_and_scalar) 5066 << DestTy << SrcTy << R; 5067 5068 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType(); 5069 ExprResult CastExprRes = Owned(CastExpr); 5070 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy); 5071 if (CastExprRes.isInvalid()) 5072 return ExprError(); 5073 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take(); 5074 5075 Kind = CK_VectorSplat; 5076 return Owned(CastExpr); 5077} 5078 5079ExprResult 5080Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5081 Declarator &D, ParsedType &Ty, 5082 SourceLocation RParenLoc, Expr *CastExpr) { 5083 assert(!D.isInvalidType() && (CastExpr != 0) && 5084 "ActOnCastExpr(): missing type or expr"); 5085 5086 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 5087 if (D.isInvalidType()) 5088 return ExprError(); 5089 5090 if (getLangOpts().CPlusPlus) { 5091 // Check that there are no default arguments (C++ only). 5092 CheckExtraCXXDefaultArguments(D); 5093 } 5094 5095 checkUnusedDeclAttributes(D); 5096 5097 QualType castType = castTInfo->getType(); 5098 Ty = CreateParsedType(castType, castTInfo); 5099 5100 bool isVectorLiteral = false; 5101 5102 // Check for an altivec or OpenCL literal, 5103 // i.e. all the elements are integer constants. 5104 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 5105 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 5106 if ((getLangOpts().AltiVec || getLangOpts().OpenCL) 5107 && castType->isVectorType() && (PE || PLE)) { 5108 if (PLE && PLE->getNumExprs() == 0) { 5109 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 5110 return ExprError(); 5111 } 5112 if (PE || PLE->getNumExprs() == 1) { 5113 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 5114 if (!E->getType()->isVectorType()) 5115 isVectorLiteral = true; 5116 } 5117 else 5118 isVectorLiteral = true; 5119 } 5120 5121 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 5122 // then handle it as such. 5123 if (isVectorLiteral) 5124 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 5125 5126 // If the Expr being casted is a ParenListExpr, handle it specially. 5127 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 5128 // sequence of BinOp comma operators. 5129 if (isa<ParenListExpr>(CastExpr)) { 5130 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 5131 if (Result.isInvalid()) return ExprError(); 5132 CastExpr = Result.take(); 5133 } 5134 5135 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 5136} 5137 5138ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 5139 SourceLocation RParenLoc, Expr *E, 5140 TypeSourceInfo *TInfo) { 5141 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 5142 "Expected paren or paren list expression"); 5143 5144 Expr **exprs; 5145 unsigned numExprs; 5146 Expr *subExpr; 5147 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 5148 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 5149 LiteralLParenLoc = PE->getLParenLoc(); 5150 LiteralRParenLoc = PE->getRParenLoc(); 5151 exprs = PE->getExprs(); 5152 numExprs = PE->getNumExprs(); 5153 } else { // isa<ParenExpr> by assertion at function entrance 5154 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 5155 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 5156 subExpr = cast<ParenExpr>(E)->getSubExpr(); 5157 exprs = &subExpr; 5158 numExprs = 1; 5159 } 5160 5161 QualType Ty = TInfo->getType(); 5162 assert(Ty->isVectorType() && "Expected vector type"); 5163 5164 SmallVector<Expr *, 8> initExprs; 5165 const VectorType *VTy = Ty->getAs<VectorType>(); 5166 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 5167 5168 // '(...)' form of vector initialization in AltiVec: the number of 5169 // initializers must be one or must match the size of the vector. 5170 // If a single value is specified in the initializer then it will be 5171 // replicated to all the components of the vector 5172 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 5173 // The number of initializers must be one or must match the size of the 5174 // vector. If a single value is specified in the initializer then it will 5175 // be replicated to all the components of the vector 5176 if (numExprs == 1) { 5177 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5178 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5179 if (Literal.isInvalid()) 5180 return ExprError(); 5181 Literal = ImpCastExprToType(Literal.take(), ElemTy, 5182 PrepareScalarCast(Literal, ElemTy)); 5183 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 5184 } 5185 else if (numExprs < numElems) { 5186 Diag(E->getExprLoc(), 5187 diag::err_incorrect_number_of_vector_initializers); 5188 return ExprError(); 5189 } 5190 else 5191 initExprs.append(exprs, exprs + numExprs); 5192 } 5193 else { 5194 // For OpenCL, when the number of initializers is a single value, 5195 // it will be replicated to all components of the vector. 5196 if (getLangOpts().OpenCL && 5197 VTy->getVectorKind() == VectorType::GenericVector && 5198 numExprs == 1) { 5199 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5200 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5201 if (Literal.isInvalid()) 5202 return ExprError(); 5203 Literal = ImpCastExprToType(Literal.take(), ElemTy, 5204 PrepareScalarCast(Literal, ElemTy)); 5205 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 5206 } 5207 5208 initExprs.append(exprs, exprs + numExprs); 5209 } 5210 // FIXME: This means that pretty-printing the final AST will produce curly 5211 // braces instead of the original commas. 5212 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 5213 initExprs, LiteralRParenLoc); 5214 initE->setType(Ty); 5215 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 5216} 5217 5218/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 5219/// the ParenListExpr into a sequence of comma binary operators. 5220ExprResult 5221Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 5222 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 5223 if (!E) 5224 return Owned(OrigExpr); 5225 5226 ExprResult Result(E->getExpr(0)); 5227 5228 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 5229 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 5230 E->getExpr(i)); 5231 5232 if (Result.isInvalid()) return ExprError(); 5233 5234 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 5235} 5236 5237ExprResult Sema::ActOnParenListExpr(SourceLocation L, 5238 SourceLocation R, 5239 MultiExprArg Val) { 5240 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 5241 return Owned(expr); 5242} 5243 5244/// \brief Emit a specialized diagnostic when one expression is a null pointer 5245/// constant and the other is not a pointer. Returns true if a diagnostic is 5246/// emitted. 5247bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 5248 SourceLocation QuestionLoc) { 5249 Expr *NullExpr = LHSExpr; 5250 Expr *NonPointerExpr = RHSExpr; 5251 Expr::NullPointerConstantKind NullKind = 5252 NullExpr->isNullPointerConstant(Context, 5253 Expr::NPC_ValueDependentIsNotNull); 5254 5255 if (NullKind == Expr::NPCK_NotNull) { 5256 NullExpr = RHSExpr; 5257 NonPointerExpr = LHSExpr; 5258 NullKind = 5259 NullExpr->isNullPointerConstant(Context, 5260 Expr::NPC_ValueDependentIsNotNull); 5261 } 5262 5263 if (NullKind == Expr::NPCK_NotNull) 5264 return false; 5265 5266 if (NullKind == Expr::NPCK_ZeroExpression) 5267 return false; 5268 5269 if (NullKind == Expr::NPCK_ZeroLiteral) { 5270 // In this case, check to make sure that we got here from a "NULL" 5271 // string in the source code. 5272 NullExpr = NullExpr->IgnoreParenImpCasts(); 5273 SourceLocation loc = NullExpr->getExprLoc(); 5274 if (!findMacroSpelling(loc, "NULL")) 5275 return false; 5276 } 5277 5278 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 5279 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 5280 << NonPointerExpr->getType() << DiagType 5281 << NonPointerExpr->getSourceRange(); 5282 return true; 5283} 5284 5285/// \brief Return false if the condition expression is valid, true otherwise. 5286static bool checkCondition(Sema &S, Expr *Cond) { 5287 QualType CondTy = Cond->getType(); 5288 5289 // C99 6.5.15p2 5290 if (CondTy->isScalarType()) return false; 5291 5292 // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar. 5293 if (S.getLangOpts().OpenCL && CondTy->isVectorType()) 5294 return false; 5295 5296 // Emit the proper error message. 5297 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ? 5298 diag::err_typecheck_cond_expect_scalar : 5299 diag::err_typecheck_cond_expect_scalar_or_vector) 5300 << CondTy; 5301 return true; 5302} 5303 5304/// \brief Return false if the two expressions can be converted to a vector, 5305/// true otherwise 5306static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS, 5307 ExprResult &RHS, 5308 QualType CondTy) { 5309 // Both operands should be of scalar type. 5310 if (!LHS.get()->getType()->isScalarType()) { 5311 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 5312 << CondTy; 5313 return true; 5314 } 5315 if (!RHS.get()->getType()->isScalarType()) { 5316 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 5317 << CondTy; 5318 return true; 5319 } 5320 5321 // Implicity convert these scalars to the type of the condition. 5322 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast); 5323 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast); 5324 return false; 5325} 5326 5327/// \brief Handle when one or both operands are void type. 5328static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 5329 ExprResult &RHS) { 5330 Expr *LHSExpr = LHS.get(); 5331 Expr *RHSExpr = RHS.get(); 5332 5333 if (!LHSExpr->getType()->isVoidType()) 5334 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5335 << RHSExpr->getSourceRange(); 5336 if (!RHSExpr->getType()->isVoidType()) 5337 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5338 << LHSExpr->getSourceRange(); 5339 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid); 5340 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid); 5341 return S.Context.VoidTy; 5342} 5343 5344/// \brief Return false if the NullExpr can be promoted to PointerTy, 5345/// true otherwise. 5346static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 5347 QualType PointerTy) { 5348 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 5349 !NullExpr.get()->isNullPointerConstant(S.Context, 5350 Expr::NPC_ValueDependentIsNull)) 5351 return true; 5352 5353 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer); 5354 return false; 5355} 5356 5357/// \brief Checks compatibility between two pointers and return the resulting 5358/// type. 5359static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 5360 ExprResult &RHS, 5361 SourceLocation Loc) { 5362 QualType LHSTy = LHS.get()->getType(); 5363 QualType RHSTy = RHS.get()->getType(); 5364 5365 if (S.Context.hasSameType(LHSTy, RHSTy)) { 5366 // Two identical pointers types are always compatible. 5367 return LHSTy; 5368 } 5369 5370 QualType lhptee, rhptee; 5371 5372 // Get the pointee types. 5373 bool IsBlockPointer = false; 5374 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 5375 lhptee = LHSBTy->getPointeeType(); 5376 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 5377 IsBlockPointer = true; 5378 } else { 5379 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 5380 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 5381 } 5382 5383 // C99 6.5.15p6: If both operands are pointers to compatible types or to 5384 // differently qualified versions of compatible types, the result type is 5385 // a pointer to an appropriately qualified version of the composite 5386 // type. 5387 5388 // Only CVR-qualifiers exist in the standard, and the differently-qualified 5389 // clause doesn't make sense for our extensions. E.g. address space 2 should 5390 // be incompatible with address space 3: they may live on different devices or 5391 // anything. 5392 Qualifiers lhQual = lhptee.getQualifiers(); 5393 Qualifiers rhQual = rhptee.getQualifiers(); 5394 5395 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 5396 lhQual.removeCVRQualifiers(); 5397 rhQual.removeCVRQualifiers(); 5398 5399 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 5400 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 5401 5402 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 5403 5404 if (CompositeTy.isNull()) { 5405 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers) 5406 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5407 << RHS.get()->getSourceRange(); 5408 // In this situation, we assume void* type. No especially good 5409 // reason, but this is what gcc does, and we do have to pick 5410 // to get a consistent AST. 5411 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy); 5412 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 5413 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 5414 return incompatTy; 5415 } 5416 5417 // The pointer types are compatible. 5418 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 5419 if (IsBlockPointer) 5420 ResultTy = S.Context.getBlockPointerType(ResultTy); 5421 else 5422 ResultTy = S.Context.getPointerType(ResultTy); 5423 5424 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast); 5425 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast); 5426 return ResultTy; 5427} 5428 5429/// \brief Return the resulting type when the operands are both block pointers. 5430static QualType checkConditionalBlockPointerCompatibility(Sema &S, 5431 ExprResult &LHS, 5432 ExprResult &RHS, 5433 SourceLocation Loc) { 5434 QualType LHSTy = LHS.get()->getType(); 5435 QualType RHSTy = RHS.get()->getType(); 5436 5437 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 5438 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 5439 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 5440 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5441 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5442 return destType; 5443 } 5444 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 5445 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5446 << RHS.get()->getSourceRange(); 5447 return QualType(); 5448 } 5449 5450 // We have 2 block pointer types. 5451 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 5452} 5453 5454/// \brief Return the resulting type when the operands are both pointers. 5455static QualType 5456checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 5457 ExprResult &RHS, 5458 SourceLocation Loc) { 5459 // get the pointer types 5460 QualType LHSTy = LHS.get()->getType(); 5461 QualType RHSTy = RHS.get()->getType(); 5462 5463 // get the "pointed to" types 5464 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5465 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5466 5467 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 5468 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 5469 // Figure out necessary qualifiers (C99 6.5.15p6) 5470 QualType destPointee 5471 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5472 QualType destType = S.Context.getPointerType(destPointee); 5473 // Add qualifiers if necessary. 5474 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp); 5475 // Promote to void*. 5476 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5477 return destType; 5478 } 5479 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 5480 QualType destPointee 5481 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5482 QualType destType = S.Context.getPointerType(destPointee); 5483 // Add qualifiers if necessary. 5484 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp); 5485 // Promote to void*. 5486 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5487 return destType; 5488 } 5489 5490 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 5491} 5492 5493/// \brief Return false if the first expression is not an integer and the second 5494/// expression is not a pointer, true otherwise. 5495static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 5496 Expr* PointerExpr, SourceLocation Loc, 5497 bool IsIntFirstExpr) { 5498 if (!PointerExpr->getType()->isPointerType() || 5499 !Int.get()->getType()->isIntegerType()) 5500 return false; 5501 5502 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 5503 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 5504 5505 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch) 5506 << Expr1->getType() << Expr2->getType() 5507 << Expr1->getSourceRange() << Expr2->getSourceRange(); 5508 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(), 5509 CK_IntegralToPointer); 5510 return true; 5511} 5512 5513/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 5514/// In that case, LHS = cond. 5515/// C99 6.5.15 5516QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 5517 ExprResult &RHS, ExprValueKind &VK, 5518 ExprObjectKind &OK, 5519 SourceLocation QuestionLoc) { 5520 5521 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 5522 if (!LHSResult.isUsable()) return QualType(); 5523 LHS = LHSResult; 5524 5525 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 5526 if (!RHSResult.isUsable()) return QualType(); 5527 RHS = RHSResult; 5528 5529 // C++ is sufficiently different to merit its own checker. 5530 if (getLangOpts().CPlusPlus) 5531 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 5532 5533 VK = VK_RValue; 5534 OK = OK_Ordinary; 5535 5536 // First, check the condition. 5537 Cond = UsualUnaryConversions(Cond.take()); 5538 if (Cond.isInvalid()) 5539 return QualType(); 5540 if (checkCondition(*this, Cond.get())) 5541 return QualType(); 5542 5543 // Now check the two expressions. 5544 if (LHS.get()->getType()->isVectorType() || 5545 RHS.get()->getType()->isVectorType()) 5546 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false); 5547 5548 UsualArithmeticConversions(LHS, RHS); 5549 if (LHS.isInvalid() || RHS.isInvalid()) 5550 return QualType(); 5551 5552 QualType CondTy = Cond.get()->getType(); 5553 QualType LHSTy = LHS.get()->getType(); 5554 QualType RHSTy = RHS.get()->getType(); 5555 5556 // If the condition is a vector, and both operands are scalar, 5557 // attempt to implicity convert them to the vector type to act like the 5558 // built in select. (OpenCL v1.1 s6.3.i) 5559 if (getLangOpts().OpenCL && CondTy->isVectorType()) 5560 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy)) 5561 return QualType(); 5562 5563 // If both operands have arithmetic type, do the usual arithmetic conversions 5564 // to find a common type: C99 6.5.15p3,5. 5565 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) 5566 return LHS.get()->getType(); 5567 5568 // If both operands are the same structure or union type, the result is that 5569 // type. 5570 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 5571 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 5572 if (LHSRT->getDecl() == RHSRT->getDecl()) 5573 // "If both the operands have structure or union type, the result has 5574 // that type." This implies that CV qualifiers are dropped. 5575 return LHSTy.getUnqualifiedType(); 5576 // FIXME: Type of conditional expression must be complete in C mode. 5577 } 5578 5579 // C99 6.5.15p5: "If both operands have void type, the result has void type." 5580 // The following || allows only one side to be void (a GCC-ism). 5581 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 5582 return checkConditionalVoidType(*this, LHS, RHS); 5583 } 5584 5585 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 5586 // the type of the other operand." 5587 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 5588 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 5589 5590 // All objective-c pointer type analysis is done here. 5591 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 5592 QuestionLoc); 5593 if (LHS.isInvalid() || RHS.isInvalid()) 5594 return QualType(); 5595 if (!compositeType.isNull()) 5596 return compositeType; 5597 5598 5599 // Handle block pointer types. 5600 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 5601 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 5602 QuestionLoc); 5603 5604 // Check constraints for C object pointers types (C99 6.5.15p3,6). 5605 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 5606 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 5607 QuestionLoc); 5608 5609 // GCC compatibility: soften pointer/integer mismatch. Note that 5610 // null pointers have been filtered out by this point. 5611 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 5612 /*isIntFirstExpr=*/true)) 5613 return RHSTy; 5614 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 5615 /*isIntFirstExpr=*/false)) 5616 return LHSTy; 5617 5618 // Emit a better diagnostic if one of the expressions is a null pointer 5619 // constant and the other is not a pointer type. In this case, the user most 5620 // likely forgot to take the address of the other expression. 5621 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 5622 return QualType(); 5623 5624 // Otherwise, the operands are not compatible. 5625 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 5626 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5627 << RHS.get()->getSourceRange(); 5628 return QualType(); 5629} 5630 5631/// FindCompositeObjCPointerType - Helper method to find composite type of 5632/// two objective-c pointer types of the two input expressions. 5633QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 5634 SourceLocation QuestionLoc) { 5635 QualType LHSTy = LHS.get()->getType(); 5636 QualType RHSTy = RHS.get()->getType(); 5637 5638 // Handle things like Class and struct objc_class*. Here we case the result 5639 // to the pseudo-builtin, because that will be implicitly cast back to the 5640 // redefinition type if an attempt is made to access its fields. 5641 if (LHSTy->isObjCClassType() && 5642 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 5643 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 5644 return LHSTy; 5645 } 5646 if (RHSTy->isObjCClassType() && 5647 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 5648 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 5649 return RHSTy; 5650 } 5651 // And the same for struct objc_object* / id 5652 if (LHSTy->isObjCIdType() && 5653 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 5654 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 5655 return LHSTy; 5656 } 5657 if (RHSTy->isObjCIdType() && 5658 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 5659 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 5660 return RHSTy; 5661 } 5662 // And the same for struct objc_selector* / SEL 5663 if (Context.isObjCSelType(LHSTy) && 5664 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 5665 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast); 5666 return LHSTy; 5667 } 5668 if (Context.isObjCSelType(RHSTy) && 5669 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 5670 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast); 5671 return RHSTy; 5672 } 5673 // Check constraints for Objective-C object pointers types. 5674 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 5675 5676 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 5677 // Two identical object pointer types are always compatible. 5678 return LHSTy; 5679 } 5680 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 5681 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 5682 QualType compositeType = LHSTy; 5683 5684 // If both operands are interfaces and either operand can be 5685 // assigned to the other, use that type as the composite 5686 // type. This allows 5687 // xxx ? (A*) a : (B*) b 5688 // where B is a subclass of A. 5689 // 5690 // Additionally, as for assignment, if either type is 'id' 5691 // allow silent coercion. Finally, if the types are 5692 // incompatible then make sure to use 'id' as the composite 5693 // type so the result is acceptable for sending messages to. 5694 5695 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 5696 // It could return the composite type. 5697 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 5698 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 5699 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 5700 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 5701 } else if ((LHSTy->isObjCQualifiedIdType() || 5702 RHSTy->isObjCQualifiedIdType()) && 5703 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 5704 // Need to handle "id<xx>" explicitly. 5705 // GCC allows qualified id and any Objective-C type to devolve to 5706 // id. Currently localizing to here until clear this should be 5707 // part of ObjCQualifiedIdTypesAreCompatible. 5708 compositeType = Context.getObjCIdType(); 5709 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 5710 compositeType = Context.getObjCIdType(); 5711 } else if (!(compositeType = 5712 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) 5713 ; 5714 else { 5715 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 5716 << LHSTy << RHSTy 5717 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5718 QualType incompatTy = Context.getObjCIdType(); 5719 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 5720 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 5721 return incompatTy; 5722 } 5723 // The object pointer types are compatible. 5724 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast); 5725 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast); 5726 return compositeType; 5727 } 5728 // Check Objective-C object pointer types and 'void *' 5729 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 5730 if (getLangOpts().ObjCAutoRefCount) { 5731 // ARC forbids the implicit conversion of object pointers to 'void *', 5732 // so these types are not compatible. 5733 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 5734 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5735 LHS = RHS = true; 5736 return QualType(); 5737 } 5738 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5739 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5740 QualType destPointee 5741 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5742 QualType destType = Context.getPointerType(destPointee); 5743 // Add qualifiers if necessary. 5744 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp); 5745 // Promote to void*. 5746 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5747 return destType; 5748 } 5749 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 5750 if (getLangOpts().ObjCAutoRefCount) { 5751 // ARC forbids the implicit conversion of object pointers to 'void *', 5752 // so these types are not compatible. 5753 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 5754 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5755 LHS = RHS = true; 5756 return QualType(); 5757 } 5758 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5759 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5760 QualType destPointee 5761 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5762 QualType destType = Context.getPointerType(destPointee); 5763 // Add qualifiers if necessary. 5764 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp); 5765 // Promote to void*. 5766 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5767 return destType; 5768 } 5769 return QualType(); 5770} 5771 5772/// SuggestParentheses - Emit a note with a fixit hint that wraps 5773/// ParenRange in parentheses. 5774static void SuggestParentheses(Sema &Self, SourceLocation Loc, 5775 const PartialDiagnostic &Note, 5776 SourceRange ParenRange) { 5777 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd()); 5778 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 5779 EndLoc.isValid()) { 5780 Self.Diag(Loc, Note) 5781 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 5782 << FixItHint::CreateInsertion(EndLoc, ")"); 5783 } else { 5784 // We can't display the parentheses, so just show the bare note. 5785 Self.Diag(Loc, Note) << ParenRange; 5786 } 5787} 5788 5789static bool IsArithmeticOp(BinaryOperatorKind Opc) { 5790 return Opc >= BO_Mul && Opc <= BO_Shr; 5791} 5792 5793/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 5794/// expression, either using a built-in or overloaded operator, 5795/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 5796/// expression. 5797static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 5798 Expr **RHSExprs) { 5799 // Don't strip parenthesis: we should not warn if E is in parenthesis. 5800 E = E->IgnoreImpCasts(); 5801 E = E->IgnoreConversionOperator(); 5802 E = E->IgnoreImpCasts(); 5803 5804 // Built-in binary operator. 5805 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 5806 if (IsArithmeticOp(OP->getOpcode())) { 5807 *Opcode = OP->getOpcode(); 5808 *RHSExprs = OP->getRHS(); 5809 return true; 5810 } 5811 } 5812 5813 // Overloaded operator. 5814 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 5815 if (Call->getNumArgs() != 2) 5816 return false; 5817 5818 // Make sure this is really a binary operator that is safe to pass into 5819 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 5820 OverloadedOperatorKind OO = Call->getOperator(); 5821 if (OO < OO_Plus || OO > OO_Arrow || 5822 OO == OO_PlusPlus || OO == OO_MinusMinus) 5823 return false; 5824 5825 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 5826 if (IsArithmeticOp(OpKind)) { 5827 *Opcode = OpKind; 5828 *RHSExprs = Call->getArg(1); 5829 return true; 5830 } 5831 } 5832 5833 return false; 5834} 5835 5836static bool IsLogicOp(BinaryOperatorKind Opc) { 5837 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr); 5838} 5839 5840/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 5841/// or is a logical expression such as (x==y) which has int type, but is 5842/// commonly interpreted as boolean. 5843static bool ExprLooksBoolean(Expr *E) { 5844 E = E->IgnoreParenImpCasts(); 5845 5846 if (E->getType()->isBooleanType()) 5847 return true; 5848 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 5849 return IsLogicOp(OP->getOpcode()); 5850 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 5851 return OP->getOpcode() == UO_LNot; 5852 5853 return false; 5854} 5855 5856/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 5857/// and binary operator are mixed in a way that suggests the programmer assumed 5858/// the conditional operator has higher precedence, for example: 5859/// "int x = a + someBinaryCondition ? 1 : 2". 5860static void DiagnoseConditionalPrecedence(Sema &Self, 5861 SourceLocation OpLoc, 5862 Expr *Condition, 5863 Expr *LHSExpr, 5864 Expr *RHSExpr) { 5865 BinaryOperatorKind CondOpcode; 5866 Expr *CondRHS; 5867 5868 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 5869 return; 5870 if (!ExprLooksBoolean(CondRHS)) 5871 return; 5872 5873 // The condition is an arithmetic binary expression, with a right- 5874 // hand side that looks boolean, so warn. 5875 5876 Self.Diag(OpLoc, diag::warn_precedence_conditional) 5877 << Condition->getSourceRange() 5878 << BinaryOperator::getOpcodeStr(CondOpcode); 5879 5880 SuggestParentheses(Self, OpLoc, 5881 Self.PDiag(diag::note_precedence_silence) 5882 << BinaryOperator::getOpcodeStr(CondOpcode), 5883 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 5884 5885 SuggestParentheses(Self, OpLoc, 5886 Self.PDiag(diag::note_precedence_conditional_first), 5887 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 5888} 5889 5890/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 5891/// in the case of a the GNU conditional expr extension. 5892ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 5893 SourceLocation ColonLoc, 5894 Expr *CondExpr, Expr *LHSExpr, 5895 Expr *RHSExpr) { 5896 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 5897 // was the condition. 5898 OpaqueValueExpr *opaqueValue = 0; 5899 Expr *commonExpr = 0; 5900 if (LHSExpr == 0) { 5901 commonExpr = CondExpr; 5902 // Lower out placeholder types first. This is important so that we don't 5903 // try to capture a placeholder. This happens in few cases in C++; such 5904 // as Objective-C++'s dictionary subscripting syntax. 5905 if (commonExpr->hasPlaceholderType()) { 5906 ExprResult result = CheckPlaceholderExpr(commonExpr); 5907 if (!result.isUsable()) return ExprError(); 5908 commonExpr = result.take(); 5909 } 5910 // We usually want to apply unary conversions *before* saving, except 5911 // in the special case of a C++ l-value conditional. 5912 if (!(getLangOpts().CPlusPlus 5913 && !commonExpr->isTypeDependent() 5914 && commonExpr->getValueKind() == RHSExpr->getValueKind() 5915 && commonExpr->isGLValue() 5916 && commonExpr->isOrdinaryOrBitFieldObject() 5917 && RHSExpr->isOrdinaryOrBitFieldObject() 5918 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 5919 ExprResult commonRes = UsualUnaryConversions(commonExpr); 5920 if (commonRes.isInvalid()) 5921 return ExprError(); 5922 commonExpr = commonRes.take(); 5923 } 5924 5925 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 5926 commonExpr->getType(), 5927 commonExpr->getValueKind(), 5928 commonExpr->getObjectKind(), 5929 commonExpr); 5930 LHSExpr = CondExpr = opaqueValue; 5931 } 5932 5933 ExprValueKind VK = VK_RValue; 5934 ExprObjectKind OK = OK_Ordinary; 5935 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 5936 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 5937 VK, OK, QuestionLoc); 5938 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 5939 RHS.isInvalid()) 5940 return ExprError(); 5941 5942 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 5943 RHS.get()); 5944 5945 if (!commonExpr) 5946 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc, 5947 LHS.take(), ColonLoc, 5948 RHS.take(), result, VK, OK)); 5949 5950 return Owned(new (Context) 5951 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(), 5952 RHS.take(), QuestionLoc, ColonLoc, result, VK, 5953 OK)); 5954} 5955 5956// checkPointerTypesForAssignment - This is a very tricky routine (despite 5957// being closely modeled after the C99 spec:-). The odd characteristic of this 5958// routine is it effectively iqnores the qualifiers on the top level pointee. 5959// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 5960// FIXME: add a couple examples in this comment. 5961static Sema::AssignConvertType 5962checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 5963 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 5964 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 5965 5966 // get the "pointed to" type (ignoring qualifiers at the top level) 5967 const Type *lhptee, *rhptee; 5968 Qualifiers lhq, rhq; 5969 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split(); 5970 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split(); 5971 5972 Sema::AssignConvertType ConvTy = Sema::Compatible; 5973 5974 // C99 6.5.16.1p1: This following citation is common to constraints 5975 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 5976 // qualifiers of the type *pointed to* by the right; 5977 Qualifiers lq; 5978 5979 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 5980 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 5981 lhq.compatiblyIncludesObjCLifetime(rhq)) { 5982 // Ignore lifetime for further calculation. 5983 lhq.removeObjCLifetime(); 5984 rhq.removeObjCLifetime(); 5985 } 5986 5987 if (!lhq.compatiblyIncludes(rhq)) { 5988 // Treat address-space mismatches as fatal. TODO: address subspaces 5989 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 5990 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 5991 5992 // It's okay to add or remove GC or lifetime qualifiers when converting to 5993 // and from void*. 5994 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 5995 .compatiblyIncludes( 5996 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 5997 && (lhptee->isVoidType() || rhptee->isVoidType())) 5998 ; // keep old 5999 6000 // Treat lifetime mismatches as fatal. 6001 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 6002 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 6003 6004 // For GCC compatibility, other qualifier mismatches are treated 6005 // as still compatible in C. 6006 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 6007 } 6008 6009 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 6010 // incomplete type and the other is a pointer to a qualified or unqualified 6011 // version of void... 6012 if (lhptee->isVoidType()) { 6013 if (rhptee->isIncompleteOrObjectType()) 6014 return ConvTy; 6015 6016 // As an extension, we allow cast to/from void* to function pointer. 6017 assert(rhptee->isFunctionType()); 6018 return Sema::FunctionVoidPointer; 6019 } 6020 6021 if (rhptee->isVoidType()) { 6022 if (lhptee->isIncompleteOrObjectType()) 6023 return ConvTy; 6024 6025 // As an extension, we allow cast to/from void* to function pointer. 6026 assert(lhptee->isFunctionType()); 6027 return Sema::FunctionVoidPointer; 6028 } 6029 6030 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 6031 // unqualified versions of compatible types, ... 6032 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 6033 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 6034 // Check if the pointee types are compatible ignoring the sign. 6035 // We explicitly check for char so that we catch "char" vs 6036 // "unsigned char" on systems where "char" is unsigned. 6037 if (lhptee->isCharType()) 6038 ltrans = S.Context.UnsignedCharTy; 6039 else if (lhptee->hasSignedIntegerRepresentation()) 6040 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 6041 6042 if (rhptee->isCharType()) 6043 rtrans = S.Context.UnsignedCharTy; 6044 else if (rhptee->hasSignedIntegerRepresentation()) 6045 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 6046 6047 if (ltrans == rtrans) { 6048 // Types are compatible ignoring the sign. Qualifier incompatibility 6049 // takes priority over sign incompatibility because the sign 6050 // warning can be disabled. 6051 if (ConvTy != Sema::Compatible) 6052 return ConvTy; 6053 6054 return Sema::IncompatiblePointerSign; 6055 } 6056 6057 // If we are a multi-level pointer, it's possible that our issue is simply 6058 // one of qualification - e.g. char ** -> const char ** is not allowed. If 6059 // the eventual target type is the same and the pointers have the same 6060 // level of indirection, this must be the issue. 6061 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 6062 do { 6063 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 6064 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 6065 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 6066 6067 if (lhptee == rhptee) 6068 return Sema::IncompatibleNestedPointerQualifiers; 6069 } 6070 6071 // General pointer incompatibility takes priority over qualifiers. 6072 return Sema::IncompatiblePointer; 6073 } 6074 if (!S.getLangOpts().CPlusPlus && 6075 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 6076 return Sema::IncompatiblePointer; 6077 return ConvTy; 6078} 6079 6080/// checkBlockPointerTypesForAssignment - This routine determines whether two 6081/// block pointer types are compatible or whether a block and normal pointer 6082/// are compatible. It is more restrict than comparing two function pointer 6083// types. 6084static Sema::AssignConvertType 6085checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 6086 QualType RHSType) { 6087 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 6088 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 6089 6090 QualType lhptee, rhptee; 6091 6092 // get the "pointed to" type (ignoring qualifiers at the top level) 6093 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 6094 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 6095 6096 // In C++, the types have to match exactly. 6097 if (S.getLangOpts().CPlusPlus) 6098 return Sema::IncompatibleBlockPointer; 6099 6100 Sema::AssignConvertType ConvTy = Sema::Compatible; 6101 6102 // For blocks we enforce that qualifiers are identical. 6103 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 6104 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 6105 6106 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 6107 return Sema::IncompatibleBlockPointer; 6108 6109 return ConvTy; 6110} 6111 6112/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 6113/// for assignment compatibility. 6114static Sema::AssignConvertType 6115checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 6116 QualType RHSType) { 6117 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 6118 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 6119 6120 if (LHSType->isObjCBuiltinType()) { 6121 // Class is not compatible with ObjC object pointers. 6122 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 6123 !RHSType->isObjCQualifiedClassType()) 6124 return Sema::IncompatiblePointer; 6125 return Sema::Compatible; 6126 } 6127 if (RHSType->isObjCBuiltinType()) { 6128 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 6129 !LHSType->isObjCQualifiedClassType()) 6130 return Sema::IncompatiblePointer; 6131 return Sema::Compatible; 6132 } 6133 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 6134 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 6135 6136 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 6137 // make an exception for id<P> 6138 !LHSType->isObjCQualifiedIdType()) 6139 return Sema::CompatiblePointerDiscardsQualifiers; 6140 6141 if (S.Context.typesAreCompatible(LHSType, RHSType)) 6142 return Sema::Compatible; 6143 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 6144 return Sema::IncompatibleObjCQualifiedId; 6145 return Sema::IncompatiblePointer; 6146} 6147 6148Sema::AssignConvertType 6149Sema::CheckAssignmentConstraints(SourceLocation Loc, 6150 QualType LHSType, QualType RHSType) { 6151 // Fake up an opaque expression. We don't actually care about what 6152 // cast operations are required, so if CheckAssignmentConstraints 6153 // adds casts to this they'll be wasted, but fortunately that doesn't 6154 // usually happen on valid code. 6155 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 6156 ExprResult RHSPtr = &RHSExpr; 6157 CastKind K = CK_Invalid; 6158 6159 return CheckAssignmentConstraints(LHSType, RHSPtr, K); 6160} 6161 6162/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 6163/// has code to accommodate several GCC extensions when type checking 6164/// pointers. Here are some objectionable examples that GCC considers warnings: 6165/// 6166/// int a, *pint; 6167/// short *pshort; 6168/// struct foo *pfoo; 6169/// 6170/// pint = pshort; // warning: assignment from incompatible pointer type 6171/// a = pint; // warning: assignment makes integer from pointer without a cast 6172/// pint = a; // warning: assignment makes pointer from integer without a cast 6173/// pint = pfoo; // warning: assignment from incompatible pointer type 6174/// 6175/// As a result, the code for dealing with pointers is more complex than the 6176/// C99 spec dictates. 6177/// 6178/// Sets 'Kind' for any result kind except Incompatible. 6179Sema::AssignConvertType 6180Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 6181 CastKind &Kind) { 6182 QualType RHSType = RHS.get()->getType(); 6183 QualType OrigLHSType = LHSType; 6184 6185 // Get canonical types. We're not formatting these types, just comparing 6186 // them. 6187 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 6188 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 6189 6190 // Common case: no conversion required. 6191 if (LHSType == RHSType) { 6192 Kind = CK_NoOp; 6193 return Compatible; 6194 } 6195 6196 // If we have an atomic type, try a non-atomic assignment, then just add an 6197 // atomic qualification step. 6198 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 6199 Sema::AssignConvertType result = 6200 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 6201 if (result != Compatible) 6202 return result; 6203 if (Kind != CK_NoOp) 6204 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind); 6205 Kind = CK_NonAtomicToAtomic; 6206 return Compatible; 6207 } 6208 6209 // If the left-hand side is a reference type, then we are in a 6210 // (rare!) case where we've allowed the use of references in C, 6211 // e.g., as a parameter type in a built-in function. In this case, 6212 // just make sure that the type referenced is compatible with the 6213 // right-hand side type. The caller is responsible for adjusting 6214 // LHSType so that the resulting expression does not have reference 6215 // type. 6216 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 6217 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 6218 Kind = CK_LValueBitCast; 6219 return Compatible; 6220 } 6221 return Incompatible; 6222 } 6223 6224 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 6225 // to the same ExtVector type. 6226 if (LHSType->isExtVectorType()) { 6227 if (RHSType->isExtVectorType()) 6228 return Incompatible; 6229 if (RHSType->isArithmeticType()) { 6230 // CK_VectorSplat does T -> vector T, so first cast to the 6231 // element type. 6232 QualType elType = cast<ExtVectorType>(LHSType)->getElementType(); 6233 if (elType != RHSType) { 6234 Kind = PrepareScalarCast(RHS, elType); 6235 RHS = ImpCastExprToType(RHS.take(), elType, Kind); 6236 } 6237 Kind = CK_VectorSplat; 6238 return Compatible; 6239 } 6240 } 6241 6242 // Conversions to or from vector type. 6243 if (LHSType->isVectorType() || RHSType->isVectorType()) { 6244 if (LHSType->isVectorType() && RHSType->isVectorType()) { 6245 // Allow assignments of an AltiVec vector type to an equivalent GCC 6246 // vector type and vice versa 6247 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 6248 Kind = CK_BitCast; 6249 return Compatible; 6250 } 6251 6252 // If we are allowing lax vector conversions, and LHS and RHS are both 6253 // vectors, the total size only needs to be the same. This is a bitcast; 6254 // no bits are changed but the result type is different. 6255 if (getLangOpts().LaxVectorConversions && 6256 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) { 6257 Kind = CK_BitCast; 6258 return IncompatibleVectors; 6259 } 6260 } 6261 return Incompatible; 6262 } 6263 6264 // Arithmetic conversions. 6265 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 6266 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 6267 Kind = PrepareScalarCast(RHS, LHSType); 6268 return Compatible; 6269 } 6270 6271 // Conversions to normal pointers. 6272 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 6273 // U* -> T* 6274 if (isa<PointerType>(RHSType)) { 6275 Kind = CK_BitCast; 6276 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 6277 } 6278 6279 // int -> T* 6280 if (RHSType->isIntegerType()) { 6281 Kind = CK_IntegralToPointer; // FIXME: null? 6282 return IntToPointer; 6283 } 6284 6285 // C pointers are not compatible with ObjC object pointers, 6286 // with two exceptions: 6287 if (isa<ObjCObjectPointerType>(RHSType)) { 6288 // - conversions to void* 6289 if (LHSPointer->getPointeeType()->isVoidType()) { 6290 Kind = CK_BitCast; 6291 return Compatible; 6292 } 6293 6294 // - conversions from 'Class' to the redefinition type 6295 if (RHSType->isObjCClassType() && 6296 Context.hasSameType(LHSType, 6297 Context.getObjCClassRedefinitionType())) { 6298 Kind = CK_BitCast; 6299 return Compatible; 6300 } 6301 6302 Kind = CK_BitCast; 6303 return IncompatiblePointer; 6304 } 6305 6306 // U^ -> void* 6307 if (RHSType->getAs<BlockPointerType>()) { 6308 if (LHSPointer->getPointeeType()->isVoidType()) { 6309 Kind = CK_BitCast; 6310 return Compatible; 6311 } 6312 } 6313 6314 return Incompatible; 6315 } 6316 6317 // Conversions to block pointers. 6318 if (isa<BlockPointerType>(LHSType)) { 6319 // U^ -> T^ 6320 if (RHSType->isBlockPointerType()) { 6321 Kind = CK_BitCast; 6322 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 6323 } 6324 6325 // int or null -> T^ 6326 if (RHSType->isIntegerType()) { 6327 Kind = CK_IntegralToPointer; // FIXME: null 6328 return IntToBlockPointer; 6329 } 6330 6331 // id -> T^ 6332 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 6333 Kind = CK_AnyPointerToBlockPointerCast; 6334 return Compatible; 6335 } 6336 6337 // void* -> T^ 6338 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 6339 if (RHSPT->getPointeeType()->isVoidType()) { 6340 Kind = CK_AnyPointerToBlockPointerCast; 6341 return Compatible; 6342 } 6343 6344 return Incompatible; 6345 } 6346 6347 // Conversions to Objective-C pointers. 6348 if (isa<ObjCObjectPointerType>(LHSType)) { 6349 // A* -> B* 6350 if (RHSType->isObjCObjectPointerType()) { 6351 Kind = CK_BitCast; 6352 Sema::AssignConvertType result = 6353 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 6354 if (getLangOpts().ObjCAutoRefCount && 6355 result == Compatible && 6356 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 6357 result = IncompatibleObjCWeakRef; 6358 return result; 6359 } 6360 6361 // int or null -> A* 6362 if (RHSType->isIntegerType()) { 6363 Kind = CK_IntegralToPointer; // FIXME: null 6364 return IntToPointer; 6365 } 6366 6367 // In general, C pointers are not compatible with ObjC object pointers, 6368 // with two exceptions: 6369 if (isa<PointerType>(RHSType)) { 6370 Kind = CK_CPointerToObjCPointerCast; 6371 6372 // - conversions from 'void*' 6373 if (RHSType->isVoidPointerType()) { 6374 return Compatible; 6375 } 6376 6377 // - conversions to 'Class' from its redefinition type 6378 if (LHSType->isObjCClassType() && 6379 Context.hasSameType(RHSType, 6380 Context.getObjCClassRedefinitionType())) { 6381 return Compatible; 6382 } 6383 6384 return IncompatiblePointer; 6385 } 6386 6387 // T^ -> A* 6388 if (RHSType->isBlockPointerType()) { 6389 maybeExtendBlockObject(*this, RHS); 6390 Kind = CK_BlockPointerToObjCPointerCast; 6391 return Compatible; 6392 } 6393 6394 return Incompatible; 6395 } 6396 6397 // Conversions from pointers that are not covered by the above. 6398 if (isa<PointerType>(RHSType)) { 6399 // T* -> _Bool 6400 if (LHSType == Context.BoolTy) { 6401 Kind = CK_PointerToBoolean; 6402 return Compatible; 6403 } 6404 6405 // T* -> int 6406 if (LHSType->isIntegerType()) { 6407 Kind = CK_PointerToIntegral; 6408 return PointerToInt; 6409 } 6410 6411 return Incompatible; 6412 } 6413 6414 // Conversions from Objective-C pointers that are not covered by the above. 6415 if (isa<ObjCObjectPointerType>(RHSType)) { 6416 // T* -> _Bool 6417 if (LHSType == Context.BoolTy) { 6418 Kind = CK_PointerToBoolean; 6419 return Compatible; 6420 } 6421 6422 // T* -> int 6423 if (LHSType->isIntegerType()) { 6424 Kind = CK_PointerToIntegral; 6425 return PointerToInt; 6426 } 6427 6428 return Incompatible; 6429 } 6430 6431 // struct A -> struct B 6432 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 6433 if (Context.typesAreCompatible(LHSType, RHSType)) { 6434 Kind = CK_NoOp; 6435 return Compatible; 6436 } 6437 } 6438 6439 return Incompatible; 6440} 6441 6442/// \brief Constructs a transparent union from an expression that is 6443/// used to initialize the transparent union. 6444static void ConstructTransparentUnion(Sema &S, ASTContext &C, 6445 ExprResult &EResult, QualType UnionType, 6446 FieldDecl *Field) { 6447 // Build an initializer list that designates the appropriate member 6448 // of the transparent union. 6449 Expr *E = EResult.take(); 6450 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 6451 E, SourceLocation()); 6452 Initializer->setType(UnionType); 6453 Initializer->setInitializedFieldInUnion(Field); 6454 6455 // Build a compound literal constructing a value of the transparent 6456 // union type from this initializer list. 6457 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 6458 EResult = S.Owned( 6459 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 6460 VK_RValue, Initializer, false)); 6461} 6462 6463Sema::AssignConvertType 6464Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 6465 ExprResult &RHS) { 6466 QualType RHSType = RHS.get()->getType(); 6467 6468 // If the ArgType is a Union type, we want to handle a potential 6469 // transparent_union GCC extension. 6470 const RecordType *UT = ArgType->getAsUnionType(); 6471 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 6472 return Incompatible; 6473 6474 // The field to initialize within the transparent union. 6475 RecordDecl *UD = UT->getDecl(); 6476 FieldDecl *InitField = 0; 6477 // It's compatible if the expression matches any of the fields. 6478 for (RecordDecl::field_iterator it = UD->field_begin(), 6479 itend = UD->field_end(); 6480 it != itend; ++it) { 6481 if (it->getType()->isPointerType()) { 6482 // If the transparent union contains a pointer type, we allow: 6483 // 1) void pointer 6484 // 2) null pointer constant 6485 if (RHSType->isPointerType()) 6486 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 6487 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast); 6488 InitField = *it; 6489 break; 6490 } 6491 6492 if (RHS.get()->isNullPointerConstant(Context, 6493 Expr::NPC_ValueDependentIsNull)) { 6494 RHS = ImpCastExprToType(RHS.take(), it->getType(), 6495 CK_NullToPointer); 6496 InitField = *it; 6497 break; 6498 } 6499 } 6500 6501 CastKind Kind = CK_Invalid; 6502 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 6503 == Compatible) { 6504 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind); 6505 InitField = *it; 6506 break; 6507 } 6508 } 6509 6510 if (!InitField) 6511 return Incompatible; 6512 6513 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 6514 return Compatible; 6515} 6516 6517Sema::AssignConvertType 6518Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, 6519 bool Diagnose, 6520 bool DiagnoseCFAudited) { 6521 if (getLangOpts().CPlusPlus) { 6522 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 6523 // C++ 5.17p3: If the left operand is not of class type, the 6524 // expression is implicitly converted (C++ 4) to the 6525 // cv-unqualified type of the left operand. 6526 ExprResult Res; 6527 if (Diagnose) { 6528 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6529 AA_Assigning); 6530 } else { 6531 ImplicitConversionSequence ICS = 6532 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6533 /*SuppressUserConversions=*/false, 6534 /*AllowExplicit=*/false, 6535 /*InOverloadResolution=*/false, 6536 /*CStyle=*/false, 6537 /*AllowObjCWritebackConversion=*/false); 6538 if (ICS.isFailure()) 6539 return Incompatible; 6540 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6541 ICS, AA_Assigning); 6542 } 6543 if (Res.isInvalid()) 6544 return Incompatible; 6545 Sema::AssignConvertType result = Compatible; 6546 if (getLangOpts().ObjCAutoRefCount && 6547 !CheckObjCARCUnavailableWeakConversion(LHSType, 6548 RHS.get()->getType())) 6549 result = IncompatibleObjCWeakRef; 6550 RHS = Res; 6551 return result; 6552 } 6553 6554 // FIXME: Currently, we fall through and treat C++ classes like C 6555 // structures. 6556 // FIXME: We also fall through for atomics; not sure what should 6557 // happen there, though. 6558 } 6559 6560 // C99 6.5.16.1p1: the left operand is a pointer and the right is 6561 // a null pointer constant. 6562 if ((LHSType->isPointerType() || 6563 LHSType->isObjCObjectPointerType() || 6564 LHSType->isBlockPointerType()) 6565 && RHS.get()->isNullPointerConstant(Context, 6566 Expr::NPC_ValueDependentIsNull)) { 6567 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer); 6568 return Compatible; 6569 } 6570 6571 // This check seems unnatural, however it is necessary to ensure the proper 6572 // conversion of functions/arrays. If the conversion were done for all 6573 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 6574 // expressions that suppress this implicit conversion (&, sizeof). 6575 // 6576 // Suppress this for references: C++ 8.5.3p5. 6577 if (!LHSType->isReferenceType()) { 6578 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 6579 if (RHS.isInvalid()) 6580 return Incompatible; 6581 } 6582 6583 CastKind Kind = CK_Invalid; 6584 Sema::AssignConvertType result = 6585 CheckAssignmentConstraints(LHSType, RHS, Kind); 6586 6587 // C99 6.5.16.1p2: The value of the right operand is converted to the 6588 // type of the assignment expression. 6589 // CheckAssignmentConstraints allows the left-hand side to be a reference, 6590 // so that we can use references in built-in functions even in C. 6591 // The getNonReferenceType() call makes sure that the resulting expression 6592 // does not have reference type. 6593 if (result != Incompatible && RHS.get()->getType() != LHSType) { 6594 QualType Ty = LHSType.getNonLValueExprType(Context); 6595 Expr *E = RHS.take(); 6596 if (getLangOpts().ObjCAutoRefCount) 6597 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 6598 DiagnoseCFAudited); 6599 RHS = ImpCastExprToType(E, Ty, Kind); 6600 } 6601 return result; 6602} 6603 6604QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 6605 ExprResult &RHS) { 6606 Diag(Loc, diag::err_typecheck_invalid_operands) 6607 << LHS.get()->getType() << RHS.get()->getType() 6608 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6609 return QualType(); 6610} 6611 6612QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 6613 SourceLocation Loc, bool IsCompAssign) { 6614 if (!IsCompAssign) { 6615 LHS = DefaultFunctionArrayLvalueConversion(LHS.take()); 6616 if (LHS.isInvalid()) 6617 return QualType(); 6618 } 6619 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 6620 if (RHS.isInvalid()) 6621 return QualType(); 6622 6623 // For conversion purposes, we ignore any qualifiers. 6624 // For example, "const float" and "float" are equivalent. 6625 QualType LHSType = 6626 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6627 QualType RHSType = 6628 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6629 6630 // If the vector types are identical, return. 6631 if (LHSType == RHSType) 6632 return LHSType; 6633 6634 // Handle the case of equivalent AltiVec and GCC vector types 6635 if (LHSType->isVectorType() && RHSType->isVectorType() && 6636 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 6637 if (LHSType->isExtVectorType()) { 6638 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6639 return LHSType; 6640 } 6641 6642 if (!IsCompAssign) 6643 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 6644 return RHSType; 6645 } 6646 6647 if (getLangOpts().LaxVectorConversions && 6648 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) { 6649 // If we are allowing lax vector conversions, and LHS and RHS are both 6650 // vectors, the total size only needs to be the same. This is a 6651 // bitcast; no bits are changed but the result type is different. 6652 // FIXME: Should we really be allowing this? 6653 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6654 return LHSType; 6655 } 6656 6657 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can 6658 // swap back (so that we don't reverse the inputs to a subtract, for instance. 6659 bool swapped = false; 6660 if (RHSType->isExtVectorType() && !IsCompAssign) { 6661 swapped = true; 6662 std::swap(RHS, LHS); 6663 std::swap(RHSType, LHSType); 6664 } 6665 6666 // Handle the case of an ext vector and scalar. 6667 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) { 6668 QualType EltTy = LV->getElementType(); 6669 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) { 6670 int order = Context.getIntegerTypeOrder(EltTy, RHSType); 6671 if (order > 0) 6672 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast); 6673 if (order >= 0) { 6674 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat); 6675 if (swapped) std::swap(RHS, LHS); 6676 return LHSType; 6677 } 6678 } 6679 if (EltTy->isRealFloatingType() && RHSType->isScalarType()) { 6680 if (RHSType->isRealFloatingType()) { 6681 int order = Context.getFloatingTypeOrder(EltTy, RHSType); 6682 if (order > 0) 6683 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast); 6684 if (order >= 0) { 6685 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat); 6686 if (swapped) std::swap(RHS, LHS); 6687 return LHSType; 6688 } 6689 } 6690 if (RHSType->isIntegralType(Context)) { 6691 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralToFloating); 6692 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat); 6693 if (swapped) std::swap(RHS, LHS); 6694 return LHSType; 6695 } 6696 } 6697 } 6698 6699 // Vectors of different size or scalar and non-ext-vector are errors. 6700 if (swapped) std::swap(RHS, LHS); 6701 Diag(Loc, diag::err_typecheck_vector_not_convertable) 6702 << LHS.get()->getType() << RHS.get()->getType() 6703 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6704 return QualType(); 6705} 6706 6707// checkArithmeticNull - Detect when a NULL constant is used improperly in an 6708// expression. These are mainly cases where the null pointer is used as an 6709// integer instead of a pointer. 6710static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 6711 SourceLocation Loc, bool IsCompare) { 6712 // The canonical way to check for a GNU null is with isNullPointerConstant, 6713 // but we use a bit of a hack here for speed; this is a relatively 6714 // hot path, and isNullPointerConstant is slow. 6715 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 6716 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 6717 6718 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 6719 6720 // Avoid analyzing cases where the result will either be invalid (and 6721 // diagnosed as such) or entirely valid and not something to warn about. 6722 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 6723 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 6724 return; 6725 6726 // Comparison operations would not make sense with a null pointer no matter 6727 // what the other expression is. 6728 if (!IsCompare) { 6729 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 6730 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 6731 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 6732 return; 6733 } 6734 6735 // The rest of the operations only make sense with a null pointer 6736 // if the other expression is a pointer. 6737 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 6738 NonNullType->canDecayToPointerType()) 6739 return; 6740 6741 S.Diag(Loc, diag::warn_null_in_comparison_operation) 6742 << LHSNull /* LHS is NULL */ << NonNullType 6743 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6744} 6745 6746QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 6747 SourceLocation Loc, 6748 bool IsCompAssign, bool IsDiv) { 6749 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6750 6751 if (LHS.get()->getType()->isVectorType() || 6752 RHS.get()->getType()->isVectorType()) 6753 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6754 6755 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 6756 if (LHS.isInvalid() || RHS.isInvalid()) 6757 return QualType(); 6758 6759 6760 if (compType.isNull() || !compType->isArithmeticType()) 6761 return InvalidOperands(Loc, LHS, RHS); 6762 6763 // Check for division by zero. 6764 llvm::APSInt RHSValue; 6765 if (IsDiv && !RHS.get()->isValueDependent() && 6766 RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0) 6767 DiagRuntimeBehavior(Loc, RHS.get(), 6768 PDiag(diag::warn_division_by_zero) 6769 << RHS.get()->getSourceRange()); 6770 6771 return compType; 6772} 6773 6774QualType Sema::CheckRemainderOperands( 6775 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 6776 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6777 6778 if (LHS.get()->getType()->isVectorType() || 6779 RHS.get()->getType()->isVectorType()) { 6780 if (LHS.get()->getType()->hasIntegerRepresentation() && 6781 RHS.get()->getType()->hasIntegerRepresentation()) 6782 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6783 return InvalidOperands(Loc, LHS, RHS); 6784 } 6785 6786 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 6787 if (LHS.isInvalid() || RHS.isInvalid()) 6788 return QualType(); 6789 6790 if (compType.isNull() || !compType->isIntegerType()) 6791 return InvalidOperands(Loc, LHS, RHS); 6792 6793 // Check for remainder by zero. 6794 llvm::APSInt RHSValue; 6795 if (!RHS.get()->isValueDependent() && 6796 RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0) 6797 DiagRuntimeBehavior(Loc, RHS.get(), 6798 PDiag(diag::warn_remainder_by_zero) 6799 << RHS.get()->getSourceRange()); 6800 6801 return compType; 6802} 6803 6804/// \brief Diagnose invalid arithmetic on two void pointers. 6805static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 6806 Expr *LHSExpr, Expr *RHSExpr) { 6807 S.Diag(Loc, S.getLangOpts().CPlusPlus 6808 ? diag::err_typecheck_pointer_arith_void_type 6809 : diag::ext_gnu_void_ptr) 6810 << 1 /* two pointers */ << LHSExpr->getSourceRange() 6811 << RHSExpr->getSourceRange(); 6812} 6813 6814/// \brief Diagnose invalid arithmetic on a void pointer. 6815static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 6816 Expr *Pointer) { 6817 S.Diag(Loc, S.getLangOpts().CPlusPlus 6818 ? diag::err_typecheck_pointer_arith_void_type 6819 : diag::ext_gnu_void_ptr) 6820 << 0 /* one pointer */ << Pointer->getSourceRange(); 6821} 6822 6823/// \brief Diagnose invalid arithmetic on two function pointers. 6824static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 6825 Expr *LHS, Expr *RHS) { 6826 assert(LHS->getType()->isAnyPointerType()); 6827 assert(RHS->getType()->isAnyPointerType()); 6828 S.Diag(Loc, S.getLangOpts().CPlusPlus 6829 ? diag::err_typecheck_pointer_arith_function_type 6830 : diag::ext_gnu_ptr_func_arith) 6831 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 6832 // We only show the second type if it differs from the first. 6833 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 6834 RHS->getType()) 6835 << RHS->getType()->getPointeeType() 6836 << LHS->getSourceRange() << RHS->getSourceRange(); 6837} 6838 6839/// \brief Diagnose invalid arithmetic on a function pointer. 6840static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 6841 Expr *Pointer) { 6842 assert(Pointer->getType()->isAnyPointerType()); 6843 S.Diag(Loc, S.getLangOpts().CPlusPlus 6844 ? diag::err_typecheck_pointer_arith_function_type 6845 : diag::ext_gnu_ptr_func_arith) 6846 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 6847 << 0 /* one pointer, so only one type */ 6848 << Pointer->getSourceRange(); 6849} 6850 6851/// \brief Emit error if Operand is incomplete pointer type 6852/// 6853/// \returns True if pointer has incomplete type 6854static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 6855 Expr *Operand) { 6856 assert(Operand->getType()->isAnyPointerType() && 6857 !Operand->getType()->isDependentType()); 6858 QualType PointeeTy = Operand->getType()->getPointeeType(); 6859 return S.RequireCompleteType(Loc, PointeeTy, 6860 diag::err_typecheck_arithmetic_incomplete_type, 6861 PointeeTy, Operand->getSourceRange()); 6862} 6863 6864/// \brief Check the validity of an arithmetic pointer operand. 6865/// 6866/// If the operand has pointer type, this code will check for pointer types 6867/// which are invalid in arithmetic operations. These will be diagnosed 6868/// appropriately, including whether or not the use is supported as an 6869/// extension. 6870/// 6871/// \returns True when the operand is valid to use (even if as an extension). 6872static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 6873 Expr *Operand) { 6874 if (!Operand->getType()->isAnyPointerType()) return true; 6875 6876 QualType PointeeTy = Operand->getType()->getPointeeType(); 6877 if (PointeeTy->isVoidType()) { 6878 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 6879 return !S.getLangOpts().CPlusPlus; 6880 } 6881 if (PointeeTy->isFunctionType()) { 6882 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 6883 return !S.getLangOpts().CPlusPlus; 6884 } 6885 6886 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 6887 6888 return true; 6889} 6890 6891/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 6892/// operands. 6893/// 6894/// This routine will diagnose any invalid arithmetic on pointer operands much 6895/// like \see checkArithmeticOpPointerOperand. However, it has special logic 6896/// for emitting a single diagnostic even for operations where both LHS and RHS 6897/// are (potentially problematic) pointers. 6898/// 6899/// \returns True when the operand is valid to use (even if as an extension). 6900static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 6901 Expr *LHSExpr, Expr *RHSExpr) { 6902 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 6903 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 6904 if (!isLHSPointer && !isRHSPointer) return true; 6905 6906 QualType LHSPointeeTy, RHSPointeeTy; 6907 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 6908 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 6909 6910 // Check for arithmetic on pointers to incomplete types. 6911 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 6912 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 6913 if (isLHSVoidPtr || isRHSVoidPtr) { 6914 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 6915 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 6916 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 6917 6918 return !S.getLangOpts().CPlusPlus; 6919 } 6920 6921 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 6922 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 6923 if (isLHSFuncPtr || isRHSFuncPtr) { 6924 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 6925 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 6926 RHSExpr); 6927 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 6928 6929 return !S.getLangOpts().CPlusPlus; 6930 } 6931 6932 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 6933 return false; 6934 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 6935 return false; 6936 6937 return true; 6938} 6939 6940/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 6941/// literal. 6942static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 6943 Expr *LHSExpr, Expr *RHSExpr) { 6944 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 6945 Expr* IndexExpr = RHSExpr; 6946 if (!StrExpr) { 6947 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 6948 IndexExpr = LHSExpr; 6949 } 6950 6951 bool IsStringPlusInt = StrExpr && 6952 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 6953 if (!IsStringPlusInt) 6954 return; 6955 6956 llvm::APSInt index; 6957 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 6958 unsigned StrLenWithNull = StrExpr->getLength() + 1; 6959 if (index.isNonNegative() && 6960 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 6961 index.isUnsigned())) 6962 return; 6963 } 6964 6965 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 6966 Self.Diag(OpLoc, diag::warn_string_plus_int) 6967 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 6968 6969 // Only print a fixit for "str" + int, not for int + "str". 6970 if (IndexExpr == RHSExpr) { 6971 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 6972 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 6973 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 6974 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 6975 << FixItHint::CreateInsertion(EndLoc, "]"); 6976 } else 6977 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 6978} 6979 6980/// \brief Emit a warning when adding a char literal to a string. 6981static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 6982 Expr *LHSExpr, Expr *RHSExpr) { 6983 const DeclRefExpr *StringRefExpr = 6984 dyn_cast<DeclRefExpr>(LHSExpr->IgnoreImpCasts()); 6985 const CharacterLiteral *CharExpr = 6986 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 6987 if (!StringRefExpr) { 6988 StringRefExpr = dyn_cast<DeclRefExpr>(RHSExpr->IgnoreImpCasts()); 6989 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 6990 } 6991 6992 if (!CharExpr || !StringRefExpr) 6993 return; 6994 6995 const QualType StringType = StringRefExpr->getType(); 6996 6997 // Return if not a PointerType. 6998 if (!StringType->isAnyPointerType()) 6999 return; 7000 7001 // Return if not a CharacterType. 7002 if (!StringType->getPointeeType()->isAnyCharacterType()) 7003 return; 7004 7005 ASTContext &Ctx = Self.getASTContext(); 7006 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 7007 7008 const QualType CharType = CharExpr->getType(); 7009 if (!CharType->isAnyCharacterType() && 7010 CharType->isIntegerType() && 7011 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 7012 Self.Diag(OpLoc, diag::warn_string_plus_char) 7013 << DiagRange << Ctx.CharTy; 7014 } else { 7015 Self.Diag(OpLoc, diag::warn_string_plus_char) 7016 << DiagRange << CharExpr->getType(); 7017 } 7018 7019 // Only print a fixit for str + char, not for char + str. 7020 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 7021 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 7022 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 7023 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 7024 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 7025 << FixItHint::CreateInsertion(EndLoc, "]"); 7026 } else { 7027 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 7028 } 7029} 7030 7031/// \brief Emit error when two pointers are incompatible. 7032static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 7033 Expr *LHSExpr, Expr *RHSExpr) { 7034 assert(LHSExpr->getType()->isAnyPointerType()); 7035 assert(RHSExpr->getType()->isAnyPointerType()); 7036 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 7037 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 7038 << RHSExpr->getSourceRange(); 7039} 7040 7041QualType Sema::CheckAdditionOperands( // C99 6.5.6 7042 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 7043 QualType* CompLHSTy) { 7044 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7045 7046 if (LHS.get()->getType()->isVectorType() || 7047 RHS.get()->getType()->isVectorType()) { 7048 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 7049 if (CompLHSTy) *CompLHSTy = compType; 7050 return compType; 7051 } 7052 7053 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 7054 if (LHS.isInvalid() || RHS.isInvalid()) 7055 return QualType(); 7056 7057 // Diagnose "string literal" '+' int and string '+' "char literal". 7058 if (Opc == BO_Add) { 7059 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 7060 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 7061 } 7062 7063 // handle the common case first (both operands are arithmetic). 7064 if (!compType.isNull() && compType->isArithmeticType()) { 7065 if (CompLHSTy) *CompLHSTy = compType; 7066 return compType; 7067 } 7068 7069 // Type-checking. Ultimately the pointer's going to be in PExp; 7070 // note that we bias towards the LHS being the pointer. 7071 Expr *PExp = LHS.get(), *IExp = RHS.get(); 7072 7073 bool isObjCPointer; 7074 if (PExp->getType()->isPointerType()) { 7075 isObjCPointer = false; 7076 } else if (PExp->getType()->isObjCObjectPointerType()) { 7077 isObjCPointer = true; 7078 } else { 7079 std::swap(PExp, IExp); 7080 if (PExp->getType()->isPointerType()) { 7081 isObjCPointer = false; 7082 } else if (PExp->getType()->isObjCObjectPointerType()) { 7083 isObjCPointer = true; 7084 } else { 7085 return InvalidOperands(Loc, LHS, RHS); 7086 } 7087 } 7088 assert(PExp->getType()->isAnyPointerType()); 7089 7090 if (!IExp->getType()->isIntegerType()) 7091 return InvalidOperands(Loc, LHS, RHS); 7092 7093 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 7094 return QualType(); 7095 7096 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 7097 return QualType(); 7098 7099 // Check array bounds for pointer arithemtic 7100 CheckArrayAccess(PExp, IExp); 7101 7102 if (CompLHSTy) { 7103 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 7104 if (LHSTy.isNull()) { 7105 LHSTy = LHS.get()->getType(); 7106 if (LHSTy->isPromotableIntegerType()) 7107 LHSTy = Context.getPromotedIntegerType(LHSTy); 7108 } 7109 *CompLHSTy = LHSTy; 7110 } 7111 7112 return PExp->getType(); 7113} 7114 7115// C99 6.5.6 7116QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 7117 SourceLocation Loc, 7118 QualType* CompLHSTy) { 7119 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7120 7121 if (LHS.get()->getType()->isVectorType() || 7122 RHS.get()->getType()->isVectorType()) { 7123 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 7124 if (CompLHSTy) *CompLHSTy = compType; 7125 return compType; 7126 } 7127 7128 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 7129 if (LHS.isInvalid() || RHS.isInvalid()) 7130 return QualType(); 7131 7132 // Enforce type constraints: C99 6.5.6p3. 7133 7134 // Handle the common case first (both operands are arithmetic). 7135 if (!compType.isNull() && compType->isArithmeticType()) { 7136 if (CompLHSTy) *CompLHSTy = compType; 7137 return compType; 7138 } 7139 7140 // Either ptr - int or ptr - ptr. 7141 if (LHS.get()->getType()->isAnyPointerType()) { 7142 QualType lpointee = LHS.get()->getType()->getPointeeType(); 7143 7144 // Diagnose bad cases where we step over interface counts. 7145 if (LHS.get()->getType()->isObjCObjectPointerType() && 7146 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 7147 return QualType(); 7148 7149 // The result type of a pointer-int computation is the pointer type. 7150 if (RHS.get()->getType()->isIntegerType()) { 7151 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 7152 return QualType(); 7153 7154 // Check array bounds for pointer arithemtic 7155 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0, 7156 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 7157 7158 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 7159 return LHS.get()->getType(); 7160 } 7161 7162 // Handle pointer-pointer subtractions. 7163 if (const PointerType *RHSPTy 7164 = RHS.get()->getType()->getAs<PointerType>()) { 7165 QualType rpointee = RHSPTy->getPointeeType(); 7166 7167 if (getLangOpts().CPlusPlus) { 7168 // Pointee types must be the same: C++ [expr.add] 7169 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 7170 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 7171 } 7172 } else { 7173 // Pointee types must be compatible C99 6.5.6p3 7174 if (!Context.typesAreCompatible( 7175 Context.getCanonicalType(lpointee).getUnqualifiedType(), 7176 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 7177 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 7178 return QualType(); 7179 } 7180 } 7181 7182 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 7183 LHS.get(), RHS.get())) 7184 return QualType(); 7185 7186 // The pointee type may have zero size. As an extension, a structure or 7187 // union may have zero size or an array may have zero length. In this 7188 // case subtraction does not make sense. 7189 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 7190 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 7191 if (ElementSize.isZero()) { 7192 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 7193 << rpointee.getUnqualifiedType() 7194 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7195 } 7196 } 7197 7198 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 7199 return Context.getPointerDiffType(); 7200 } 7201 } 7202 7203 return InvalidOperands(Loc, LHS, RHS); 7204} 7205 7206static bool isScopedEnumerationType(QualType T) { 7207 if (const EnumType *ET = dyn_cast<EnumType>(T)) 7208 return ET->getDecl()->isScoped(); 7209 return false; 7210} 7211 7212static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 7213 SourceLocation Loc, unsigned Opc, 7214 QualType LHSType) { 7215 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 7216 // so skip remaining warnings as we don't want to modify values within Sema. 7217 if (S.getLangOpts().OpenCL) 7218 return; 7219 7220 llvm::APSInt Right; 7221 // Check right/shifter operand 7222 if (RHS.get()->isValueDependent() || 7223 !RHS.get()->isIntegerConstantExpr(Right, S.Context)) 7224 return; 7225 7226 if (Right.isNegative()) { 7227 S.DiagRuntimeBehavior(Loc, RHS.get(), 7228 S.PDiag(diag::warn_shift_negative) 7229 << RHS.get()->getSourceRange()); 7230 return; 7231 } 7232 llvm::APInt LeftBits(Right.getBitWidth(), 7233 S.Context.getTypeSize(LHS.get()->getType())); 7234 if (Right.uge(LeftBits)) { 7235 S.DiagRuntimeBehavior(Loc, RHS.get(), 7236 S.PDiag(diag::warn_shift_gt_typewidth) 7237 << RHS.get()->getSourceRange()); 7238 return; 7239 } 7240 if (Opc != BO_Shl) 7241 return; 7242 7243 // When left shifting an ICE which is signed, we can check for overflow which 7244 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 7245 // integers have defined behavior modulo one more than the maximum value 7246 // representable in the result type, so never warn for those. 7247 llvm::APSInt Left; 7248 if (LHS.get()->isValueDependent() || 7249 !LHS.get()->isIntegerConstantExpr(Left, S.Context) || 7250 LHSType->hasUnsignedIntegerRepresentation()) 7251 return; 7252 llvm::APInt ResultBits = 7253 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 7254 if (LeftBits.uge(ResultBits)) 7255 return; 7256 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 7257 Result = Result.shl(Right); 7258 7259 // Print the bit representation of the signed integer as an unsigned 7260 // hexadecimal number. 7261 SmallString<40> HexResult; 7262 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 7263 7264 // If we are only missing a sign bit, this is less likely to result in actual 7265 // bugs -- if the result is cast back to an unsigned type, it will have the 7266 // expected value. Thus we place this behind a different warning that can be 7267 // turned off separately if needed. 7268 if (LeftBits == ResultBits - 1) { 7269 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 7270 << HexResult.str() << LHSType 7271 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7272 return; 7273 } 7274 7275 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 7276 << HexResult.str() << Result.getMinSignedBits() << LHSType 7277 << Left.getBitWidth() << LHS.get()->getSourceRange() 7278 << RHS.get()->getSourceRange(); 7279} 7280 7281// C99 6.5.7 7282QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 7283 SourceLocation Loc, unsigned Opc, 7284 bool IsCompAssign) { 7285 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7286 7287 // Vector shifts promote their scalar inputs to vector type. 7288 if (LHS.get()->getType()->isVectorType() || 7289 RHS.get()->getType()->isVectorType()) 7290 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 7291 7292 // Shifts don't perform usual arithmetic conversions, they just do integer 7293 // promotions on each operand. C99 6.5.7p3 7294 7295 // For the LHS, do usual unary conversions, but then reset them away 7296 // if this is a compound assignment. 7297 ExprResult OldLHS = LHS; 7298 LHS = UsualUnaryConversions(LHS.take()); 7299 if (LHS.isInvalid()) 7300 return QualType(); 7301 QualType LHSType = LHS.get()->getType(); 7302 if (IsCompAssign) LHS = OldLHS; 7303 7304 // The RHS is simpler. 7305 RHS = UsualUnaryConversions(RHS.take()); 7306 if (RHS.isInvalid()) 7307 return QualType(); 7308 QualType RHSType = RHS.get()->getType(); 7309 7310 // C99 6.5.7p2: Each of the operands shall have integer type. 7311 if (!LHSType->hasIntegerRepresentation() || 7312 !RHSType->hasIntegerRepresentation()) 7313 return InvalidOperands(Loc, LHS, RHS); 7314 7315 // C++0x: Don't allow scoped enums. FIXME: Use something better than 7316 // hasIntegerRepresentation() above instead of this. 7317 if (isScopedEnumerationType(LHSType) || 7318 isScopedEnumerationType(RHSType)) { 7319 return InvalidOperands(Loc, LHS, RHS); 7320 } 7321 // Sanity-check shift operands 7322 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 7323 7324 // "The type of the result is that of the promoted left operand." 7325 return LHSType; 7326} 7327 7328static bool IsWithinTemplateSpecialization(Decl *D) { 7329 if (DeclContext *DC = D->getDeclContext()) { 7330 if (isa<ClassTemplateSpecializationDecl>(DC)) 7331 return true; 7332 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 7333 return FD->isFunctionTemplateSpecialization(); 7334 } 7335 return false; 7336} 7337 7338/// If two different enums are compared, raise a warning. 7339static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 7340 Expr *RHS) { 7341 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 7342 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 7343 7344 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 7345 if (!LHSEnumType) 7346 return; 7347 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 7348 if (!RHSEnumType) 7349 return; 7350 7351 // Ignore anonymous enums. 7352 if (!LHSEnumType->getDecl()->getIdentifier()) 7353 return; 7354 if (!RHSEnumType->getDecl()->getIdentifier()) 7355 return; 7356 7357 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 7358 return; 7359 7360 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 7361 << LHSStrippedType << RHSStrippedType 7362 << LHS->getSourceRange() << RHS->getSourceRange(); 7363} 7364 7365/// \brief Diagnose bad pointer comparisons. 7366static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 7367 ExprResult &LHS, ExprResult &RHS, 7368 bool IsError) { 7369 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 7370 : diag::ext_typecheck_comparison_of_distinct_pointers) 7371 << LHS.get()->getType() << RHS.get()->getType() 7372 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7373} 7374 7375/// \brief Returns false if the pointers are converted to a composite type, 7376/// true otherwise. 7377static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 7378 ExprResult &LHS, ExprResult &RHS) { 7379 // C++ [expr.rel]p2: 7380 // [...] Pointer conversions (4.10) and qualification 7381 // conversions (4.4) are performed on pointer operands (or on 7382 // a pointer operand and a null pointer constant) to bring 7383 // them to their composite pointer type. [...] 7384 // 7385 // C++ [expr.eq]p1 uses the same notion for (in)equality 7386 // comparisons of pointers. 7387 7388 // C++ [expr.eq]p2: 7389 // In addition, pointers to members can be compared, or a pointer to 7390 // member and a null pointer constant. Pointer to member conversions 7391 // (4.11) and qualification conversions (4.4) are performed to bring 7392 // them to a common type. If one operand is a null pointer constant, 7393 // the common type is the type of the other operand. Otherwise, the 7394 // common type is a pointer to member type similar (4.4) to the type 7395 // of one of the operands, with a cv-qualification signature (4.4) 7396 // that is the union of the cv-qualification signatures of the operand 7397 // types. 7398 7399 QualType LHSType = LHS.get()->getType(); 7400 QualType RHSType = RHS.get()->getType(); 7401 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 7402 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 7403 7404 bool NonStandardCompositeType = false; 7405 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType; 7406 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 7407 if (T.isNull()) { 7408 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 7409 return true; 7410 } 7411 7412 if (NonStandardCompositeType) 7413 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 7414 << LHSType << RHSType << T << LHS.get()->getSourceRange() 7415 << RHS.get()->getSourceRange(); 7416 7417 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast); 7418 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast); 7419 return false; 7420} 7421 7422static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 7423 ExprResult &LHS, 7424 ExprResult &RHS, 7425 bool IsError) { 7426 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 7427 : diag::ext_typecheck_comparison_of_fptr_to_void) 7428 << LHS.get()->getType() << RHS.get()->getType() 7429 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7430} 7431 7432static bool isObjCObjectLiteral(ExprResult &E) { 7433 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 7434 case Stmt::ObjCArrayLiteralClass: 7435 case Stmt::ObjCDictionaryLiteralClass: 7436 case Stmt::ObjCStringLiteralClass: 7437 case Stmt::ObjCBoxedExprClass: 7438 return true; 7439 default: 7440 // Note that ObjCBoolLiteral is NOT an object literal! 7441 return false; 7442 } 7443} 7444 7445static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 7446 const ObjCObjectPointerType *Type = 7447 LHS->getType()->getAs<ObjCObjectPointerType>(); 7448 7449 // If this is not actually an Objective-C object, bail out. 7450 if (!Type) 7451 return false; 7452 7453 // Get the LHS object's interface type. 7454 QualType InterfaceType = Type->getPointeeType(); 7455 if (const ObjCObjectType *iQFaceTy = 7456 InterfaceType->getAsObjCQualifiedInterfaceType()) 7457 InterfaceType = iQFaceTy->getBaseType(); 7458 7459 // If the RHS isn't an Objective-C object, bail out. 7460 if (!RHS->getType()->isObjCObjectPointerType()) 7461 return false; 7462 7463 // Try to find the -isEqual: method. 7464 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 7465 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 7466 InterfaceType, 7467 /*instance=*/true); 7468 if (!Method) { 7469 if (Type->isObjCIdType()) { 7470 // For 'id', just check the global pool. 7471 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 7472 /*receiverId=*/true, 7473 /*warn=*/false); 7474 } else { 7475 // Check protocols. 7476 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 7477 /*instance=*/true); 7478 } 7479 } 7480 7481 if (!Method) 7482 return false; 7483 7484 QualType T = Method->param_begin()[0]->getType(); 7485 if (!T->isObjCObjectPointerType()) 7486 return false; 7487 7488 QualType R = Method->getResultType(); 7489 if (!R->isScalarType()) 7490 return false; 7491 7492 return true; 7493} 7494 7495Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 7496 FromE = FromE->IgnoreParenImpCasts(); 7497 switch (FromE->getStmtClass()) { 7498 default: 7499 break; 7500 case Stmt::ObjCStringLiteralClass: 7501 // "string literal" 7502 return LK_String; 7503 case Stmt::ObjCArrayLiteralClass: 7504 // "array literal" 7505 return LK_Array; 7506 case Stmt::ObjCDictionaryLiteralClass: 7507 // "dictionary literal" 7508 return LK_Dictionary; 7509 case Stmt::BlockExprClass: 7510 return LK_Block; 7511 case Stmt::ObjCBoxedExprClass: { 7512 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 7513 switch (Inner->getStmtClass()) { 7514 case Stmt::IntegerLiteralClass: 7515 case Stmt::FloatingLiteralClass: 7516 case Stmt::CharacterLiteralClass: 7517 case Stmt::ObjCBoolLiteralExprClass: 7518 case Stmt::CXXBoolLiteralExprClass: 7519 // "numeric literal" 7520 return LK_Numeric; 7521 case Stmt::ImplicitCastExprClass: { 7522 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 7523 // Boolean literals can be represented by implicit casts. 7524 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 7525 return LK_Numeric; 7526 break; 7527 } 7528 default: 7529 break; 7530 } 7531 return LK_Boxed; 7532 } 7533 } 7534 return LK_None; 7535} 7536 7537static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 7538 ExprResult &LHS, ExprResult &RHS, 7539 BinaryOperator::Opcode Opc){ 7540 Expr *Literal; 7541 Expr *Other; 7542 if (isObjCObjectLiteral(LHS)) { 7543 Literal = LHS.get(); 7544 Other = RHS.get(); 7545 } else { 7546 Literal = RHS.get(); 7547 Other = LHS.get(); 7548 } 7549 7550 // Don't warn on comparisons against nil. 7551 Other = Other->IgnoreParenCasts(); 7552 if (Other->isNullPointerConstant(S.getASTContext(), 7553 Expr::NPC_ValueDependentIsNotNull)) 7554 return; 7555 7556 // This should be kept in sync with warn_objc_literal_comparison. 7557 // LK_String should always be after the other literals, since it has its own 7558 // warning flag. 7559 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 7560 assert(LiteralKind != Sema::LK_Block); 7561 if (LiteralKind == Sema::LK_None) { 7562 llvm_unreachable("Unknown Objective-C object literal kind"); 7563 } 7564 7565 if (LiteralKind == Sema::LK_String) 7566 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 7567 << Literal->getSourceRange(); 7568 else 7569 S.Diag(Loc, diag::warn_objc_literal_comparison) 7570 << LiteralKind << Literal->getSourceRange(); 7571 7572 if (BinaryOperator::isEqualityOp(Opc) && 7573 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 7574 SourceLocation Start = LHS.get()->getLocStart(); 7575 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 7576 CharSourceRange OpRange = 7577 CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc)); 7578 7579 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 7580 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 7581 << FixItHint::CreateReplacement(OpRange, " isEqual:") 7582 << FixItHint::CreateInsertion(End, "]"); 7583 } 7584} 7585 7586static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS, 7587 ExprResult &RHS, 7588 SourceLocation Loc, 7589 unsigned OpaqueOpc) { 7590 // This checking requires bools. 7591 if (!S.getLangOpts().Bool) return; 7592 7593 // Check that left hand side is !something. 7594 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 7595 if (!UO || UO->getOpcode() != UO_LNot) return; 7596 7597 // Only check if the right hand side is non-bool arithmetic type. 7598 if (RHS.get()->getType()->isBooleanType()) return; 7599 7600 // Make sure that the something in !something is not bool. 7601 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 7602 if (SubExpr->getType()->isBooleanType()) return; 7603 7604 // Emit warning. 7605 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison) 7606 << Loc; 7607 7608 // First note suggest !(x < y) 7609 SourceLocation FirstOpen = SubExpr->getLocStart(); 7610 SourceLocation FirstClose = RHS.get()->getLocEnd(); 7611 FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose); 7612 if (FirstClose.isInvalid()) 7613 FirstOpen = SourceLocation(); 7614 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 7615 << FixItHint::CreateInsertion(FirstOpen, "(") 7616 << FixItHint::CreateInsertion(FirstClose, ")"); 7617 7618 // Second note suggests (!x) < y 7619 SourceLocation SecondOpen = LHS.get()->getLocStart(); 7620 SourceLocation SecondClose = LHS.get()->getLocEnd(); 7621 SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose); 7622 if (SecondClose.isInvalid()) 7623 SecondOpen = SourceLocation(); 7624 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 7625 << FixItHint::CreateInsertion(SecondOpen, "(") 7626 << FixItHint::CreateInsertion(SecondClose, ")"); 7627} 7628 7629// Get the decl for a simple expression: a reference to a variable, 7630// an implicit C++ field reference, or an implicit ObjC ivar reference. 7631static ValueDecl *getCompareDecl(Expr *E) { 7632 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 7633 return DR->getDecl(); 7634 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 7635 if (Ivar->isFreeIvar()) 7636 return Ivar->getDecl(); 7637 } 7638 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 7639 if (Mem->isImplicitAccess()) 7640 return Mem->getMemberDecl(); 7641 } 7642 return 0; 7643} 7644 7645// C99 6.5.8, C++ [expr.rel] 7646QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 7647 SourceLocation Loc, unsigned OpaqueOpc, 7648 bool IsRelational) { 7649 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 7650 7651 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc; 7652 7653 // Handle vector comparisons separately. 7654 if (LHS.get()->getType()->isVectorType() || 7655 RHS.get()->getType()->isVectorType()) 7656 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 7657 7658 QualType LHSType = LHS.get()->getType(); 7659 QualType RHSType = RHS.get()->getType(); 7660 7661 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 7662 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 7663 7664 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 7665 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc); 7666 7667 if (!LHSType->hasFloatingRepresentation() && 7668 !(LHSType->isBlockPointerType() && IsRelational) && 7669 !LHS.get()->getLocStart().isMacroID() && 7670 !RHS.get()->getLocStart().isMacroID()) { 7671 // For non-floating point types, check for self-comparisons of the form 7672 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 7673 // often indicate logic errors in the program. 7674 // 7675 // NOTE: Don't warn about comparison expressions resulting from macro 7676 // expansion. Also don't warn about comparisons which are only self 7677 // comparisons within a template specialization. The warnings should catch 7678 // obvious cases in the definition of the template anyways. The idea is to 7679 // warn when the typed comparison operator will always evaluate to the same 7680 // result. 7681 ValueDecl *DL = getCompareDecl(LHSStripped); 7682 ValueDecl *DR = getCompareDecl(RHSStripped); 7683 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 7684 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 7685 << 0 // self- 7686 << (Opc == BO_EQ 7687 || Opc == BO_LE 7688 || Opc == BO_GE)); 7689 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 7690 !DL->getType()->isReferenceType() && 7691 !DR->getType()->isReferenceType()) { 7692 // what is it always going to eval to? 7693 char always_evals_to; 7694 switch(Opc) { 7695 case BO_EQ: // e.g. array1 == array2 7696 always_evals_to = 0; // false 7697 break; 7698 case BO_NE: // e.g. array1 != array2 7699 always_evals_to = 1; // true 7700 break; 7701 default: 7702 // best we can say is 'a constant' 7703 always_evals_to = 2; // e.g. array1 <= array2 7704 break; 7705 } 7706 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 7707 << 1 // array 7708 << always_evals_to); 7709 } 7710 7711 if (isa<CastExpr>(LHSStripped)) 7712 LHSStripped = LHSStripped->IgnoreParenCasts(); 7713 if (isa<CastExpr>(RHSStripped)) 7714 RHSStripped = RHSStripped->IgnoreParenCasts(); 7715 7716 // Warn about comparisons against a string constant (unless the other 7717 // operand is null), the user probably wants strcmp. 7718 Expr *literalString = 0; 7719 Expr *literalStringStripped = 0; 7720 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 7721 !RHSStripped->isNullPointerConstant(Context, 7722 Expr::NPC_ValueDependentIsNull)) { 7723 literalString = LHS.get(); 7724 literalStringStripped = LHSStripped; 7725 } else if ((isa<StringLiteral>(RHSStripped) || 7726 isa<ObjCEncodeExpr>(RHSStripped)) && 7727 !LHSStripped->isNullPointerConstant(Context, 7728 Expr::NPC_ValueDependentIsNull)) { 7729 literalString = RHS.get(); 7730 literalStringStripped = RHSStripped; 7731 } 7732 7733 if (literalString) { 7734 DiagRuntimeBehavior(Loc, 0, 7735 PDiag(diag::warn_stringcompare) 7736 << isa<ObjCEncodeExpr>(literalStringStripped) 7737 << literalString->getSourceRange()); 7738 } 7739 } 7740 7741 // C99 6.5.8p3 / C99 6.5.9p4 7742 UsualArithmeticConversions(LHS, RHS); 7743 if (LHS.isInvalid() || RHS.isInvalid()) 7744 return QualType(); 7745 7746 LHSType = LHS.get()->getType(); 7747 RHSType = RHS.get()->getType(); 7748 7749 // The result of comparisons is 'bool' in C++, 'int' in C. 7750 QualType ResultTy = Context.getLogicalOperationType(); 7751 7752 if (IsRelational) { 7753 if (LHSType->isRealType() && RHSType->isRealType()) 7754 return ResultTy; 7755 } else { 7756 // Check for comparisons of floating point operands using != and ==. 7757 if (LHSType->hasFloatingRepresentation()) 7758 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 7759 7760 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 7761 return ResultTy; 7762 } 7763 7764 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context, 7765 Expr::NPC_ValueDependentIsNull); 7766 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context, 7767 Expr::NPC_ValueDependentIsNull); 7768 7769 // All of the following pointer-related warnings are GCC extensions, except 7770 // when handling null pointer constants. 7771 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 7772 QualType LCanPointeeTy = 7773 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 7774 QualType RCanPointeeTy = 7775 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 7776 7777 if (getLangOpts().CPlusPlus) { 7778 if (LCanPointeeTy == RCanPointeeTy) 7779 return ResultTy; 7780 if (!IsRelational && 7781 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 7782 // Valid unless comparison between non-null pointer and function pointer 7783 // This is a gcc extension compatibility comparison. 7784 // In a SFINAE context, we treat this as a hard error to maintain 7785 // conformance with the C++ standard. 7786 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 7787 && !LHSIsNull && !RHSIsNull) { 7788 diagnoseFunctionPointerToVoidComparison( 7789 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 7790 7791 if (isSFINAEContext()) 7792 return QualType(); 7793 7794 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7795 return ResultTy; 7796 } 7797 } 7798 7799 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 7800 return QualType(); 7801 else 7802 return ResultTy; 7803 } 7804 // C99 6.5.9p2 and C99 6.5.8p2 7805 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 7806 RCanPointeeTy.getUnqualifiedType())) { 7807 // Valid unless a relational comparison of function pointers 7808 if (IsRelational && LCanPointeeTy->isFunctionType()) { 7809 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 7810 << LHSType << RHSType << LHS.get()->getSourceRange() 7811 << RHS.get()->getSourceRange(); 7812 } 7813 } else if (!IsRelational && 7814 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 7815 // Valid unless comparison between non-null pointer and function pointer 7816 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 7817 && !LHSIsNull && !RHSIsNull) 7818 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 7819 /*isError*/false); 7820 } else { 7821 // Invalid 7822 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 7823 } 7824 if (LCanPointeeTy != RCanPointeeTy) { 7825 if (LHSIsNull && !RHSIsNull) 7826 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 7827 else 7828 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7829 } 7830 return ResultTy; 7831 } 7832 7833 if (getLangOpts().CPlusPlus) { 7834 // Comparison of nullptr_t with itself. 7835 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 7836 return ResultTy; 7837 7838 // Comparison of pointers with null pointer constants and equality 7839 // comparisons of member pointers to null pointer constants. 7840 if (RHSIsNull && 7841 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 7842 (!IsRelational && 7843 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 7844 RHS = ImpCastExprToType(RHS.take(), LHSType, 7845 LHSType->isMemberPointerType() 7846 ? CK_NullToMemberPointer 7847 : CK_NullToPointer); 7848 return ResultTy; 7849 } 7850 if (LHSIsNull && 7851 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 7852 (!IsRelational && 7853 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 7854 LHS = ImpCastExprToType(LHS.take(), RHSType, 7855 RHSType->isMemberPointerType() 7856 ? CK_NullToMemberPointer 7857 : CK_NullToPointer); 7858 return ResultTy; 7859 } 7860 7861 // Comparison of member pointers. 7862 if (!IsRelational && 7863 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 7864 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 7865 return QualType(); 7866 else 7867 return ResultTy; 7868 } 7869 7870 // Handle scoped enumeration types specifically, since they don't promote 7871 // to integers. 7872 if (LHS.get()->getType()->isEnumeralType() && 7873 Context.hasSameUnqualifiedType(LHS.get()->getType(), 7874 RHS.get()->getType())) 7875 return ResultTy; 7876 } 7877 7878 // Handle block pointer types. 7879 if (!IsRelational && LHSType->isBlockPointerType() && 7880 RHSType->isBlockPointerType()) { 7881 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 7882 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 7883 7884 if (!LHSIsNull && !RHSIsNull && 7885 !Context.typesAreCompatible(lpointee, rpointee)) { 7886 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 7887 << LHSType << RHSType << LHS.get()->getSourceRange() 7888 << RHS.get()->getSourceRange(); 7889 } 7890 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7891 return ResultTy; 7892 } 7893 7894 // Allow block pointers to be compared with null pointer constants. 7895 if (!IsRelational 7896 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 7897 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 7898 if (!LHSIsNull && !RHSIsNull) { 7899 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 7900 ->getPointeeType()->isVoidType()) 7901 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 7902 ->getPointeeType()->isVoidType()))) 7903 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 7904 << LHSType << RHSType << LHS.get()->getSourceRange() 7905 << RHS.get()->getSourceRange(); 7906 } 7907 if (LHSIsNull && !RHSIsNull) 7908 LHS = ImpCastExprToType(LHS.take(), RHSType, 7909 RHSType->isPointerType() ? CK_BitCast 7910 : CK_AnyPointerToBlockPointerCast); 7911 else 7912 RHS = ImpCastExprToType(RHS.take(), LHSType, 7913 LHSType->isPointerType() ? CK_BitCast 7914 : CK_AnyPointerToBlockPointerCast); 7915 return ResultTy; 7916 } 7917 7918 if (LHSType->isObjCObjectPointerType() || 7919 RHSType->isObjCObjectPointerType()) { 7920 const PointerType *LPT = LHSType->getAs<PointerType>(); 7921 const PointerType *RPT = RHSType->getAs<PointerType>(); 7922 if (LPT || RPT) { 7923 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 7924 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 7925 7926 if (!LPtrToVoid && !RPtrToVoid && 7927 !Context.typesAreCompatible(LHSType, RHSType)) { 7928 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 7929 /*isError*/false); 7930 } 7931 if (LHSIsNull && !RHSIsNull) { 7932 Expr *E = LHS.take(); 7933 if (getLangOpts().ObjCAutoRefCount) 7934 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion); 7935 LHS = ImpCastExprToType(E, RHSType, 7936 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 7937 } 7938 else { 7939 Expr *E = RHS.take(); 7940 if (getLangOpts().ObjCAutoRefCount) 7941 CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion); 7942 RHS = ImpCastExprToType(E, LHSType, 7943 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 7944 } 7945 return ResultTy; 7946 } 7947 if (LHSType->isObjCObjectPointerType() && 7948 RHSType->isObjCObjectPointerType()) { 7949 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 7950 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 7951 /*isError*/false); 7952 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 7953 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 7954 7955 if (LHSIsNull && !RHSIsNull) 7956 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 7957 else 7958 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7959 return ResultTy; 7960 } 7961 } 7962 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 7963 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 7964 unsigned DiagID = 0; 7965 bool isError = false; 7966 if (LangOpts.DebuggerSupport) { 7967 // Under a debugger, allow the comparison of pointers to integers, 7968 // since users tend to want to compare addresses. 7969 } else if ((LHSIsNull && LHSType->isIntegerType()) || 7970 (RHSIsNull && RHSType->isIntegerType())) { 7971 if (IsRelational && !getLangOpts().CPlusPlus) 7972 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 7973 } else if (IsRelational && !getLangOpts().CPlusPlus) 7974 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 7975 else if (getLangOpts().CPlusPlus) { 7976 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 7977 isError = true; 7978 } else 7979 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 7980 7981 if (DiagID) { 7982 Diag(Loc, DiagID) 7983 << LHSType << RHSType << LHS.get()->getSourceRange() 7984 << RHS.get()->getSourceRange(); 7985 if (isError) 7986 return QualType(); 7987 } 7988 7989 if (LHSType->isIntegerType()) 7990 LHS = ImpCastExprToType(LHS.take(), RHSType, 7991 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 7992 else 7993 RHS = ImpCastExprToType(RHS.take(), LHSType, 7994 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 7995 return ResultTy; 7996 } 7997 7998 // Handle block pointers. 7999 if (!IsRelational && RHSIsNull 8000 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 8001 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer); 8002 return ResultTy; 8003 } 8004 if (!IsRelational && LHSIsNull 8005 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 8006 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer); 8007 return ResultTy; 8008 } 8009 8010 return InvalidOperands(Loc, LHS, RHS); 8011} 8012 8013 8014// Return a signed type that is of identical size and number of elements. 8015// For floating point vectors, return an integer type of identical size 8016// and number of elements. 8017QualType Sema::GetSignedVectorType(QualType V) { 8018 const VectorType *VTy = V->getAs<VectorType>(); 8019 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 8020 if (TypeSize == Context.getTypeSize(Context.CharTy)) 8021 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 8022 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 8023 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 8024 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 8025 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 8026 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 8027 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 8028 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 8029 "Unhandled vector element size in vector compare"); 8030 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 8031} 8032 8033/// CheckVectorCompareOperands - vector comparisons are a clang extension that 8034/// operates on extended vector types. Instead of producing an IntTy result, 8035/// like a scalar comparison, a vector comparison produces a vector of integer 8036/// types. 8037QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 8038 SourceLocation Loc, 8039 bool IsRelational) { 8040 // Check to make sure we're operating on vectors of the same type and width, 8041 // Allowing one side to be a scalar of element type. 8042 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false); 8043 if (vType.isNull()) 8044 return vType; 8045 8046 QualType LHSType = LHS.get()->getType(); 8047 8048 // If AltiVec, the comparison results in a numeric type, i.e. 8049 // bool for C++, int for C 8050 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 8051 return Context.getLogicalOperationType(); 8052 8053 // For non-floating point types, check for self-comparisons of the form 8054 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 8055 // often indicate logic errors in the program. 8056 if (!LHSType->hasFloatingRepresentation()) { 8057 if (DeclRefExpr* DRL 8058 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 8059 if (DeclRefExpr* DRR 8060 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 8061 if (DRL->getDecl() == DRR->getDecl()) 8062 DiagRuntimeBehavior(Loc, 0, 8063 PDiag(diag::warn_comparison_always) 8064 << 0 // self- 8065 << 2 // "a constant" 8066 ); 8067 } 8068 8069 // Check for comparisons of floating point operands using != and ==. 8070 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 8071 assert (RHS.get()->getType()->hasFloatingRepresentation()); 8072 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 8073 } 8074 8075 // Return a signed type for the vector. 8076 return GetSignedVectorType(LHSType); 8077} 8078 8079QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 8080 SourceLocation Loc) { 8081 // Ensure that either both operands are of the same vector type, or 8082 // one operand is of a vector type and the other is of its element type. 8083 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false); 8084 if (vType.isNull()) 8085 return InvalidOperands(Loc, LHS, RHS); 8086 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 8087 vType->hasFloatingRepresentation()) 8088 return InvalidOperands(Loc, LHS, RHS); 8089 8090 return GetSignedVectorType(LHS.get()->getType()); 8091} 8092 8093inline QualType Sema::CheckBitwiseOperands( 8094 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8095 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8096 8097 if (LHS.get()->getType()->isVectorType() || 8098 RHS.get()->getType()->isVectorType()) { 8099 if (LHS.get()->getType()->hasIntegerRepresentation() && 8100 RHS.get()->getType()->hasIntegerRepresentation()) 8101 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 8102 8103 return InvalidOperands(Loc, LHS, RHS); 8104 } 8105 8106 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS); 8107 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 8108 IsCompAssign); 8109 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 8110 return QualType(); 8111 LHS = LHSResult.take(); 8112 RHS = RHSResult.take(); 8113 8114 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 8115 return compType; 8116 return InvalidOperands(Loc, LHS, RHS); 8117} 8118 8119inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 8120 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) { 8121 8122 // Check vector operands differently. 8123 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 8124 return CheckVectorLogicalOperands(LHS, RHS, Loc); 8125 8126 // Diagnose cases where the user write a logical and/or but probably meant a 8127 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 8128 // is a constant. 8129 if (LHS.get()->getType()->isIntegerType() && 8130 !LHS.get()->getType()->isBooleanType() && 8131 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 8132 // Don't warn in macros or template instantiations. 8133 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 8134 // If the RHS can be constant folded, and if it constant folds to something 8135 // that isn't 0 or 1 (which indicate a potential logical operation that 8136 // happened to fold to true/false) then warn. 8137 // Parens on the RHS are ignored. 8138 llvm::APSInt Result; 8139 if (RHS.get()->EvaluateAsInt(Result, Context)) 8140 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) || 8141 (Result != 0 && Result != 1)) { 8142 Diag(Loc, diag::warn_logical_instead_of_bitwise) 8143 << RHS.get()->getSourceRange() 8144 << (Opc == BO_LAnd ? "&&" : "||"); 8145 // Suggest replacing the logical operator with the bitwise version 8146 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 8147 << (Opc == BO_LAnd ? "&" : "|") 8148 << FixItHint::CreateReplacement(SourceRange( 8149 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(), 8150 getLangOpts())), 8151 Opc == BO_LAnd ? "&" : "|"); 8152 if (Opc == BO_LAnd) 8153 // Suggest replacing "Foo() && kNonZero" with "Foo()" 8154 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 8155 << FixItHint::CreateRemoval( 8156 SourceRange( 8157 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(), 8158 0, getSourceManager(), 8159 getLangOpts()), 8160 RHS.get()->getLocEnd())); 8161 } 8162 } 8163 8164 if (!Context.getLangOpts().CPlusPlus) { 8165 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 8166 // not operate on the built-in scalar and vector float types. 8167 if (Context.getLangOpts().OpenCL && 8168 Context.getLangOpts().OpenCLVersion < 120) { 8169 if (LHS.get()->getType()->isFloatingType() || 8170 RHS.get()->getType()->isFloatingType()) 8171 return InvalidOperands(Loc, LHS, RHS); 8172 } 8173 8174 LHS = UsualUnaryConversions(LHS.take()); 8175 if (LHS.isInvalid()) 8176 return QualType(); 8177 8178 RHS = UsualUnaryConversions(RHS.take()); 8179 if (RHS.isInvalid()) 8180 return QualType(); 8181 8182 if (!LHS.get()->getType()->isScalarType() || 8183 !RHS.get()->getType()->isScalarType()) 8184 return InvalidOperands(Loc, LHS, RHS); 8185 8186 return Context.IntTy; 8187 } 8188 8189 // The following is safe because we only use this method for 8190 // non-overloadable operands. 8191 8192 // C++ [expr.log.and]p1 8193 // C++ [expr.log.or]p1 8194 // The operands are both contextually converted to type bool. 8195 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 8196 if (LHSRes.isInvalid()) 8197 return InvalidOperands(Loc, LHS, RHS); 8198 LHS = LHSRes; 8199 8200 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 8201 if (RHSRes.isInvalid()) 8202 return InvalidOperands(Loc, LHS, RHS); 8203 RHS = RHSRes; 8204 8205 // C++ [expr.log.and]p2 8206 // C++ [expr.log.or]p2 8207 // The result is a bool. 8208 return Context.BoolTy; 8209} 8210 8211static bool IsReadonlyMessage(Expr *E, Sema &S) { 8212 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 8213 if (!ME) return false; 8214 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 8215 ObjCMessageExpr *Base = 8216 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 8217 if (!Base) return false; 8218 return Base->getMethodDecl() != 0; 8219} 8220 8221/// Is the given expression (which must be 'const') a reference to a 8222/// variable which was originally non-const, but which has become 8223/// 'const' due to being captured within a block? 8224enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 8225static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 8226 assert(E->isLValue() && E->getType().isConstQualified()); 8227 E = E->IgnoreParens(); 8228 8229 // Must be a reference to a declaration from an enclosing scope. 8230 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 8231 if (!DRE) return NCCK_None; 8232 if (!DRE->refersToEnclosingLocal()) return NCCK_None; 8233 8234 // The declaration must be a variable which is not declared 'const'. 8235 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 8236 if (!var) return NCCK_None; 8237 if (var->getType().isConstQualified()) return NCCK_None; 8238 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 8239 8240 // Decide whether the first capture was for a block or a lambda. 8241 DeclContext *DC = S.CurContext, *Prev = 0; 8242 while (DC != var->getDeclContext()) { 8243 Prev = DC; 8244 DC = DC->getParent(); 8245 } 8246 // Unless we have an init-capture, we've gone one step too far. 8247 if (!var->isInitCapture()) 8248 DC = Prev; 8249 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 8250} 8251 8252/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 8253/// emit an error and return true. If so, return false. 8254static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 8255 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 8256 SourceLocation OrigLoc = Loc; 8257 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 8258 &Loc); 8259 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 8260 IsLV = Expr::MLV_InvalidMessageExpression; 8261 if (IsLV == Expr::MLV_Valid) 8262 return false; 8263 8264 unsigned Diag = 0; 8265 bool NeedType = false; 8266 switch (IsLV) { // C99 6.5.16p2 8267 case Expr::MLV_ConstQualified: 8268 Diag = diag::err_typecheck_assign_const; 8269 8270 // Use a specialized diagnostic when we're assigning to an object 8271 // from an enclosing function or block. 8272 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 8273 if (NCCK == NCCK_Block) 8274 Diag = diag::err_block_decl_ref_not_modifiable_lvalue; 8275 else 8276 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue; 8277 break; 8278 } 8279 8280 // In ARC, use some specialized diagnostics for occasions where we 8281 // infer 'const'. These are always pseudo-strong variables. 8282 if (S.getLangOpts().ObjCAutoRefCount) { 8283 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 8284 if (declRef && isa<VarDecl>(declRef->getDecl())) { 8285 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 8286 8287 // Use the normal diagnostic if it's pseudo-__strong but the 8288 // user actually wrote 'const'. 8289 if (var->isARCPseudoStrong() && 8290 (!var->getTypeSourceInfo() || 8291 !var->getTypeSourceInfo()->getType().isConstQualified())) { 8292 // There are two pseudo-strong cases: 8293 // - self 8294 ObjCMethodDecl *method = S.getCurMethodDecl(); 8295 if (method && var == method->getSelfDecl()) 8296 Diag = method->isClassMethod() 8297 ? diag::err_typecheck_arc_assign_self_class_method 8298 : diag::err_typecheck_arc_assign_self; 8299 8300 // - fast enumeration variables 8301 else 8302 Diag = diag::err_typecheck_arr_assign_enumeration; 8303 8304 SourceRange Assign; 8305 if (Loc != OrigLoc) 8306 Assign = SourceRange(OrigLoc, OrigLoc); 8307 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 8308 // We need to preserve the AST regardless, so migration tool 8309 // can do its job. 8310 return false; 8311 } 8312 } 8313 } 8314 8315 break; 8316 case Expr::MLV_ArrayType: 8317 case Expr::MLV_ArrayTemporary: 8318 Diag = diag::err_typecheck_array_not_modifiable_lvalue; 8319 NeedType = true; 8320 break; 8321 case Expr::MLV_NotObjectType: 8322 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue; 8323 NeedType = true; 8324 break; 8325 case Expr::MLV_LValueCast: 8326 Diag = diag::err_typecheck_lvalue_casts_not_supported; 8327 break; 8328 case Expr::MLV_Valid: 8329 llvm_unreachable("did not take early return for MLV_Valid"); 8330 case Expr::MLV_InvalidExpression: 8331 case Expr::MLV_MemberFunction: 8332 case Expr::MLV_ClassTemporary: 8333 Diag = diag::err_typecheck_expression_not_modifiable_lvalue; 8334 break; 8335 case Expr::MLV_IncompleteType: 8336 case Expr::MLV_IncompleteVoidType: 8337 return S.RequireCompleteType(Loc, E->getType(), 8338 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 8339 case Expr::MLV_DuplicateVectorComponents: 8340 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 8341 break; 8342 case Expr::MLV_NoSetterProperty: 8343 llvm_unreachable("readonly properties should be processed differently"); 8344 case Expr::MLV_InvalidMessageExpression: 8345 Diag = diag::error_readonly_message_assignment; 8346 break; 8347 case Expr::MLV_SubObjCPropertySetting: 8348 Diag = diag::error_no_subobject_property_setting; 8349 break; 8350 } 8351 8352 SourceRange Assign; 8353 if (Loc != OrigLoc) 8354 Assign = SourceRange(OrigLoc, OrigLoc); 8355 if (NeedType) 8356 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign; 8357 else 8358 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 8359 return true; 8360} 8361 8362static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 8363 SourceLocation Loc, 8364 Sema &Sema) { 8365 // C / C++ fields 8366 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 8367 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 8368 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 8369 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 8370 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 8371 } 8372 8373 // Objective-C instance variables 8374 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 8375 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 8376 if (OL && OR && OL->getDecl() == OR->getDecl()) { 8377 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 8378 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 8379 if (RL && RR && RL->getDecl() == RR->getDecl()) 8380 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 8381 } 8382} 8383 8384// C99 6.5.16.1 8385QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 8386 SourceLocation Loc, 8387 QualType CompoundType) { 8388 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 8389 8390 // Verify that LHS is a modifiable lvalue, and emit error if not. 8391 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 8392 return QualType(); 8393 8394 QualType LHSType = LHSExpr->getType(); 8395 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 8396 CompoundType; 8397 AssignConvertType ConvTy; 8398 if (CompoundType.isNull()) { 8399 Expr *RHSCheck = RHS.get(); 8400 8401 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 8402 8403 QualType LHSTy(LHSType); 8404 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 8405 if (RHS.isInvalid()) 8406 return QualType(); 8407 // Special case of NSObject attributes on c-style pointer types. 8408 if (ConvTy == IncompatiblePointer && 8409 ((Context.isObjCNSObjectType(LHSType) && 8410 RHSType->isObjCObjectPointerType()) || 8411 (Context.isObjCNSObjectType(RHSType) && 8412 LHSType->isObjCObjectPointerType()))) 8413 ConvTy = Compatible; 8414 8415 if (ConvTy == Compatible && 8416 LHSType->isObjCObjectType()) 8417 Diag(Loc, diag::err_objc_object_assignment) 8418 << LHSType; 8419 8420 // If the RHS is a unary plus or minus, check to see if they = and + are 8421 // right next to each other. If so, the user may have typo'd "x =+ 4" 8422 // instead of "x += 4". 8423 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 8424 RHSCheck = ICE->getSubExpr(); 8425 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 8426 if ((UO->getOpcode() == UO_Plus || 8427 UO->getOpcode() == UO_Minus) && 8428 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 8429 // Only if the two operators are exactly adjacent. 8430 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 8431 // And there is a space or other character before the subexpr of the 8432 // unary +/-. We don't want to warn on "x=-1". 8433 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 8434 UO->getSubExpr()->getLocStart().isFileID()) { 8435 Diag(Loc, diag::warn_not_compound_assign) 8436 << (UO->getOpcode() == UO_Plus ? "+" : "-") 8437 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 8438 } 8439 } 8440 8441 if (ConvTy == Compatible) { 8442 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 8443 // Warn about retain cycles where a block captures the LHS, but 8444 // not if the LHS is a simple variable into which the block is 8445 // being stored...unless that variable can be captured by reference! 8446 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 8447 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 8448 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 8449 checkRetainCycles(LHSExpr, RHS.get()); 8450 8451 // It is safe to assign a weak reference into a strong variable. 8452 // Although this code can still have problems: 8453 // id x = self.weakProp; 8454 // id y = self.weakProp; 8455 // we do not warn to warn spuriously when 'x' and 'y' are on separate 8456 // paths through the function. This should be revisited if 8457 // -Wrepeated-use-of-weak is made flow-sensitive. 8458 DiagnosticsEngine::Level Level = 8459 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 8460 RHS.get()->getLocStart()); 8461 if (Level != DiagnosticsEngine::Ignored) 8462 getCurFunction()->markSafeWeakUse(RHS.get()); 8463 8464 } else if (getLangOpts().ObjCAutoRefCount) { 8465 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 8466 } 8467 } 8468 } else { 8469 // Compound assignment "x += y" 8470 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 8471 } 8472 8473 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 8474 RHS.get(), AA_Assigning)) 8475 return QualType(); 8476 8477 CheckForNullPointerDereference(*this, LHSExpr); 8478 8479 // C99 6.5.16p3: The type of an assignment expression is the type of the 8480 // left operand unless the left operand has qualified type, in which case 8481 // it is the unqualified version of the type of the left operand. 8482 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 8483 // is converted to the type of the assignment expression (above). 8484 // C++ 5.17p1: the type of the assignment expression is that of its left 8485 // operand. 8486 return (getLangOpts().CPlusPlus 8487 ? LHSType : LHSType.getUnqualifiedType()); 8488} 8489 8490// C99 6.5.17 8491static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 8492 SourceLocation Loc) { 8493 LHS = S.CheckPlaceholderExpr(LHS.take()); 8494 RHS = S.CheckPlaceholderExpr(RHS.take()); 8495 if (LHS.isInvalid() || RHS.isInvalid()) 8496 return QualType(); 8497 8498 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 8499 // operands, but not unary promotions. 8500 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 8501 8502 // So we treat the LHS as a ignored value, and in C++ we allow the 8503 // containing site to determine what should be done with the RHS. 8504 LHS = S.IgnoredValueConversions(LHS.take()); 8505 if (LHS.isInvalid()) 8506 return QualType(); 8507 8508 S.DiagnoseUnusedExprResult(LHS.get()); 8509 8510 if (!S.getLangOpts().CPlusPlus) { 8511 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take()); 8512 if (RHS.isInvalid()) 8513 return QualType(); 8514 if (!RHS.get()->getType()->isVoidType()) 8515 S.RequireCompleteType(Loc, RHS.get()->getType(), 8516 diag::err_incomplete_type); 8517 } 8518 8519 return RHS.get()->getType(); 8520} 8521 8522/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 8523/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 8524static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 8525 ExprValueKind &VK, 8526 SourceLocation OpLoc, 8527 bool IsInc, bool IsPrefix) { 8528 if (Op->isTypeDependent()) 8529 return S.Context.DependentTy; 8530 8531 QualType ResType = Op->getType(); 8532 // Atomic types can be used for increment / decrement where the non-atomic 8533 // versions can, so ignore the _Atomic() specifier for the purpose of 8534 // checking. 8535 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8536 ResType = ResAtomicType->getValueType(); 8537 8538 assert(!ResType.isNull() && "no type for increment/decrement expression"); 8539 8540 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 8541 // Decrement of bool is not allowed. 8542 if (!IsInc) { 8543 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 8544 return QualType(); 8545 } 8546 // Increment of bool sets it to true, but is deprecated. 8547 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); 8548 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 8549 // Error on enum increments and decrements in C++ mode 8550 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 8551 return QualType(); 8552 } else if (ResType->isRealType()) { 8553 // OK! 8554 } else if (ResType->isPointerType()) { 8555 // C99 6.5.2.4p2, 6.5.6p2 8556 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 8557 return QualType(); 8558 } else if (ResType->isObjCObjectPointerType()) { 8559 // On modern runtimes, ObjC pointer arithmetic is forbidden. 8560 // Otherwise, we just need a complete type. 8561 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 8562 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 8563 return QualType(); 8564 } else if (ResType->isAnyComplexType()) { 8565 // C99 does not support ++/-- on complex types, we allow as an extension. 8566 S.Diag(OpLoc, diag::ext_integer_increment_complex) 8567 << ResType << Op->getSourceRange(); 8568 } else if (ResType->isPlaceholderType()) { 8569 ExprResult PR = S.CheckPlaceholderExpr(Op); 8570 if (PR.isInvalid()) return QualType(); 8571 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc, 8572 IsInc, IsPrefix); 8573 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 8574 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 8575 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 8576 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 8577 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 8578 } else { 8579 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 8580 << ResType << int(IsInc) << Op->getSourceRange(); 8581 return QualType(); 8582 } 8583 // At this point, we know we have a real, complex or pointer type. 8584 // Now make sure the operand is a modifiable lvalue. 8585 if (CheckForModifiableLvalue(Op, OpLoc, S)) 8586 return QualType(); 8587 // In C++, a prefix increment is the same type as the operand. Otherwise 8588 // (in C or with postfix), the increment is the unqualified type of the 8589 // operand. 8590 if (IsPrefix && S.getLangOpts().CPlusPlus) { 8591 VK = VK_LValue; 8592 return ResType; 8593 } else { 8594 VK = VK_RValue; 8595 return ResType.getUnqualifiedType(); 8596 } 8597} 8598 8599 8600/// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 8601/// This routine allows us to typecheck complex/recursive expressions 8602/// where the declaration is needed for type checking. We only need to 8603/// handle cases when the expression references a function designator 8604/// or is an lvalue. Here are some examples: 8605/// - &(x) => x 8606/// - &*****f => f for f a function designator. 8607/// - &s.xx => s 8608/// - &s.zz[1].yy -> s, if zz is an array 8609/// - *(x + 1) -> x, if x is an array 8610/// - &"123"[2] -> 0 8611/// - & __real__ x -> x 8612static ValueDecl *getPrimaryDecl(Expr *E) { 8613 switch (E->getStmtClass()) { 8614 case Stmt::DeclRefExprClass: 8615 return cast<DeclRefExpr>(E)->getDecl(); 8616 case Stmt::MemberExprClass: 8617 // If this is an arrow operator, the address is an offset from 8618 // the base's value, so the object the base refers to is 8619 // irrelevant. 8620 if (cast<MemberExpr>(E)->isArrow()) 8621 return 0; 8622 // Otherwise, the expression refers to a part of the base 8623 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 8624 case Stmt::ArraySubscriptExprClass: { 8625 // FIXME: This code shouldn't be necessary! We should catch the implicit 8626 // promotion of register arrays earlier. 8627 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 8628 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 8629 if (ICE->getSubExpr()->getType()->isArrayType()) 8630 return getPrimaryDecl(ICE->getSubExpr()); 8631 } 8632 return 0; 8633 } 8634 case Stmt::UnaryOperatorClass: { 8635 UnaryOperator *UO = cast<UnaryOperator>(E); 8636 8637 switch(UO->getOpcode()) { 8638 case UO_Real: 8639 case UO_Imag: 8640 case UO_Extension: 8641 return getPrimaryDecl(UO->getSubExpr()); 8642 default: 8643 return 0; 8644 } 8645 } 8646 case Stmt::ParenExprClass: 8647 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 8648 case Stmt::ImplicitCastExprClass: 8649 // If the result of an implicit cast is an l-value, we care about 8650 // the sub-expression; otherwise, the result here doesn't matter. 8651 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 8652 default: 8653 return 0; 8654 } 8655} 8656 8657namespace { 8658 enum { 8659 AO_Bit_Field = 0, 8660 AO_Vector_Element = 1, 8661 AO_Property_Expansion = 2, 8662 AO_Register_Variable = 3, 8663 AO_No_Error = 4 8664 }; 8665} 8666/// \brief Diagnose invalid operand for address of operations. 8667/// 8668/// \param Type The type of operand which cannot have its address taken. 8669static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 8670 Expr *E, unsigned Type) { 8671 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 8672} 8673 8674/// CheckAddressOfOperand - The operand of & must be either a function 8675/// designator or an lvalue designating an object. If it is an lvalue, the 8676/// object cannot be declared with storage class register or be a bit field. 8677/// Note: The usual conversions are *not* applied to the operand of the & 8678/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 8679/// In C++, the operand might be an overloaded function name, in which case 8680/// we allow the '&' but retain the overloaded-function type. 8681QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 8682 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 8683 if (PTy->getKind() == BuiltinType::Overload) { 8684 Expr *E = OrigOp.get()->IgnoreParens(); 8685 if (!isa<OverloadExpr>(E)) { 8686 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 8687 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 8688 << OrigOp.get()->getSourceRange(); 8689 return QualType(); 8690 } 8691 8692 OverloadExpr *Ovl = cast<OverloadExpr>(E); 8693 if (isa<UnresolvedMemberExpr>(Ovl)) 8694 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 8695 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8696 << OrigOp.get()->getSourceRange(); 8697 return QualType(); 8698 } 8699 8700 return Context.OverloadTy; 8701 } 8702 8703 if (PTy->getKind() == BuiltinType::UnknownAny) 8704 return Context.UnknownAnyTy; 8705 8706 if (PTy->getKind() == BuiltinType::BoundMember) { 8707 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8708 << OrigOp.get()->getSourceRange(); 8709 return QualType(); 8710 } 8711 8712 OrigOp = CheckPlaceholderExpr(OrigOp.take()); 8713 if (OrigOp.isInvalid()) return QualType(); 8714 } 8715 8716 if (OrigOp.get()->isTypeDependent()) 8717 return Context.DependentTy; 8718 8719 assert(!OrigOp.get()->getType()->isPlaceholderType()); 8720 8721 // Make sure to ignore parentheses in subsequent checks 8722 Expr *op = OrigOp.get()->IgnoreParens(); 8723 8724 if (getLangOpts().C99) { 8725 // Implement C99-only parts of addressof rules. 8726 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 8727 if (uOp->getOpcode() == UO_Deref) 8728 // Per C99 6.5.3.2, the address of a deref always returns a valid result 8729 // (assuming the deref expression is valid). 8730 return uOp->getSubExpr()->getType(); 8731 } 8732 // Technically, there should be a check for array subscript 8733 // expressions here, but the result of one is always an lvalue anyway. 8734 } 8735 ValueDecl *dcl = getPrimaryDecl(op); 8736 Expr::LValueClassification lval = op->ClassifyLValue(Context); 8737 unsigned AddressOfError = AO_No_Error; 8738 8739 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 8740 bool sfinae = (bool)isSFINAEContext(); 8741 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 8742 : diag::ext_typecheck_addrof_temporary) 8743 << op->getType() << op->getSourceRange(); 8744 if (sfinae) 8745 return QualType(); 8746 // Materialize the temporary as an lvalue so that we can take its address. 8747 OrigOp = op = new (Context) 8748 MaterializeTemporaryExpr(op->getType(), OrigOp.take(), true, 0); 8749 } else if (isa<ObjCSelectorExpr>(op)) { 8750 return Context.getPointerType(op->getType()); 8751 } else if (lval == Expr::LV_MemberFunction) { 8752 // If it's an instance method, make a member pointer. 8753 // The expression must have exactly the form &A::foo. 8754 8755 // If the underlying expression isn't a decl ref, give up. 8756 if (!isa<DeclRefExpr>(op)) { 8757 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8758 << OrigOp.get()->getSourceRange(); 8759 return QualType(); 8760 } 8761 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 8762 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 8763 8764 // The id-expression was parenthesized. 8765 if (OrigOp.get() != DRE) { 8766 Diag(OpLoc, diag::err_parens_pointer_member_function) 8767 << OrigOp.get()->getSourceRange(); 8768 8769 // The method was named without a qualifier. 8770 } else if (!DRE->getQualifier()) { 8771 if (MD->getParent()->getName().empty()) 8772 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 8773 << op->getSourceRange(); 8774 else { 8775 SmallString<32> Str; 8776 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 8777 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 8778 << op->getSourceRange() 8779 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 8780 } 8781 } 8782 8783 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 8784 if (isa<CXXDestructorDecl>(MD)) 8785 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 8786 8787 return Context.getMemberPointerType(op->getType(), 8788 Context.getTypeDeclType(MD->getParent()).getTypePtr()); 8789 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 8790 // C99 6.5.3.2p1 8791 // The operand must be either an l-value or a function designator 8792 if (!op->getType()->isFunctionType()) { 8793 // Use a special diagnostic for loads from property references. 8794 if (isa<PseudoObjectExpr>(op)) { 8795 AddressOfError = AO_Property_Expansion; 8796 } else { 8797 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 8798 << op->getType() << op->getSourceRange(); 8799 return QualType(); 8800 } 8801 } 8802 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 8803 // The operand cannot be a bit-field 8804 AddressOfError = AO_Bit_Field; 8805 } else if (op->getObjectKind() == OK_VectorComponent) { 8806 // The operand cannot be an element of a vector 8807 AddressOfError = AO_Vector_Element; 8808 } else if (dcl) { // C99 6.5.3.2p1 8809 // We have an lvalue with a decl. Make sure the decl is not declared 8810 // with the register storage-class specifier. 8811 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 8812 // in C++ it is not error to take address of a register 8813 // variable (c++03 7.1.1P3) 8814 if (vd->getStorageClass() == SC_Register && 8815 !getLangOpts().CPlusPlus) { 8816 AddressOfError = AO_Register_Variable; 8817 } 8818 } else if (isa<FunctionTemplateDecl>(dcl)) { 8819 return Context.OverloadTy; 8820 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 8821 // Okay: we can take the address of a field. 8822 // Could be a pointer to member, though, if there is an explicit 8823 // scope qualifier for the class. 8824 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 8825 DeclContext *Ctx = dcl->getDeclContext(); 8826 if (Ctx && Ctx->isRecord()) { 8827 if (dcl->getType()->isReferenceType()) { 8828 Diag(OpLoc, 8829 diag::err_cannot_form_pointer_to_member_of_reference_type) 8830 << dcl->getDeclName() << dcl->getType(); 8831 return QualType(); 8832 } 8833 8834 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 8835 Ctx = Ctx->getParent(); 8836 return Context.getMemberPointerType(op->getType(), 8837 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 8838 } 8839 } 8840 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl)) 8841 llvm_unreachable("Unknown/unexpected decl type"); 8842 } 8843 8844 if (AddressOfError != AO_No_Error) { 8845 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 8846 return QualType(); 8847 } 8848 8849 if (lval == Expr::LV_IncompleteVoidType) { 8850 // Taking the address of a void variable is technically illegal, but we 8851 // allow it in cases which are otherwise valid. 8852 // Example: "extern void x; void* y = &x;". 8853 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 8854 } 8855 8856 // If the operand has type "type", the result has type "pointer to type". 8857 if (op->getType()->isObjCObjectType()) 8858 return Context.getObjCObjectPointerType(op->getType()); 8859 return Context.getPointerType(op->getType()); 8860} 8861 8862/// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 8863static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 8864 SourceLocation OpLoc) { 8865 if (Op->isTypeDependent()) 8866 return S.Context.DependentTy; 8867 8868 ExprResult ConvResult = S.UsualUnaryConversions(Op); 8869 if (ConvResult.isInvalid()) 8870 return QualType(); 8871 Op = ConvResult.take(); 8872 QualType OpTy = Op->getType(); 8873 QualType Result; 8874 8875 if (isa<CXXReinterpretCastExpr>(Op)) { 8876 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 8877 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 8878 Op->getSourceRange()); 8879 } 8880 8881 // Note that per both C89 and C99, indirection is always legal, even if OpTy 8882 // is an incomplete type or void. It would be possible to warn about 8883 // dereferencing a void pointer, but it's completely well-defined, and such a 8884 // warning is unlikely to catch any mistakes. 8885 if (const PointerType *PT = OpTy->getAs<PointerType>()) 8886 Result = PT->getPointeeType(); 8887 else if (const ObjCObjectPointerType *OPT = 8888 OpTy->getAs<ObjCObjectPointerType>()) 8889 Result = OPT->getPointeeType(); 8890 else { 8891 ExprResult PR = S.CheckPlaceholderExpr(Op); 8892 if (PR.isInvalid()) return QualType(); 8893 if (PR.take() != Op) 8894 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc); 8895 } 8896 8897 if (Result.isNull()) { 8898 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 8899 << OpTy << Op->getSourceRange(); 8900 return QualType(); 8901 } 8902 8903 // Dereferences are usually l-values... 8904 VK = VK_LValue; 8905 8906 // ...except that certain expressions are never l-values in C. 8907 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 8908 VK = VK_RValue; 8909 8910 return Result; 8911} 8912 8913static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode( 8914 tok::TokenKind Kind) { 8915 BinaryOperatorKind Opc; 8916 switch (Kind) { 8917 default: llvm_unreachable("Unknown binop!"); 8918 case tok::periodstar: Opc = BO_PtrMemD; break; 8919 case tok::arrowstar: Opc = BO_PtrMemI; break; 8920 case tok::star: Opc = BO_Mul; break; 8921 case tok::slash: Opc = BO_Div; break; 8922 case tok::percent: Opc = BO_Rem; break; 8923 case tok::plus: Opc = BO_Add; break; 8924 case tok::minus: Opc = BO_Sub; break; 8925 case tok::lessless: Opc = BO_Shl; break; 8926 case tok::greatergreater: Opc = BO_Shr; break; 8927 case tok::lessequal: Opc = BO_LE; break; 8928 case tok::less: Opc = BO_LT; break; 8929 case tok::greaterequal: Opc = BO_GE; break; 8930 case tok::greater: Opc = BO_GT; break; 8931 case tok::exclaimequal: Opc = BO_NE; break; 8932 case tok::equalequal: Opc = BO_EQ; break; 8933 case tok::amp: Opc = BO_And; break; 8934 case tok::caret: Opc = BO_Xor; break; 8935 case tok::pipe: Opc = BO_Or; break; 8936 case tok::ampamp: Opc = BO_LAnd; break; 8937 case tok::pipepipe: Opc = BO_LOr; break; 8938 case tok::equal: Opc = BO_Assign; break; 8939 case tok::starequal: Opc = BO_MulAssign; break; 8940 case tok::slashequal: Opc = BO_DivAssign; break; 8941 case tok::percentequal: Opc = BO_RemAssign; break; 8942 case tok::plusequal: Opc = BO_AddAssign; break; 8943 case tok::minusequal: Opc = BO_SubAssign; break; 8944 case tok::lesslessequal: Opc = BO_ShlAssign; break; 8945 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 8946 case tok::ampequal: Opc = BO_AndAssign; break; 8947 case tok::caretequal: Opc = BO_XorAssign; break; 8948 case tok::pipeequal: Opc = BO_OrAssign; break; 8949 case tok::comma: Opc = BO_Comma; break; 8950 } 8951 return Opc; 8952} 8953 8954static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 8955 tok::TokenKind Kind) { 8956 UnaryOperatorKind Opc; 8957 switch (Kind) { 8958 default: llvm_unreachable("Unknown unary op!"); 8959 case tok::plusplus: Opc = UO_PreInc; break; 8960 case tok::minusminus: Opc = UO_PreDec; break; 8961 case tok::amp: Opc = UO_AddrOf; break; 8962 case tok::star: Opc = UO_Deref; break; 8963 case tok::plus: Opc = UO_Plus; break; 8964 case tok::minus: Opc = UO_Minus; break; 8965 case tok::tilde: Opc = UO_Not; break; 8966 case tok::exclaim: Opc = UO_LNot; break; 8967 case tok::kw___real: Opc = UO_Real; break; 8968 case tok::kw___imag: Opc = UO_Imag; break; 8969 case tok::kw___extension__: Opc = UO_Extension; break; 8970 } 8971 return Opc; 8972} 8973 8974/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 8975/// This warning is only emitted for builtin assignment operations. It is also 8976/// suppressed in the event of macro expansions. 8977static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 8978 SourceLocation OpLoc) { 8979 if (!S.ActiveTemplateInstantiations.empty()) 8980 return; 8981 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 8982 return; 8983 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 8984 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 8985 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 8986 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 8987 if (!LHSDeclRef || !RHSDeclRef || 8988 LHSDeclRef->getLocation().isMacroID() || 8989 RHSDeclRef->getLocation().isMacroID()) 8990 return; 8991 const ValueDecl *LHSDecl = 8992 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 8993 const ValueDecl *RHSDecl = 8994 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 8995 if (LHSDecl != RHSDecl) 8996 return; 8997 if (LHSDecl->getType().isVolatileQualified()) 8998 return; 8999 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 9000 if (RefTy->getPointeeType().isVolatileQualified()) 9001 return; 9002 9003 S.Diag(OpLoc, diag::warn_self_assignment) 9004 << LHSDeclRef->getType() 9005 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 9006} 9007 9008/// Check if a bitwise-& is performed on an Objective-C pointer. This 9009/// is usually indicative of introspection within the Objective-C pointer. 9010static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 9011 SourceLocation OpLoc) { 9012 if (!S.getLangOpts().ObjC1) 9013 return; 9014 9015 const Expr *ObjCPointerExpr = 0, *OtherExpr = 0; 9016 const Expr *LHS = L.get(); 9017 const Expr *RHS = R.get(); 9018 9019 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 9020 ObjCPointerExpr = LHS; 9021 OtherExpr = RHS; 9022 } 9023 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 9024 ObjCPointerExpr = RHS; 9025 OtherExpr = LHS; 9026 } 9027 9028 // This warning is deliberately made very specific to reduce false 9029 // positives with logic that uses '&' for hashing. This logic mainly 9030 // looks for code trying to introspect into tagged pointers, which 9031 // code should generally never do. 9032 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 9033 unsigned Diag = diag::warn_objc_pointer_masking; 9034 // Determine if we are introspecting the result of performSelectorXXX. 9035 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 9036 // Special case messages to -performSelector and friends, which 9037 // can return non-pointer values boxed in a pointer value. 9038 // Some clients may wish to silence warnings in this subcase. 9039 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 9040 Selector S = ME->getSelector(); 9041 StringRef SelArg0 = S.getNameForSlot(0); 9042 if (SelArg0.startswith("performSelector")) 9043 Diag = diag::warn_objc_pointer_masking_performSelector; 9044 } 9045 9046 S.Diag(OpLoc, Diag) 9047 << ObjCPointerExpr->getSourceRange(); 9048 } 9049} 9050 9051/// CreateBuiltinBinOp - Creates a new built-in binary operation with 9052/// operator @p Opc at location @c TokLoc. This routine only supports 9053/// built-in operations; ActOnBinOp handles overloaded operators. 9054ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 9055 BinaryOperatorKind Opc, 9056 Expr *LHSExpr, Expr *RHSExpr) { 9057 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 9058 // The syntax only allows initializer lists on the RHS of assignment, 9059 // so we don't need to worry about accepting invalid code for 9060 // non-assignment operators. 9061 // C++11 5.17p9: 9062 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 9063 // of x = {} is x = T(). 9064 InitializationKind Kind = 9065 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 9066 InitializedEntity Entity = 9067 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 9068 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 9069 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 9070 if (Init.isInvalid()) 9071 return Init; 9072 RHSExpr = Init.take(); 9073 } 9074 9075 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 9076 QualType ResultTy; // Result type of the binary operator. 9077 // The following two variables are used for compound assignment operators 9078 QualType CompLHSTy; // Type of LHS after promotions for computation 9079 QualType CompResultTy; // Type of computation result 9080 ExprValueKind VK = VK_RValue; 9081 ExprObjectKind OK = OK_Ordinary; 9082 9083 switch (Opc) { 9084 case BO_Assign: 9085 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 9086 if (getLangOpts().CPlusPlus && 9087 LHS.get()->getObjectKind() != OK_ObjCProperty) { 9088 VK = LHS.get()->getValueKind(); 9089 OK = LHS.get()->getObjectKind(); 9090 } 9091 if (!ResultTy.isNull()) 9092 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 9093 break; 9094 case BO_PtrMemD: 9095 case BO_PtrMemI: 9096 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 9097 Opc == BO_PtrMemI); 9098 break; 9099 case BO_Mul: 9100 case BO_Div: 9101 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 9102 Opc == BO_Div); 9103 break; 9104 case BO_Rem: 9105 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 9106 break; 9107 case BO_Add: 9108 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 9109 break; 9110 case BO_Sub: 9111 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 9112 break; 9113 case BO_Shl: 9114 case BO_Shr: 9115 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 9116 break; 9117 case BO_LE: 9118 case BO_LT: 9119 case BO_GE: 9120 case BO_GT: 9121 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 9122 break; 9123 case BO_EQ: 9124 case BO_NE: 9125 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 9126 break; 9127 case BO_And: 9128 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 9129 case BO_Xor: 9130 case BO_Or: 9131 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 9132 break; 9133 case BO_LAnd: 9134 case BO_LOr: 9135 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 9136 break; 9137 case BO_MulAssign: 9138 case BO_DivAssign: 9139 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 9140 Opc == BO_DivAssign); 9141 CompLHSTy = CompResultTy; 9142 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9143 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9144 break; 9145 case BO_RemAssign: 9146 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 9147 CompLHSTy = CompResultTy; 9148 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9149 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9150 break; 9151 case BO_AddAssign: 9152 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 9153 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9154 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9155 break; 9156 case BO_SubAssign: 9157 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 9158 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9159 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9160 break; 9161 case BO_ShlAssign: 9162 case BO_ShrAssign: 9163 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 9164 CompLHSTy = CompResultTy; 9165 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9166 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9167 break; 9168 case BO_AndAssign: 9169 case BO_XorAssign: 9170 case BO_OrAssign: 9171 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 9172 CompLHSTy = CompResultTy; 9173 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9174 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9175 break; 9176 case BO_Comma: 9177 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 9178 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 9179 VK = RHS.get()->getValueKind(); 9180 OK = RHS.get()->getObjectKind(); 9181 } 9182 break; 9183 } 9184 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 9185 return ExprError(); 9186 9187 // Check for array bounds violations for both sides of the BinaryOperator 9188 CheckArrayAccess(LHS.get()); 9189 CheckArrayAccess(RHS.get()); 9190 9191 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 9192 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 9193 &Context.Idents.get("object_setClass"), 9194 SourceLocation(), LookupOrdinaryName); 9195 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 9196 SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 9197 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 9198 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 9199 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 9200 FixItHint::CreateInsertion(RHSLocEnd, ")"); 9201 } 9202 else 9203 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 9204 } 9205 else if (const ObjCIvarRefExpr *OIRE = 9206 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 9207 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 9208 9209 if (CompResultTy.isNull()) 9210 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc, 9211 ResultTy, VK, OK, OpLoc, 9212 FPFeatures.fp_contract)); 9213 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 9214 OK_ObjCProperty) { 9215 VK = VK_LValue; 9216 OK = LHS.get()->getObjectKind(); 9217 } 9218 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc, 9219 ResultTy, VK, OK, CompLHSTy, 9220 CompResultTy, OpLoc, 9221 FPFeatures.fp_contract)); 9222} 9223 9224/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 9225/// operators are mixed in a way that suggests that the programmer forgot that 9226/// comparison operators have higher precedence. The most typical example of 9227/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 9228static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 9229 SourceLocation OpLoc, Expr *LHSExpr, 9230 Expr *RHSExpr) { 9231 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 9232 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 9233 9234 // Check that one of the sides is a comparison operator. 9235 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 9236 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 9237 if (!isLeftComp && !isRightComp) 9238 return; 9239 9240 // Bitwise operations are sometimes used as eager logical ops. 9241 // Don't diagnose this. 9242 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 9243 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 9244 if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise)) 9245 return; 9246 9247 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 9248 OpLoc) 9249 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 9250 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 9251 SourceRange ParensRange = isLeftComp ? 9252 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 9253 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart()); 9254 9255 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 9256 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 9257 SuggestParentheses(Self, OpLoc, 9258 Self.PDiag(diag::note_precedence_silence) << OpStr, 9259 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 9260 SuggestParentheses(Self, OpLoc, 9261 Self.PDiag(diag::note_precedence_bitwise_first) 9262 << BinaryOperator::getOpcodeStr(Opc), 9263 ParensRange); 9264} 9265 9266/// \brief It accepts a '&' expr that is inside a '|' one. 9267/// Emit a diagnostic together with a fixit hint that wraps the '&' expression 9268/// in parentheses. 9269static void 9270EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc, 9271 BinaryOperator *Bop) { 9272 assert(Bop->getOpcode() == BO_And); 9273 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or) 9274 << Bop->getSourceRange() << OpLoc; 9275 SuggestParentheses(Self, Bop->getOperatorLoc(), 9276 Self.PDiag(diag::note_precedence_silence) 9277 << Bop->getOpcodeStr(), 9278 Bop->getSourceRange()); 9279} 9280 9281/// \brief It accepts a '&&' expr that is inside a '||' one. 9282/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 9283/// in parentheses. 9284static void 9285EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 9286 BinaryOperator *Bop) { 9287 assert(Bop->getOpcode() == BO_LAnd); 9288 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 9289 << Bop->getSourceRange() << OpLoc; 9290 SuggestParentheses(Self, Bop->getOperatorLoc(), 9291 Self.PDiag(diag::note_precedence_silence) 9292 << Bop->getOpcodeStr(), 9293 Bop->getSourceRange()); 9294} 9295 9296/// \brief Returns true if the given expression can be evaluated as a constant 9297/// 'true'. 9298static bool EvaluatesAsTrue(Sema &S, Expr *E) { 9299 bool Res; 9300 return !E->isValueDependent() && 9301 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 9302} 9303 9304/// \brief Returns true if the given expression can be evaluated as a constant 9305/// 'false'. 9306static bool EvaluatesAsFalse(Sema &S, Expr *E) { 9307 bool Res; 9308 return !E->isValueDependent() && 9309 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 9310} 9311 9312/// \brief Look for '&&' in the left hand of a '||' expr. 9313static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 9314 Expr *LHSExpr, Expr *RHSExpr) { 9315 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 9316 if (Bop->getOpcode() == BO_LAnd) { 9317 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 9318 if (EvaluatesAsFalse(S, RHSExpr)) 9319 return; 9320 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 9321 if (!EvaluatesAsTrue(S, Bop->getLHS())) 9322 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 9323 } else if (Bop->getOpcode() == BO_LOr) { 9324 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 9325 // If it's "a || b && 1 || c" we didn't warn earlier for 9326 // "a || b && 1", but warn now. 9327 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 9328 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 9329 } 9330 } 9331 } 9332} 9333 9334/// \brief Look for '&&' in the right hand of a '||' expr. 9335static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 9336 Expr *LHSExpr, Expr *RHSExpr) { 9337 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 9338 if (Bop->getOpcode() == BO_LAnd) { 9339 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 9340 if (EvaluatesAsFalse(S, LHSExpr)) 9341 return; 9342 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 9343 if (!EvaluatesAsTrue(S, Bop->getRHS())) 9344 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 9345 } 9346 } 9347} 9348 9349/// \brief Look for '&' in the left or right hand of a '|' expr. 9350static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc, 9351 Expr *OrArg) { 9352 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) { 9353 if (Bop->getOpcode() == BO_And) 9354 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop); 9355 } 9356} 9357 9358static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 9359 Expr *SubExpr, StringRef Shift) { 9360 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 9361 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 9362 StringRef Op = Bop->getOpcodeStr(); 9363 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 9364 << Bop->getSourceRange() << OpLoc << Shift << Op; 9365 SuggestParentheses(S, Bop->getOperatorLoc(), 9366 S.PDiag(diag::note_precedence_silence) << Op, 9367 Bop->getSourceRange()); 9368 } 9369 } 9370} 9371 9372static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 9373 Expr *LHSExpr, Expr *RHSExpr) { 9374 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 9375 if (!OCE) 9376 return; 9377 9378 FunctionDecl *FD = OCE->getDirectCallee(); 9379 if (!FD || !FD->isOverloadedOperator()) 9380 return; 9381 9382 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 9383 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 9384 return; 9385 9386 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 9387 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 9388 << (Kind == OO_LessLess); 9389 SuggestParentheses(S, OCE->getOperatorLoc(), 9390 S.PDiag(diag::note_precedence_silence) 9391 << (Kind == OO_LessLess ? "<<" : ">>"), 9392 OCE->getSourceRange()); 9393 SuggestParentheses(S, OpLoc, 9394 S.PDiag(diag::note_evaluate_comparison_first), 9395 SourceRange(OCE->getArg(1)->getLocStart(), 9396 RHSExpr->getLocEnd())); 9397} 9398 9399/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 9400/// precedence. 9401static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 9402 SourceLocation OpLoc, Expr *LHSExpr, 9403 Expr *RHSExpr){ 9404 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 9405 if (BinaryOperator::isBitwiseOp(Opc)) 9406 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 9407 9408 // Diagnose "arg1 & arg2 | arg3" 9409 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) { 9410 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr); 9411 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr); 9412 } 9413 9414 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 9415 // We don't warn for 'assert(a || b && "bad")' since this is safe. 9416 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 9417 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 9418 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 9419 } 9420 9421 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 9422 || Opc == BO_Shr) { 9423 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 9424 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 9425 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 9426 } 9427 9428 // Warn on overloaded shift operators and comparisons, such as: 9429 // cout << 5 == 4; 9430 if (BinaryOperator::isComparisonOp(Opc)) 9431 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 9432} 9433 9434// Binary Operators. 'Tok' is the token for the operator. 9435ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 9436 tok::TokenKind Kind, 9437 Expr *LHSExpr, Expr *RHSExpr) { 9438 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 9439 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression"); 9440 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression"); 9441 9442 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 9443 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 9444 9445 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 9446} 9447 9448/// Build an overloaded binary operator expression in the given scope. 9449static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 9450 BinaryOperatorKind Opc, 9451 Expr *LHS, Expr *RHS) { 9452 // Find all of the overloaded operators visible from this 9453 // point. We perform both an operator-name lookup from the local 9454 // scope and an argument-dependent lookup based on the types of 9455 // the arguments. 9456 UnresolvedSet<16> Functions; 9457 OverloadedOperatorKind OverOp 9458 = BinaryOperator::getOverloadedOperator(Opc); 9459 if (Sc && OverOp != OO_None) 9460 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 9461 RHS->getType(), Functions); 9462 9463 // Build the (potentially-overloaded, potentially-dependent) 9464 // binary operation. 9465 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 9466} 9467 9468ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 9469 BinaryOperatorKind Opc, 9470 Expr *LHSExpr, Expr *RHSExpr) { 9471 // We want to end up calling one of checkPseudoObjectAssignment 9472 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 9473 // both expressions are overloadable or either is type-dependent), 9474 // or CreateBuiltinBinOp (in any other case). We also want to get 9475 // any placeholder types out of the way. 9476 9477 // Handle pseudo-objects in the LHS. 9478 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 9479 // Assignments with a pseudo-object l-value need special analysis. 9480 if (pty->getKind() == BuiltinType::PseudoObject && 9481 BinaryOperator::isAssignmentOp(Opc)) 9482 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 9483 9484 // Don't resolve overloads if the other type is overloadable. 9485 if (pty->getKind() == BuiltinType::Overload) { 9486 // We can't actually test that if we still have a placeholder, 9487 // though. Fortunately, none of the exceptions we see in that 9488 // code below are valid when the LHS is an overload set. Note 9489 // that an overload set can be dependently-typed, but it never 9490 // instantiates to having an overloadable type. 9491 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 9492 if (resolvedRHS.isInvalid()) return ExprError(); 9493 RHSExpr = resolvedRHS.take(); 9494 9495 if (RHSExpr->isTypeDependent() || 9496 RHSExpr->getType()->isOverloadableType()) 9497 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9498 } 9499 9500 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 9501 if (LHS.isInvalid()) return ExprError(); 9502 LHSExpr = LHS.take(); 9503 } 9504 9505 // Handle pseudo-objects in the RHS. 9506 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 9507 // An overload in the RHS can potentially be resolved by the type 9508 // being assigned to. 9509 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 9510 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 9511 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9512 9513 if (LHSExpr->getType()->isOverloadableType()) 9514 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9515 9516 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 9517 } 9518 9519 // Don't resolve overloads if the other type is overloadable. 9520 if (pty->getKind() == BuiltinType::Overload && 9521 LHSExpr->getType()->isOverloadableType()) 9522 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9523 9524 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 9525 if (!resolvedRHS.isUsable()) return ExprError(); 9526 RHSExpr = resolvedRHS.take(); 9527 } 9528 9529 if (getLangOpts().CPlusPlus) { 9530 // If either expression is type-dependent, always build an 9531 // overloaded op. 9532 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 9533 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9534 9535 // Otherwise, build an overloaded op if either expression has an 9536 // overloadable type. 9537 if (LHSExpr->getType()->isOverloadableType() || 9538 RHSExpr->getType()->isOverloadableType()) 9539 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9540 } 9541 9542 // Build a built-in binary operation. 9543 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 9544} 9545 9546ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 9547 UnaryOperatorKind Opc, 9548 Expr *InputExpr) { 9549 ExprResult Input = Owned(InputExpr); 9550 ExprValueKind VK = VK_RValue; 9551 ExprObjectKind OK = OK_Ordinary; 9552 QualType resultType; 9553 switch (Opc) { 9554 case UO_PreInc: 9555 case UO_PreDec: 9556 case UO_PostInc: 9557 case UO_PostDec: 9558 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc, 9559 Opc == UO_PreInc || 9560 Opc == UO_PostInc, 9561 Opc == UO_PreInc || 9562 Opc == UO_PreDec); 9563 break; 9564 case UO_AddrOf: 9565 resultType = CheckAddressOfOperand(Input, OpLoc); 9566 break; 9567 case UO_Deref: { 9568 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 9569 if (Input.isInvalid()) return ExprError(); 9570 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 9571 break; 9572 } 9573 case UO_Plus: 9574 case UO_Minus: 9575 Input = UsualUnaryConversions(Input.take()); 9576 if (Input.isInvalid()) return ExprError(); 9577 resultType = Input.get()->getType(); 9578 if (resultType->isDependentType()) 9579 break; 9580 if (resultType->isArithmeticType() || // C99 6.5.3.3p1 9581 resultType->isVectorType()) 9582 break; 9583 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 9584 Opc == UO_Plus && 9585 resultType->isPointerType()) 9586 break; 9587 9588 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9589 << resultType << Input.get()->getSourceRange()); 9590 9591 case UO_Not: // bitwise complement 9592 Input = UsualUnaryConversions(Input.take()); 9593 if (Input.isInvalid()) 9594 return ExprError(); 9595 resultType = Input.get()->getType(); 9596 if (resultType->isDependentType()) 9597 break; 9598 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 9599 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 9600 // C99 does not support '~' for complex conjugation. 9601 Diag(OpLoc, diag::ext_integer_complement_complex) 9602 << resultType << Input.get()->getSourceRange(); 9603 else if (resultType->hasIntegerRepresentation()) 9604 break; 9605 else if (resultType->isExtVectorType()) { 9606 if (Context.getLangOpts().OpenCL) { 9607 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 9608 // on vector float types. 9609 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 9610 if (!T->isIntegerType()) 9611 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9612 << resultType << Input.get()->getSourceRange()); 9613 } 9614 break; 9615 } else { 9616 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9617 << resultType << Input.get()->getSourceRange()); 9618 } 9619 break; 9620 9621 case UO_LNot: // logical negation 9622 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 9623 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 9624 if (Input.isInvalid()) return ExprError(); 9625 resultType = Input.get()->getType(); 9626 9627 // Though we still have to promote half FP to float... 9628 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 9629 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take(); 9630 resultType = Context.FloatTy; 9631 } 9632 9633 if (resultType->isDependentType()) 9634 break; 9635 if (resultType->isScalarType()) { 9636 // C99 6.5.3.3p1: ok, fallthrough; 9637 if (Context.getLangOpts().CPlusPlus) { 9638 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 9639 // operand contextually converted to bool. 9640 Input = ImpCastExprToType(Input.take(), Context.BoolTy, 9641 ScalarTypeToBooleanCastKind(resultType)); 9642 } else if (Context.getLangOpts().OpenCL && 9643 Context.getLangOpts().OpenCLVersion < 120) { 9644 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 9645 // operate on scalar float types. 9646 if (!resultType->isIntegerType()) 9647 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9648 << resultType << Input.get()->getSourceRange()); 9649 } 9650 } else if (resultType->isExtVectorType()) { 9651 if (Context.getLangOpts().OpenCL && 9652 Context.getLangOpts().OpenCLVersion < 120) { 9653 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 9654 // operate on vector float types. 9655 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 9656 if (!T->isIntegerType()) 9657 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9658 << resultType << Input.get()->getSourceRange()); 9659 } 9660 // Vector logical not returns the signed variant of the operand type. 9661 resultType = GetSignedVectorType(resultType); 9662 break; 9663 } else { 9664 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9665 << resultType << Input.get()->getSourceRange()); 9666 } 9667 9668 // LNot always has type int. C99 6.5.3.3p5. 9669 // In C++, it's bool. C++ 5.3.1p8 9670 resultType = Context.getLogicalOperationType(); 9671 break; 9672 case UO_Real: 9673 case UO_Imag: 9674 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 9675 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 9676 // complex l-values to ordinary l-values and all other values to r-values. 9677 if (Input.isInvalid()) return ExprError(); 9678 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 9679 if (Input.get()->getValueKind() != VK_RValue && 9680 Input.get()->getObjectKind() == OK_Ordinary) 9681 VK = Input.get()->getValueKind(); 9682 } else if (!getLangOpts().CPlusPlus) { 9683 // In C, a volatile scalar is read by __imag. In C++, it is not. 9684 Input = DefaultLvalueConversion(Input.take()); 9685 } 9686 break; 9687 case UO_Extension: 9688 resultType = Input.get()->getType(); 9689 VK = Input.get()->getValueKind(); 9690 OK = Input.get()->getObjectKind(); 9691 break; 9692 } 9693 if (resultType.isNull() || Input.isInvalid()) 9694 return ExprError(); 9695 9696 // Check for array bounds violations in the operand of the UnaryOperator, 9697 // except for the '*' and '&' operators that have to be handled specially 9698 // by CheckArrayAccess (as there are special cases like &array[arraysize] 9699 // that are explicitly defined as valid by the standard). 9700 if (Opc != UO_AddrOf && Opc != UO_Deref) 9701 CheckArrayAccess(Input.get()); 9702 9703 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType, 9704 VK, OK, OpLoc)); 9705} 9706 9707/// \brief Determine whether the given expression is a qualified member 9708/// access expression, of a form that could be turned into a pointer to member 9709/// with the address-of operator. 9710static bool isQualifiedMemberAccess(Expr *E) { 9711 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9712 if (!DRE->getQualifier()) 9713 return false; 9714 9715 ValueDecl *VD = DRE->getDecl(); 9716 if (!VD->isCXXClassMember()) 9717 return false; 9718 9719 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 9720 return true; 9721 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 9722 return Method->isInstance(); 9723 9724 return false; 9725 } 9726 9727 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 9728 if (!ULE->getQualifier()) 9729 return false; 9730 9731 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(), 9732 DEnd = ULE->decls_end(); 9733 D != DEnd; ++D) { 9734 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) { 9735 if (Method->isInstance()) 9736 return true; 9737 } else { 9738 // Overload set does not contain methods. 9739 break; 9740 } 9741 } 9742 9743 return false; 9744 } 9745 9746 return false; 9747} 9748 9749ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 9750 UnaryOperatorKind Opc, Expr *Input) { 9751 // First things first: handle placeholders so that the 9752 // overloaded-operator check considers the right type. 9753 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 9754 // Increment and decrement of pseudo-object references. 9755 if (pty->getKind() == BuiltinType::PseudoObject && 9756 UnaryOperator::isIncrementDecrementOp(Opc)) 9757 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 9758 9759 // extension is always a builtin operator. 9760 if (Opc == UO_Extension) 9761 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9762 9763 // & gets special logic for several kinds of placeholder. 9764 // The builtin code knows what to do. 9765 if (Opc == UO_AddrOf && 9766 (pty->getKind() == BuiltinType::Overload || 9767 pty->getKind() == BuiltinType::UnknownAny || 9768 pty->getKind() == BuiltinType::BoundMember)) 9769 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9770 9771 // Anything else needs to be handled now. 9772 ExprResult Result = CheckPlaceholderExpr(Input); 9773 if (Result.isInvalid()) return ExprError(); 9774 Input = Result.take(); 9775 } 9776 9777 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 9778 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 9779 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 9780 // Find all of the overloaded operators visible from this 9781 // point. We perform both an operator-name lookup from the local 9782 // scope and an argument-dependent lookup based on the types of 9783 // the arguments. 9784 UnresolvedSet<16> Functions; 9785 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 9786 if (S && OverOp != OO_None) 9787 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 9788 Functions); 9789 9790 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 9791 } 9792 9793 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9794} 9795 9796// Unary Operators. 'Tok' is the token for the operator. 9797ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 9798 tok::TokenKind Op, Expr *Input) { 9799 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 9800} 9801 9802/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 9803ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 9804 LabelDecl *TheDecl) { 9805 TheDecl->markUsed(Context); 9806 // Create the AST node. The address of a label always has type 'void*'. 9807 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 9808 Context.getPointerType(Context.VoidTy))); 9809} 9810 9811/// Given the last statement in a statement-expression, check whether 9812/// the result is a producing expression (like a call to an 9813/// ns_returns_retained function) and, if so, rebuild it to hoist the 9814/// release out of the full-expression. Otherwise, return null. 9815/// Cannot fail. 9816static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 9817 // Should always be wrapped with one of these. 9818 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 9819 if (!cleanups) return 0; 9820 9821 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 9822 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 9823 return 0; 9824 9825 // Splice out the cast. This shouldn't modify any interesting 9826 // features of the statement. 9827 Expr *producer = cast->getSubExpr(); 9828 assert(producer->getType() == cast->getType()); 9829 assert(producer->getValueKind() == cast->getValueKind()); 9830 cleanups->setSubExpr(producer); 9831 return cleanups; 9832} 9833 9834void Sema::ActOnStartStmtExpr() { 9835 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 9836} 9837 9838void Sema::ActOnStmtExprError() { 9839 // Note that function is also called by TreeTransform when leaving a 9840 // StmtExpr scope without rebuilding anything. 9841 9842 DiscardCleanupsInEvaluationContext(); 9843 PopExpressionEvaluationContext(); 9844} 9845 9846ExprResult 9847Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 9848 SourceLocation RPLoc) { // "({..})" 9849 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 9850 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 9851 9852 if (hasAnyUnrecoverableErrorsInThisFunction()) 9853 DiscardCleanupsInEvaluationContext(); 9854 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!"); 9855 PopExpressionEvaluationContext(); 9856 9857 bool isFileScope 9858 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0); 9859 if (isFileScope) 9860 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope)); 9861 9862 // FIXME: there are a variety of strange constraints to enforce here, for 9863 // example, it is not possible to goto into a stmt expression apparently. 9864 // More semantic analysis is needed. 9865 9866 // If there are sub stmts in the compound stmt, take the type of the last one 9867 // as the type of the stmtexpr. 9868 QualType Ty = Context.VoidTy; 9869 bool StmtExprMayBindToTemp = false; 9870 if (!Compound->body_empty()) { 9871 Stmt *LastStmt = Compound->body_back(); 9872 LabelStmt *LastLabelStmt = 0; 9873 // If LastStmt is a label, skip down through into the body. 9874 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 9875 LastLabelStmt = Label; 9876 LastStmt = Label->getSubStmt(); 9877 } 9878 9879 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 9880 // Do function/array conversion on the last expression, but not 9881 // lvalue-to-rvalue. However, initialize an unqualified type. 9882 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 9883 if (LastExpr.isInvalid()) 9884 return ExprError(); 9885 Ty = LastExpr.get()->getType().getUnqualifiedType(); 9886 9887 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 9888 // In ARC, if the final expression ends in a consume, splice 9889 // the consume out and bind it later. In the alternate case 9890 // (when dealing with a retainable type), the result 9891 // initialization will create a produce. In both cases the 9892 // result will be +1, and we'll need to balance that out with 9893 // a bind. 9894 if (Expr *rebuiltLastStmt 9895 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 9896 LastExpr = rebuiltLastStmt; 9897 } else { 9898 LastExpr = PerformCopyInitialization( 9899 InitializedEntity::InitializeResult(LPLoc, 9900 Ty, 9901 false), 9902 SourceLocation(), 9903 LastExpr); 9904 } 9905 9906 if (LastExpr.isInvalid()) 9907 return ExprError(); 9908 if (LastExpr.get() != 0) { 9909 if (!LastLabelStmt) 9910 Compound->setLastStmt(LastExpr.take()); 9911 else 9912 LastLabelStmt->setSubStmt(LastExpr.take()); 9913 StmtExprMayBindToTemp = true; 9914 } 9915 } 9916 } 9917 } 9918 9919 // FIXME: Check that expression type is complete/non-abstract; statement 9920 // expressions are not lvalues. 9921 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 9922 if (StmtExprMayBindToTemp) 9923 return MaybeBindToTemporary(ResStmtExpr); 9924 return Owned(ResStmtExpr); 9925} 9926 9927ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 9928 TypeSourceInfo *TInfo, 9929 OffsetOfComponent *CompPtr, 9930 unsigned NumComponents, 9931 SourceLocation RParenLoc) { 9932 QualType ArgTy = TInfo->getType(); 9933 bool Dependent = ArgTy->isDependentType(); 9934 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 9935 9936 // We must have at least one component that refers to the type, and the first 9937 // one is known to be a field designator. Verify that the ArgTy represents 9938 // a struct/union/class. 9939 if (!Dependent && !ArgTy->isRecordType()) 9940 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 9941 << ArgTy << TypeRange); 9942 9943 // Type must be complete per C99 7.17p3 because a declaring a variable 9944 // with an incomplete type would be ill-formed. 9945 if (!Dependent 9946 && RequireCompleteType(BuiltinLoc, ArgTy, 9947 diag::err_offsetof_incomplete_type, TypeRange)) 9948 return ExprError(); 9949 9950 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 9951 // GCC extension, diagnose them. 9952 // FIXME: This diagnostic isn't actually visible because the location is in 9953 // a system header! 9954 if (NumComponents != 1) 9955 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 9956 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); 9957 9958 bool DidWarnAboutNonPOD = false; 9959 QualType CurrentType = ArgTy; 9960 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; 9961 SmallVector<OffsetOfNode, 4> Comps; 9962 SmallVector<Expr*, 4> Exprs; 9963 for (unsigned i = 0; i != NumComponents; ++i) { 9964 const OffsetOfComponent &OC = CompPtr[i]; 9965 if (OC.isBrackets) { 9966 // Offset of an array sub-field. TODO: Should we allow vector elements? 9967 if (!CurrentType->isDependentType()) { 9968 const ArrayType *AT = Context.getAsArrayType(CurrentType); 9969 if(!AT) 9970 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 9971 << CurrentType); 9972 CurrentType = AT->getElementType(); 9973 } else 9974 CurrentType = Context.DependentTy; 9975 9976 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 9977 if (IdxRval.isInvalid()) 9978 return ExprError(); 9979 Expr *Idx = IdxRval.take(); 9980 9981 // The expression must be an integral expression. 9982 // FIXME: An integral constant expression? 9983 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 9984 !Idx->getType()->isIntegerType()) 9985 return ExprError(Diag(Idx->getLocStart(), 9986 diag::err_typecheck_subscript_not_integer) 9987 << Idx->getSourceRange()); 9988 9989 // Record this array index. 9990 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 9991 Exprs.push_back(Idx); 9992 continue; 9993 } 9994 9995 // Offset of a field. 9996 if (CurrentType->isDependentType()) { 9997 // We have the offset of a field, but we can't look into the dependent 9998 // type. Just record the identifier of the field. 9999 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 10000 CurrentType = Context.DependentTy; 10001 continue; 10002 } 10003 10004 // We need to have a complete type to look into. 10005 if (RequireCompleteType(OC.LocStart, CurrentType, 10006 diag::err_offsetof_incomplete_type)) 10007 return ExprError(); 10008 10009 // Look for the designated field. 10010 const RecordType *RC = CurrentType->getAs<RecordType>(); 10011 if (!RC) 10012 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 10013 << CurrentType); 10014 RecordDecl *RD = RC->getDecl(); 10015 10016 // C++ [lib.support.types]p5: 10017 // The macro offsetof accepts a restricted set of type arguments in this 10018 // International Standard. type shall be a POD structure or a POD union 10019 // (clause 9). 10020 // C++11 [support.types]p4: 10021 // If type is not a standard-layout class (Clause 9), the results are 10022 // undefined. 10023 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 10024 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 10025 unsigned DiagID = 10026 LangOpts.CPlusPlus11? diag::warn_offsetof_non_standardlayout_type 10027 : diag::warn_offsetof_non_pod_type; 10028 10029 if (!IsSafe && !DidWarnAboutNonPOD && 10030 DiagRuntimeBehavior(BuiltinLoc, 0, 10031 PDiag(DiagID) 10032 << SourceRange(CompPtr[0].LocStart, OC.LocEnd) 10033 << CurrentType)) 10034 DidWarnAboutNonPOD = true; 10035 } 10036 10037 // Look for the field. 10038 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 10039 LookupQualifiedName(R, RD); 10040 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 10041 IndirectFieldDecl *IndirectMemberDecl = 0; 10042 if (!MemberDecl) { 10043 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 10044 MemberDecl = IndirectMemberDecl->getAnonField(); 10045 } 10046 10047 if (!MemberDecl) 10048 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 10049 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 10050 OC.LocEnd)); 10051 10052 // C99 7.17p3: 10053 // (If the specified member is a bit-field, the behavior is undefined.) 10054 // 10055 // We diagnose this as an error. 10056 if (MemberDecl->isBitField()) { 10057 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 10058 << MemberDecl->getDeclName() 10059 << SourceRange(BuiltinLoc, RParenLoc); 10060 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 10061 return ExprError(); 10062 } 10063 10064 RecordDecl *Parent = MemberDecl->getParent(); 10065 if (IndirectMemberDecl) 10066 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 10067 10068 // If the member was found in a base class, introduce OffsetOfNodes for 10069 // the base class indirections. 10070 CXXBasePaths Paths; 10071 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) { 10072 if (Paths.getDetectedVirtual()) { 10073 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 10074 << MemberDecl->getDeclName() 10075 << SourceRange(BuiltinLoc, RParenLoc); 10076 return ExprError(); 10077 } 10078 10079 CXXBasePath &Path = Paths.front(); 10080 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end(); 10081 B != BEnd; ++B) 10082 Comps.push_back(OffsetOfNode(B->Base)); 10083 } 10084 10085 if (IndirectMemberDecl) { 10086 for (IndirectFieldDecl::chain_iterator FI = 10087 IndirectMemberDecl->chain_begin(), 10088 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) { 10089 assert(isa<FieldDecl>(*FI)); 10090 Comps.push_back(OffsetOfNode(OC.LocStart, 10091 cast<FieldDecl>(*FI), OC.LocEnd)); 10092 } 10093 } else 10094 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 10095 10096 CurrentType = MemberDecl->getType().getNonReferenceType(); 10097 } 10098 10099 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, 10100 TInfo, Comps, Exprs, RParenLoc)); 10101} 10102 10103ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 10104 SourceLocation BuiltinLoc, 10105 SourceLocation TypeLoc, 10106 ParsedType ParsedArgTy, 10107 OffsetOfComponent *CompPtr, 10108 unsigned NumComponents, 10109 SourceLocation RParenLoc) { 10110 10111 TypeSourceInfo *ArgTInfo; 10112 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 10113 if (ArgTy.isNull()) 10114 return ExprError(); 10115 10116 if (!ArgTInfo) 10117 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 10118 10119 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents, 10120 RParenLoc); 10121} 10122 10123 10124ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 10125 Expr *CondExpr, 10126 Expr *LHSExpr, Expr *RHSExpr, 10127 SourceLocation RPLoc) { 10128 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 10129 10130 ExprValueKind VK = VK_RValue; 10131 ExprObjectKind OK = OK_Ordinary; 10132 QualType resType; 10133 bool ValueDependent = false; 10134 bool CondIsTrue = false; 10135 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 10136 resType = Context.DependentTy; 10137 ValueDependent = true; 10138 } else { 10139 // The conditional expression is required to be a constant expression. 10140 llvm::APSInt condEval(32); 10141 ExprResult CondICE 10142 = VerifyIntegerConstantExpression(CondExpr, &condEval, 10143 diag::err_typecheck_choose_expr_requires_constant, false); 10144 if (CondICE.isInvalid()) 10145 return ExprError(); 10146 CondExpr = CondICE.take(); 10147 CondIsTrue = condEval.getZExtValue(); 10148 10149 // If the condition is > zero, then the AST type is the same as the LSHExpr. 10150 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 10151 10152 resType = ActiveExpr->getType(); 10153 ValueDependent = ActiveExpr->isValueDependent(); 10154 VK = ActiveExpr->getValueKind(); 10155 OK = ActiveExpr->getObjectKind(); 10156 } 10157 10158 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 10159 resType, VK, OK, RPLoc, CondIsTrue, 10160 resType->isDependentType(), 10161 ValueDependent)); 10162} 10163 10164//===----------------------------------------------------------------------===// 10165// Clang Extensions. 10166//===----------------------------------------------------------------------===// 10167 10168/// ActOnBlockStart - This callback is invoked when a block literal is started. 10169void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 10170 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 10171 10172 if (LangOpts.CPlusPlus) { 10173 Decl *ManglingContextDecl; 10174 if (MangleNumberingContext *MCtx = 10175 getCurrentMangleNumberContext(Block->getDeclContext(), 10176 ManglingContextDecl)) { 10177 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 10178 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 10179 } 10180 } 10181 10182 PushBlockScope(CurScope, Block); 10183 CurContext->addDecl(Block); 10184 if (CurScope) 10185 PushDeclContext(CurScope, Block); 10186 else 10187 CurContext = Block; 10188 10189 getCurBlock()->HasImplicitReturnType = true; 10190 10191 // Enter a new evaluation context to insulate the block from any 10192 // cleanups from the enclosing full-expression. 10193 PushExpressionEvaluationContext(PotentiallyEvaluated); 10194} 10195 10196void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 10197 Scope *CurScope) { 10198 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!"); 10199 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 10200 BlockScopeInfo *CurBlock = getCurBlock(); 10201 10202 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 10203 QualType T = Sig->getType(); 10204 10205 // FIXME: We should allow unexpanded parameter packs here, but that would, 10206 // in turn, make the block expression contain unexpanded parameter packs. 10207 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 10208 // Drop the parameters. 10209 FunctionProtoType::ExtProtoInfo EPI; 10210 EPI.HasTrailingReturn = false; 10211 EPI.TypeQuals |= DeclSpec::TQ_const; 10212 T = Context.getFunctionType(Context.DependentTy, None, EPI); 10213 Sig = Context.getTrivialTypeSourceInfo(T); 10214 } 10215 10216 // GetTypeForDeclarator always produces a function type for a block 10217 // literal signature. Furthermore, it is always a FunctionProtoType 10218 // unless the function was written with a typedef. 10219 assert(T->isFunctionType() && 10220 "GetTypeForDeclarator made a non-function block signature"); 10221 10222 // Look for an explicit signature in that function type. 10223 FunctionProtoTypeLoc ExplicitSignature; 10224 10225 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 10226 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 10227 10228 // Check whether that explicit signature was synthesized by 10229 // GetTypeForDeclarator. If so, don't save that as part of the 10230 // written signature. 10231 if (ExplicitSignature.getLocalRangeBegin() == 10232 ExplicitSignature.getLocalRangeEnd()) { 10233 // This would be much cheaper if we stored TypeLocs instead of 10234 // TypeSourceInfos. 10235 TypeLoc Result = ExplicitSignature.getResultLoc(); 10236 unsigned Size = Result.getFullDataSize(); 10237 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 10238 Sig->getTypeLoc().initializeFullCopy(Result, Size); 10239 10240 ExplicitSignature = FunctionProtoTypeLoc(); 10241 } 10242 } 10243 10244 CurBlock->TheDecl->setSignatureAsWritten(Sig); 10245 CurBlock->FunctionType = T; 10246 10247 const FunctionType *Fn = T->getAs<FunctionType>(); 10248 QualType RetTy = Fn->getResultType(); 10249 bool isVariadic = 10250 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 10251 10252 CurBlock->TheDecl->setIsVariadic(isVariadic); 10253 10254 // Context.DependentTy is used as a placeholder for a missing block 10255 // return type. TODO: what should we do with declarators like: 10256 // ^ * { ... } 10257 // If the answer is "apply template argument deduction".... 10258 if (RetTy != Context.DependentTy) { 10259 CurBlock->ReturnType = RetTy; 10260 CurBlock->TheDecl->setBlockMissingReturnType(false); 10261 CurBlock->HasImplicitReturnType = false; 10262 } 10263 10264 // Push block parameters from the declarator if we had them. 10265 SmallVector<ParmVarDecl*, 8> Params; 10266 if (ExplicitSignature) { 10267 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) { 10268 ParmVarDecl *Param = ExplicitSignature.getArg(I); 10269 if (Param->getIdentifier() == 0 && 10270 !Param->isImplicit() && 10271 !Param->isInvalidDecl() && 10272 !getLangOpts().CPlusPlus) 10273 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 10274 Params.push_back(Param); 10275 } 10276 10277 // Fake up parameter variables if we have a typedef, like 10278 // ^ fntype { ... } 10279 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 10280 for (FunctionProtoType::arg_type_iterator 10281 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) { 10282 ParmVarDecl *Param = 10283 BuildParmVarDeclForTypedef(CurBlock->TheDecl, 10284 ParamInfo.getLocStart(), 10285 *I); 10286 Params.push_back(Param); 10287 } 10288 } 10289 10290 // Set the parameters on the block decl. 10291 if (!Params.empty()) { 10292 CurBlock->TheDecl->setParams(Params); 10293 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(), 10294 CurBlock->TheDecl->param_end(), 10295 /*CheckParameterNames=*/false); 10296 } 10297 10298 // Finally we can process decl attributes. 10299 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 10300 10301 // Put the parameter variables in scope. 10302 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(), 10303 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) { 10304 (*AI)->setOwningFunction(CurBlock->TheDecl); 10305 10306 // If this has an identifier, add it to the scope stack. 10307 if ((*AI)->getIdentifier()) { 10308 CheckShadow(CurBlock->TheScope, *AI); 10309 10310 PushOnScopeChains(*AI, CurBlock->TheScope); 10311 } 10312 } 10313} 10314 10315/// ActOnBlockError - If there is an error parsing a block, this callback 10316/// is invoked to pop the information about the block from the action impl. 10317void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 10318 // Leave the expression-evaluation context. 10319 DiscardCleanupsInEvaluationContext(); 10320 PopExpressionEvaluationContext(); 10321 10322 // Pop off CurBlock, handle nested blocks. 10323 PopDeclContext(); 10324 PopFunctionScopeInfo(); 10325} 10326 10327/// ActOnBlockStmtExpr - This is called when the body of a block statement 10328/// literal was successfully completed. ^(int x){...} 10329ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 10330 Stmt *Body, Scope *CurScope) { 10331 // If blocks are disabled, emit an error. 10332 if (!LangOpts.Blocks) 10333 Diag(CaretLoc, diag::err_blocks_disable); 10334 10335 // Leave the expression-evaluation context. 10336 if (hasAnyUnrecoverableErrorsInThisFunction()) 10337 DiscardCleanupsInEvaluationContext(); 10338 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!"); 10339 PopExpressionEvaluationContext(); 10340 10341 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 10342 10343 if (BSI->HasImplicitReturnType) 10344 deduceClosureReturnType(*BSI); 10345 10346 PopDeclContext(); 10347 10348 QualType RetTy = Context.VoidTy; 10349 if (!BSI->ReturnType.isNull()) 10350 RetTy = BSI->ReturnType; 10351 10352 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>(); 10353 QualType BlockTy; 10354 10355 // Set the captured variables on the block. 10356 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 10357 SmallVector<BlockDecl::Capture, 4> Captures; 10358 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) { 10359 CapturingScopeInfo::Capture &Cap = BSI->Captures[i]; 10360 if (Cap.isThisCapture()) 10361 continue; 10362 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 10363 Cap.isNested(), Cap.getInitExpr()); 10364 Captures.push_back(NewCap); 10365 } 10366 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(), 10367 BSI->CXXThisCaptureIndex != 0); 10368 10369 // If the user wrote a function type in some form, try to use that. 10370 if (!BSI->FunctionType.isNull()) { 10371 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 10372 10373 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 10374 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 10375 10376 // Turn protoless block types into nullary block types. 10377 if (isa<FunctionNoProtoType>(FTy)) { 10378 FunctionProtoType::ExtProtoInfo EPI; 10379 EPI.ExtInfo = Ext; 10380 BlockTy = Context.getFunctionType(RetTy, None, EPI); 10381 10382 // Otherwise, if we don't need to change anything about the function type, 10383 // preserve its sugar structure. 10384 } else if (FTy->getResultType() == RetTy && 10385 (!NoReturn || FTy->getNoReturnAttr())) { 10386 BlockTy = BSI->FunctionType; 10387 10388 // Otherwise, make the minimal modifications to the function type. 10389 } else { 10390 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 10391 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10392 EPI.TypeQuals = 0; // FIXME: silently? 10393 EPI.ExtInfo = Ext; 10394 BlockTy = Context.getFunctionType(RetTy, FPT->getArgTypes(), EPI); 10395 } 10396 10397 // If we don't have a function type, just build one from nothing. 10398 } else { 10399 FunctionProtoType::ExtProtoInfo EPI; 10400 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 10401 BlockTy = Context.getFunctionType(RetTy, None, EPI); 10402 } 10403 10404 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(), 10405 BSI->TheDecl->param_end()); 10406 BlockTy = Context.getBlockPointerType(BlockTy); 10407 10408 // If needed, diagnose invalid gotos and switches in the block. 10409 if (getCurFunction()->NeedsScopeChecking() && 10410 !hasAnyUnrecoverableErrorsInThisFunction() && 10411 !PP.isCodeCompletionEnabled()) 10412 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 10413 10414 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 10415 10416 // Try to apply the named return value optimization. We have to check again 10417 // if we can do this, though, because blocks keep return statements around 10418 // to deduce an implicit return type. 10419 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 10420 !BSI->TheDecl->isDependentContext()) 10421 computeNRVO(Body, getCurBlock()); 10422 10423 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 10424 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 10425 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 10426 10427 // If the block isn't obviously global, i.e. it captures anything at 10428 // all, then we need to do a few things in the surrounding context: 10429 if (Result->getBlockDecl()->hasCaptures()) { 10430 // First, this expression has a new cleanup object. 10431 ExprCleanupObjects.push_back(Result->getBlockDecl()); 10432 ExprNeedsCleanups = true; 10433 10434 // It also gets a branch-protected scope if any of the captured 10435 // variables needs destruction. 10436 for (BlockDecl::capture_const_iterator 10437 ci = Result->getBlockDecl()->capture_begin(), 10438 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) { 10439 const VarDecl *var = ci->getVariable(); 10440 if (var->getType().isDestructedType() != QualType::DK_none) { 10441 getCurFunction()->setHasBranchProtectedScope(); 10442 break; 10443 } 10444 } 10445 } 10446 10447 return Owned(Result); 10448} 10449 10450ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 10451 Expr *E, ParsedType Ty, 10452 SourceLocation RPLoc) { 10453 TypeSourceInfo *TInfo; 10454 GetTypeFromParser(Ty, &TInfo); 10455 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 10456} 10457 10458ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 10459 Expr *E, TypeSourceInfo *TInfo, 10460 SourceLocation RPLoc) { 10461 Expr *OrigExpr = E; 10462 10463 // Get the va_list type 10464 QualType VaListType = Context.getBuiltinVaListType(); 10465 if (VaListType->isArrayType()) { 10466 // Deal with implicit array decay; for example, on x86-64, 10467 // va_list is an array, but it's supposed to decay to 10468 // a pointer for va_arg. 10469 VaListType = Context.getArrayDecayedType(VaListType); 10470 // Make sure the input expression also decays appropriately. 10471 ExprResult Result = UsualUnaryConversions(E); 10472 if (Result.isInvalid()) 10473 return ExprError(); 10474 E = Result.take(); 10475 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 10476 // If va_list is a record type and we are compiling in C++ mode, 10477 // check the argument using reference binding. 10478 InitializedEntity Entity 10479 = InitializedEntity::InitializeParameter(Context, 10480 Context.getLValueReferenceType(VaListType), false); 10481 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 10482 if (Init.isInvalid()) 10483 return ExprError(); 10484 E = Init.takeAs<Expr>(); 10485 } else { 10486 // Otherwise, the va_list argument must be an l-value because 10487 // it is modified by va_arg. 10488 if (!E->isTypeDependent() && 10489 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 10490 return ExprError(); 10491 } 10492 10493 if (!E->isTypeDependent() && 10494 !Context.hasSameType(VaListType, E->getType())) { 10495 return ExprError(Diag(E->getLocStart(), 10496 diag::err_first_argument_to_va_arg_not_of_type_va_list) 10497 << OrigExpr->getType() << E->getSourceRange()); 10498 } 10499 10500 if (!TInfo->getType()->isDependentType()) { 10501 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 10502 diag::err_second_parameter_to_va_arg_incomplete, 10503 TInfo->getTypeLoc())) 10504 return ExprError(); 10505 10506 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 10507 TInfo->getType(), 10508 diag::err_second_parameter_to_va_arg_abstract, 10509 TInfo->getTypeLoc())) 10510 return ExprError(); 10511 10512 if (!TInfo->getType().isPODType(Context)) { 10513 Diag(TInfo->getTypeLoc().getBeginLoc(), 10514 TInfo->getType()->isObjCLifetimeType() 10515 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 10516 : diag::warn_second_parameter_to_va_arg_not_pod) 10517 << TInfo->getType() 10518 << TInfo->getTypeLoc().getSourceRange(); 10519 } 10520 10521 // Check for va_arg where arguments of the given type will be promoted 10522 // (i.e. this va_arg is guaranteed to have undefined behavior). 10523 QualType PromoteType; 10524 if (TInfo->getType()->isPromotableIntegerType()) { 10525 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 10526 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 10527 PromoteType = QualType(); 10528 } 10529 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 10530 PromoteType = Context.DoubleTy; 10531 if (!PromoteType.isNull()) 10532 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 10533 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 10534 << TInfo->getType() 10535 << PromoteType 10536 << TInfo->getTypeLoc().getSourceRange()); 10537 } 10538 10539 QualType T = TInfo->getType().getNonLValueExprType(Context); 10540 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T)); 10541} 10542 10543ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 10544 // The type of __null will be int or long, depending on the size of 10545 // pointers on the target. 10546 QualType Ty; 10547 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 10548 if (pw == Context.getTargetInfo().getIntWidth()) 10549 Ty = Context.IntTy; 10550 else if (pw == Context.getTargetInfo().getLongWidth()) 10551 Ty = Context.LongTy; 10552 else if (pw == Context.getTargetInfo().getLongLongWidth()) 10553 Ty = Context.LongLongTy; 10554 else { 10555 llvm_unreachable("I don't know size of pointer!"); 10556 } 10557 10558 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc)); 10559} 10560 10561static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType, 10562 Expr *SrcExpr, FixItHint &Hint, 10563 bool &IsNSString) { 10564 if (!SemaRef.getLangOpts().ObjC1) 10565 return; 10566 10567 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 10568 if (!PT) 10569 return; 10570 10571 // Check if the destination is of type 'id'. 10572 if (!PT->isObjCIdType()) { 10573 // Check if the destination is the 'NSString' interface. 10574 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 10575 if (!ID || !ID->getIdentifier()->isStr("NSString")) 10576 return; 10577 IsNSString = true; 10578 } 10579 10580 // Ignore any parens, implicit casts (should only be 10581 // array-to-pointer decays), and not-so-opaque values. The last is 10582 // important for making this trigger for property assignments. 10583 SrcExpr = SrcExpr->IgnoreParenImpCasts(); 10584 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 10585 if (OV->getSourceExpr()) 10586 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 10587 10588 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 10589 if (!SL || !SL->isAscii()) 10590 return; 10591 10592 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@"); 10593} 10594 10595bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 10596 SourceLocation Loc, 10597 QualType DstType, QualType SrcType, 10598 Expr *SrcExpr, AssignmentAction Action, 10599 bool *Complained) { 10600 if (Complained) 10601 *Complained = false; 10602 10603 // Decode the result (notice that AST's are still created for extensions). 10604 bool CheckInferredResultType = false; 10605 bool isInvalid = false; 10606 unsigned DiagKind = 0; 10607 FixItHint Hint; 10608 ConversionFixItGenerator ConvHints; 10609 bool MayHaveConvFixit = false; 10610 bool MayHaveFunctionDiff = false; 10611 bool IsNSString = false; 10612 10613 switch (ConvTy) { 10614 case Compatible: 10615 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 10616 return false; 10617 10618 case PointerToInt: 10619 DiagKind = diag::ext_typecheck_convert_pointer_int; 10620 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10621 MayHaveConvFixit = true; 10622 break; 10623 case IntToPointer: 10624 DiagKind = diag::ext_typecheck_convert_int_pointer; 10625 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10626 MayHaveConvFixit = true; 10627 break; 10628 case IncompatiblePointer: 10629 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint, IsNSString); 10630 DiagKind = 10631 (Action == AA_Passing_CFAudited ? 10632 diag::err_arc_typecheck_convert_incompatible_pointer : 10633 diag::ext_typecheck_convert_incompatible_pointer); 10634 CheckInferredResultType = DstType->isObjCObjectPointerType() && 10635 SrcType->isObjCObjectPointerType(); 10636 if (Hint.isNull() && !CheckInferredResultType) { 10637 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10638 } 10639 else if (CheckInferredResultType) { 10640 SrcType = SrcType.getUnqualifiedType(); 10641 DstType = DstType.getUnqualifiedType(); 10642 } 10643 else if (IsNSString && !Hint.isNull()) 10644 DiagKind = diag::warn_missing_atsign_prefix; 10645 MayHaveConvFixit = true; 10646 break; 10647 case IncompatiblePointerSign: 10648 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 10649 break; 10650 case FunctionVoidPointer: 10651 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 10652 break; 10653 case IncompatiblePointerDiscardsQualifiers: { 10654 // Perform array-to-pointer decay if necessary. 10655 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 10656 10657 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 10658 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 10659 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 10660 DiagKind = diag::err_typecheck_incompatible_address_space; 10661 break; 10662 10663 10664 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 10665 DiagKind = diag::err_typecheck_incompatible_ownership; 10666 break; 10667 } 10668 10669 llvm_unreachable("unknown error case for discarding qualifiers!"); 10670 // fallthrough 10671 } 10672 case CompatiblePointerDiscardsQualifiers: 10673 // If the qualifiers lost were because we were applying the 10674 // (deprecated) C++ conversion from a string literal to a char* 10675 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 10676 // Ideally, this check would be performed in 10677 // checkPointerTypesForAssignment. However, that would require a 10678 // bit of refactoring (so that the second argument is an 10679 // expression, rather than a type), which should be done as part 10680 // of a larger effort to fix checkPointerTypesForAssignment for 10681 // C++ semantics. 10682 if (getLangOpts().CPlusPlus && 10683 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 10684 return false; 10685 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 10686 break; 10687 case IncompatibleNestedPointerQualifiers: 10688 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 10689 break; 10690 case IntToBlockPointer: 10691 DiagKind = diag::err_int_to_block_pointer; 10692 break; 10693 case IncompatibleBlockPointer: 10694 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 10695 break; 10696 case IncompatibleObjCQualifiedId: 10697 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since 10698 // it can give a more specific diagnostic. 10699 DiagKind = diag::warn_incompatible_qualified_id; 10700 break; 10701 case IncompatibleVectors: 10702 DiagKind = diag::warn_incompatible_vectors; 10703 break; 10704 case IncompatibleObjCWeakRef: 10705 DiagKind = diag::err_arc_weak_unavailable_assign; 10706 break; 10707 case Incompatible: 10708 DiagKind = diag::err_typecheck_convert_incompatible; 10709 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10710 MayHaveConvFixit = true; 10711 isInvalid = true; 10712 MayHaveFunctionDiff = true; 10713 break; 10714 } 10715 10716 QualType FirstType, SecondType; 10717 switch (Action) { 10718 case AA_Assigning: 10719 case AA_Initializing: 10720 // The destination type comes first. 10721 FirstType = DstType; 10722 SecondType = SrcType; 10723 break; 10724 10725 case AA_Returning: 10726 case AA_Passing: 10727 case AA_Passing_CFAudited: 10728 case AA_Converting: 10729 case AA_Sending: 10730 case AA_Casting: 10731 // The source type comes first. 10732 FirstType = SrcType; 10733 SecondType = DstType; 10734 break; 10735 } 10736 10737 PartialDiagnostic FDiag = PDiag(DiagKind); 10738 if (Action == AA_Passing_CFAudited) 10739 FDiag << FirstType << SecondType << SrcExpr->getSourceRange(); 10740 else 10741 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 10742 10743 // If we can fix the conversion, suggest the FixIts. 10744 assert(ConvHints.isNull() || Hint.isNull()); 10745 if (!ConvHints.isNull()) { 10746 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(), 10747 HE = ConvHints.Hints.end(); HI != HE; ++HI) 10748 FDiag << *HI; 10749 } else { 10750 FDiag << Hint; 10751 } 10752 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 10753 10754 if (MayHaveFunctionDiff) 10755 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 10756 10757 Diag(Loc, FDiag); 10758 10759 if (SecondType == Context.OverloadTy) 10760 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 10761 FirstType); 10762 10763 if (CheckInferredResultType) 10764 EmitRelatedResultTypeNote(SrcExpr); 10765 10766 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 10767 EmitRelatedResultTypeNoteForReturn(DstType); 10768 10769 if (Complained) 10770 *Complained = true; 10771 return isInvalid; 10772} 10773 10774ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 10775 llvm::APSInt *Result) { 10776 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 10777 public: 10778 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 10779 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 10780 } 10781 } Diagnoser; 10782 10783 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 10784} 10785 10786ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 10787 llvm::APSInt *Result, 10788 unsigned DiagID, 10789 bool AllowFold) { 10790 class IDDiagnoser : public VerifyICEDiagnoser { 10791 unsigned DiagID; 10792 10793 public: 10794 IDDiagnoser(unsigned DiagID) 10795 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 10796 10797 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 10798 S.Diag(Loc, DiagID) << SR; 10799 } 10800 } Diagnoser(DiagID); 10801 10802 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 10803} 10804 10805void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 10806 SourceRange SR) { 10807 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 10808} 10809 10810ExprResult 10811Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 10812 VerifyICEDiagnoser &Diagnoser, 10813 bool AllowFold) { 10814 SourceLocation DiagLoc = E->getLocStart(); 10815 10816 if (getLangOpts().CPlusPlus11) { 10817 // C++11 [expr.const]p5: 10818 // If an expression of literal class type is used in a context where an 10819 // integral constant expression is required, then that class type shall 10820 // have a single non-explicit conversion function to an integral or 10821 // unscoped enumeration type 10822 ExprResult Converted; 10823 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 10824 public: 10825 CXX11ConvertDiagnoser(bool Silent) 10826 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 10827 Silent, true) {} 10828 10829 virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 10830 QualType T) { 10831 return S.Diag(Loc, diag::err_ice_not_integral) << T; 10832 } 10833 10834 virtual SemaDiagnosticBuilder diagnoseIncomplete( 10835 Sema &S, SourceLocation Loc, QualType T) { 10836 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 10837 } 10838 10839 virtual SemaDiagnosticBuilder diagnoseExplicitConv( 10840 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) { 10841 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 10842 } 10843 10844 virtual SemaDiagnosticBuilder noteExplicitConv( 10845 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) { 10846 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 10847 << ConvTy->isEnumeralType() << ConvTy; 10848 } 10849 10850 virtual SemaDiagnosticBuilder diagnoseAmbiguous( 10851 Sema &S, SourceLocation Loc, QualType T) { 10852 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 10853 } 10854 10855 virtual SemaDiagnosticBuilder noteAmbiguous( 10856 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) { 10857 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 10858 << ConvTy->isEnumeralType() << ConvTy; 10859 } 10860 10861 virtual SemaDiagnosticBuilder diagnoseConversion( 10862 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) { 10863 llvm_unreachable("conversion functions are permitted"); 10864 } 10865 } ConvertDiagnoser(Diagnoser.Suppress); 10866 10867 Converted = PerformContextualImplicitConversion(DiagLoc, E, 10868 ConvertDiagnoser); 10869 if (Converted.isInvalid()) 10870 return Converted; 10871 E = Converted.take(); 10872 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 10873 return ExprError(); 10874 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 10875 // An ICE must be of integral or unscoped enumeration type. 10876 if (!Diagnoser.Suppress) 10877 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 10878 return ExprError(); 10879 } 10880 10881 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 10882 // in the non-ICE case. 10883 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 10884 if (Result) 10885 *Result = E->EvaluateKnownConstInt(Context); 10886 return Owned(E); 10887 } 10888 10889 Expr::EvalResult EvalResult; 10890 SmallVector<PartialDiagnosticAt, 8> Notes; 10891 EvalResult.Diag = &Notes; 10892 10893 // Try to evaluate the expression, and produce diagnostics explaining why it's 10894 // not a constant expression as a side-effect. 10895 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 10896 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 10897 10898 // In C++11, we can rely on diagnostics being produced for any expression 10899 // which is not a constant expression. If no diagnostics were produced, then 10900 // this is a constant expression. 10901 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 10902 if (Result) 10903 *Result = EvalResult.Val.getInt(); 10904 return Owned(E); 10905 } 10906 10907 // If our only note is the usual "invalid subexpression" note, just point 10908 // the caret at its location rather than producing an essentially 10909 // redundant note. 10910 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 10911 diag::note_invalid_subexpr_in_const_expr) { 10912 DiagLoc = Notes[0].first; 10913 Notes.clear(); 10914 } 10915 10916 if (!Folded || !AllowFold) { 10917 if (!Diagnoser.Suppress) { 10918 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 10919 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 10920 Diag(Notes[I].first, Notes[I].second); 10921 } 10922 10923 return ExprError(); 10924 } 10925 10926 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 10927 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 10928 Diag(Notes[I].first, Notes[I].second); 10929 10930 if (Result) 10931 *Result = EvalResult.Val.getInt(); 10932 return Owned(E); 10933} 10934 10935namespace { 10936 // Handle the case where we conclude a expression which we speculatively 10937 // considered to be unevaluated is actually evaluated. 10938 class TransformToPE : public TreeTransform<TransformToPE> { 10939 typedef TreeTransform<TransformToPE> BaseTransform; 10940 10941 public: 10942 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 10943 10944 // Make sure we redo semantic analysis 10945 bool AlwaysRebuild() { return true; } 10946 10947 // Make sure we handle LabelStmts correctly. 10948 // FIXME: This does the right thing, but maybe we need a more general 10949 // fix to TreeTransform? 10950 StmtResult TransformLabelStmt(LabelStmt *S) { 10951 S->getDecl()->setStmt(0); 10952 return BaseTransform::TransformLabelStmt(S); 10953 } 10954 10955 // We need to special-case DeclRefExprs referring to FieldDecls which 10956 // are not part of a member pointer formation; normal TreeTransforming 10957 // doesn't catch this case because of the way we represent them in the AST. 10958 // FIXME: This is a bit ugly; is it really the best way to handle this 10959 // case? 10960 // 10961 // Error on DeclRefExprs referring to FieldDecls. 10962 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 10963 if (isa<FieldDecl>(E->getDecl()) && 10964 !SemaRef.isUnevaluatedContext()) 10965 return SemaRef.Diag(E->getLocation(), 10966 diag::err_invalid_non_static_member_use) 10967 << E->getDecl() << E->getSourceRange(); 10968 10969 return BaseTransform::TransformDeclRefExpr(E); 10970 } 10971 10972 // Exception: filter out member pointer formation 10973 ExprResult TransformUnaryOperator(UnaryOperator *E) { 10974 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 10975 return E; 10976 10977 return BaseTransform::TransformUnaryOperator(E); 10978 } 10979 10980 ExprResult TransformLambdaExpr(LambdaExpr *E) { 10981 // Lambdas never need to be transformed. 10982 return E; 10983 } 10984 }; 10985} 10986 10987ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 10988 assert(isUnevaluatedContext() && 10989 "Should only transform unevaluated expressions"); 10990 ExprEvalContexts.back().Context = 10991 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 10992 if (isUnevaluatedContext()) 10993 return E; 10994 return TransformToPE(*this).TransformExpr(E); 10995} 10996 10997void 10998Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 10999 Decl *LambdaContextDecl, 11000 bool IsDecltype) { 11001 ExprEvalContexts.push_back( 11002 ExpressionEvaluationContextRecord(NewContext, 11003 ExprCleanupObjects.size(), 11004 ExprNeedsCleanups, 11005 LambdaContextDecl, 11006 IsDecltype)); 11007 ExprNeedsCleanups = false; 11008 if (!MaybeODRUseExprs.empty()) 11009 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 11010} 11011 11012void 11013Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 11014 ReuseLambdaContextDecl_t, 11015 bool IsDecltype) { 11016 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 11017 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 11018} 11019 11020void Sema::PopExpressionEvaluationContext() { 11021 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 11022 11023 if (!Rec.Lambdas.empty()) { 11024 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 11025 unsigned D; 11026 if (Rec.isUnevaluated()) { 11027 // C++11 [expr.prim.lambda]p2: 11028 // A lambda-expression shall not appear in an unevaluated operand 11029 // (Clause 5). 11030 D = diag::err_lambda_unevaluated_operand; 11031 } else { 11032 // C++1y [expr.const]p2: 11033 // A conditional-expression e is a core constant expression unless the 11034 // evaluation of e, following the rules of the abstract machine, would 11035 // evaluate [...] a lambda-expression. 11036 D = diag::err_lambda_in_constant_expression; 11037 } 11038 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) 11039 Diag(Rec.Lambdas[I]->getLocStart(), D); 11040 } else { 11041 // Mark the capture expressions odr-used. This was deferred 11042 // during lambda expression creation. 11043 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) { 11044 LambdaExpr *Lambda = Rec.Lambdas[I]; 11045 for (LambdaExpr::capture_init_iterator 11046 C = Lambda->capture_init_begin(), 11047 CEnd = Lambda->capture_init_end(); 11048 C != CEnd; ++C) { 11049 MarkDeclarationsReferencedInExpr(*C); 11050 } 11051 } 11052 } 11053 } 11054 11055 // When are coming out of an unevaluated context, clear out any 11056 // temporaries that we may have created as part of the evaluation of 11057 // the expression in that context: they aren't relevant because they 11058 // will never be constructed. 11059 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 11060 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 11061 ExprCleanupObjects.end()); 11062 ExprNeedsCleanups = Rec.ParentNeedsCleanups; 11063 CleanupVarDeclMarking(); 11064 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 11065 // Otherwise, merge the contexts together. 11066 } else { 11067 ExprNeedsCleanups |= Rec.ParentNeedsCleanups; 11068 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 11069 Rec.SavedMaybeODRUseExprs.end()); 11070 } 11071 11072 // Pop the current expression evaluation context off the stack. 11073 ExprEvalContexts.pop_back(); 11074} 11075 11076void Sema::DiscardCleanupsInEvaluationContext() { 11077 ExprCleanupObjects.erase( 11078 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 11079 ExprCleanupObjects.end()); 11080 ExprNeedsCleanups = false; 11081 MaybeODRUseExprs.clear(); 11082} 11083 11084ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 11085 if (!E->getType()->isVariablyModifiedType()) 11086 return E; 11087 return TransformToPotentiallyEvaluated(E); 11088} 11089 11090static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 11091 // Do not mark anything as "used" within a dependent context; wait for 11092 // an instantiation. 11093 if (SemaRef.CurContext->isDependentContext()) 11094 return false; 11095 11096 switch (SemaRef.ExprEvalContexts.back().Context) { 11097 case Sema::Unevaluated: 11098 case Sema::UnevaluatedAbstract: 11099 // We are in an expression that is not potentially evaluated; do nothing. 11100 // (Depending on how you read the standard, we actually do need to do 11101 // something here for null pointer constants, but the standard's 11102 // definition of a null pointer constant is completely crazy.) 11103 return false; 11104 11105 case Sema::ConstantEvaluated: 11106 case Sema::PotentiallyEvaluated: 11107 // We are in a potentially evaluated expression (or a constant-expression 11108 // in C++03); we need to do implicit template instantiation, implicitly 11109 // define class members, and mark most declarations as used. 11110 return true; 11111 11112 case Sema::PotentiallyEvaluatedIfUsed: 11113 // Referenced declarations will only be used if the construct in the 11114 // containing expression is used. 11115 return false; 11116 } 11117 llvm_unreachable("Invalid context"); 11118} 11119 11120/// \brief Mark a function referenced, and check whether it is odr-used 11121/// (C++ [basic.def.odr]p2, C99 6.9p3) 11122void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) { 11123 assert(Func && "No function?"); 11124 11125 Func->setReferenced(); 11126 11127 // C++11 [basic.def.odr]p3: 11128 // A function whose name appears as a potentially-evaluated expression is 11129 // odr-used if it is the unique lookup result or the selected member of a 11130 // set of overloaded functions [...]. 11131 // 11132 // We (incorrectly) mark overload resolution as an unevaluated context, so we 11133 // can just check that here. Skip the rest of this function if we've already 11134 // marked the function as used. 11135 if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) { 11136 // C++11 [temp.inst]p3: 11137 // Unless a function template specialization has been explicitly 11138 // instantiated or explicitly specialized, the function template 11139 // specialization is implicitly instantiated when the specialization is 11140 // referenced in a context that requires a function definition to exist. 11141 // 11142 // We consider constexpr function templates to be referenced in a context 11143 // that requires a definition to exist whenever they are referenced. 11144 // 11145 // FIXME: This instantiates constexpr functions too frequently. If this is 11146 // really an unevaluated context (and we're not just in the definition of a 11147 // function template or overload resolution or other cases which we 11148 // incorrectly consider to be unevaluated contexts), and we're not in a 11149 // subexpression which we actually need to evaluate (for instance, a 11150 // template argument, array bound or an expression in a braced-init-list), 11151 // we are not permitted to instantiate this constexpr function definition. 11152 // 11153 // FIXME: This also implicitly defines special members too frequently. They 11154 // are only supposed to be implicitly defined if they are odr-used, but they 11155 // are not odr-used from constant expressions in unevaluated contexts. 11156 // However, they cannot be referenced if they are deleted, and they are 11157 // deleted whenever the implicit definition of the special member would 11158 // fail. 11159 if (!Func->isConstexpr() || Func->getBody()) 11160 return; 11161 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 11162 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided())) 11163 return; 11164 } 11165 11166 // Note that this declaration has been used. 11167 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 11168 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 11169 if (Constructor->isDefaultConstructor()) { 11170 if (Constructor->isTrivial()) 11171 return; 11172 if (!Constructor->isUsed(false)) 11173 DefineImplicitDefaultConstructor(Loc, Constructor); 11174 } else if (Constructor->isCopyConstructor()) { 11175 if (!Constructor->isUsed(false)) 11176 DefineImplicitCopyConstructor(Loc, Constructor); 11177 } else if (Constructor->isMoveConstructor()) { 11178 if (!Constructor->isUsed(false)) 11179 DefineImplicitMoveConstructor(Loc, Constructor); 11180 } 11181 } else if (Constructor->getInheritedConstructor()) { 11182 if (!Constructor->isUsed(false)) 11183 DefineInheritingConstructor(Loc, Constructor); 11184 } 11185 11186 MarkVTableUsed(Loc, Constructor->getParent()); 11187 } else if (CXXDestructorDecl *Destructor = 11188 dyn_cast<CXXDestructorDecl>(Func)) { 11189 if (Destructor->isDefaulted() && !Destructor->isDeleted() && 11190 !Destructor->isUsed(false)) 11191 DefineImplicitDestructor(Loc, Destructor); 11192 if (Destructor->isVirtual()) 11193 MarkVTableUsed(Loc, Destructor->getParent()); 11194 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 11195 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() && 11196 MethodDecl->isOverloadedOperator() && 11197 MethodDecl->getOverloadedOperator() == OO_Equal) { 11198 if (!MethodDecl->isUsed(false)) { 11199 if (MethodDecl->isCopyAssignmentOperator()) 11200 DefineImplicitCopyAssignment(Loc, MethodDecl); 11201 else 11202 DefineImplicitMoveAssignment(Loc, MethodDecl); 11203 } 11204 } else if (isa<CXXConversionDecl>(MethodDecl) && 11205 MethodDecl->getParent()->isLambda()) { 11206 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl); 11207 if (Conversion->isLambdaToBlockPointerConversion()) 11208 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 11209 else 11210 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 11211 } else if (MethodDecl->isVirtual()) 11212 MarkVTableUsed(Loc, MethodDecl->getParent()); 11213 } 11214 11215 // Recursive functions should be marked when used from another function. 11216 // FIXME: Is this really right? 11217 if (CurContext == Func) return; 11218 11219 // Resolve the exception specification for any function which is 11220 // used: CodeGen will need it. 11221 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 11222 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 11223 ResolveExceptionSpec(Loc, FPT); 11224 11225 // Implicit instantiation of function templates and member functions of 11226 // class templates. 11227 if (Func->isImplicitlyInstantiable()) { 11228 bool AlreadyInstantiated = false; 11229 SourceLocation PointOfInstantiation = Loc; 11230 if (FunctionTemplateSpecializationInfo *SpecInfo 11231 = Func->getTemplateSpecializationInfo()) { 11232 if (SpecInfo->getPointOfInstantiation().isInvalid()) 11233 SpecInfo->setPointOfInstantiation(Loc); 11234 else if (SpecInfo->getTemplateSpecializationKind() 11235 == TSK_ImplicitInstantiation) { 11236 AlreadyInstantiated = true; 11237 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 11238 } 11239 } else if (MemberSpecializationInfo *MSInfo 11240 = Func->getMemberSpecializationInfo()) { 11241 if (MSInfo->getPointOfInstantiation().isInvalid()) 11242 MSInfo->setPointOfInstantiation(Loc); 11243 else if (MSInfo->getTemplateSpecializationKind() 11244 == TSK_ImplicitInstantiation) { 11245 AlreadyInstantiated = true; 11246 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 11247 } 11248 } 11249 11250 if (!AlreadyInstantiated || Func->isConstexpr()) { 11251 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 11252 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 11253 ActiveTemplateInstantiations.size()) 11254 PendingLocalImplicitInstantiations.push_back( 11255 std::make_pair(Func, PointOfInstantiation)); 11256 else if (Func->isConstexpr()) 11257 // Do not defer instantiations of constexpr functions, to avoid the 11258 // expression evaluator needing to call back into Sema if it sees a 11259 // call to such a function. 11260 InstantiateFunctionDefinition(PointOfInstantiation, Func); 11261 else { 11262 PendingInstantiations.push_back(std::make_pair(Func, 11263 PointOfInstantiation)); 11264 // Notify the consumer that a function was implicitly instantiated. 11265 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 11266 } 11267 } 11268 } else { 11269 // Walk redefinitions, as some of them may be instantiable. 11270 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()), 11271 e(Func->redecls_end()); i != e; ++i) { 11272 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 11273 MarkFunctionReferenced(Loc, *i); 11274 } 11275 } 11276 11277 // Keep track of used but undefined functions. 11278 if (!Func->isDefined()) { 11279 if (mightHaveNonExternalLinkage(Func)) 11280 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 11281 else if (Func->getMostRecentDecl()->isInlined() && 11282 (LangOpts.CPlusPlus || !LangOpts.GNUInline) && 11283 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 11284 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 11285 } 11286 11287 // Normally the most current decl is marked used while processing the use and 11288 // any subsequent decls are marked used by decl merging. This fails with 11289 // template instantiation since marking can happen at the end of the file 11290 // and, because of the two phase lookup, this function is called with at 11291 // decl in the middle of a decl chain. We loop to maintain the invariant 11292 // that once a decl is used, all decls after it are also used. 11293 for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) { 11294 F->markUsed(Context); 11295 if (F == Func) 11296 break; 11297 } 11298} 11299 11300static void 11301diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 11302 VarDecl *var, DeclContext *DC) { 11303 DeclContext *VarDC = var->getDeclContext(); 11304 11305 // If the parameter still belongs to the translation unit, then 11306 // we're actually just using one parameter in the declaration of 11307 // the next. 11308 if (isa<ParmVarDecl>(var) && 11309 isa<TranslationUnitDecl>(VarDC)) 11310 return; 11311 11312 // For C code, don't diagnose about capture if we're not actually in code 11313 // right now; it's impossible to write a non-constant expression outside of 11314 // function context, so we'll get other (more useful) diagnostics later. 11315 // 11316 // For C++, things get a bit more nasty... it would be nice to suppress this 11317 // diagnostic for certain cases like using a local variable in an array bound 11318 // for a member of a local class, but the correct predicate is not obvious. 11319 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 11320 return; 11321 11322 if (isa<CXXMethodDecl>(VarDC) && 11323 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 11324 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda) 11325 << var->getIdentifier(); 11326 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) { 11327 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 11328 << var->getIdentifier() << fn->getDeclName(); 11329 } else if (isa<BlockDecl>(VarDC)) { 11330 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block) 11331 << var->getIdentifier(); 11332 } else { 11333 // FIXME: Is there any other context where a local variable can be 11334 // declared? 11335 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context) 11336 << var->getIdentifier(); 11337 } 11338 11339 S.Diag(var->getLocation(), diag::note_local_variable_declared_here) 11340 << var->getIdentifier(); 11341 11342 // FIXME: Add additional diagnostic info about class etc. which prevents 11343 // capture. 11344} 11345 11346 11347static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 11348 bool &SubCapturesAreNested, 11349 QualType &CaptureType, 11350 QualType &DeclRefType) { 11351 // Check whether we've already captured it. 11352 if (CSI->CaptureMap.count(Var)) { 11353 // If we found a capture, any subcaptures are nested. 11354 SubCapturesAreNested = true; 11355 11356 // Retrieve the capture type for this variable. 11357 CaptureType = CSI->getCapture(Var).getCaptureType(); 11358 11359 // Compute the type of an expression that refers to this variable. 11360 DeclRefType = CaptureType.getNonReferenceType(); 11361 11362 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 11363 if (Cap.isCopyCapture() && 11364 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable)) 11365 DeclRefType.addConst(); 11366 return true; 11367 } 11368 return false; 11369} 11370 11371// Only block literals, captured statements, and lambda expressions can 11372// capture; other scopes don't work. 11373static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 11374 SourceLocation Loc, 11375 const bool Diagnose, Sema &S) { 11376 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) 11377 return DC->getParent(); 11378 else if (isa<CXXMethodDecl>(DC) && 11379 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call && 11380 cast<CXXRecordDecl>(DC->getParent())->isLambda()) 11381 return DC->getParent()->getParent(); 11382 else { 11383 if (Diagnose) 11384 diagnoseUncapturableValueReference(S, Loc, Var, DC); 11385 } 11386 return 0; 11387} 11388 11389// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 11390// certain types of variables (unnamed, variably modified types etc.) 11391// so check for eligibility. 11392static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 11393 SourceLocation Loc, 11394 const bool Diagnose, Sema &S) { 11395 11396 bool IsBlock = isa<BlockScopeInfo>(CSI); 11397 bool IsLambda = isa<LambdaScopeInfo>(CSI); 11398 11399 // Lambdas are not allowed to capture unnamed variables 11400 // (e.g. anonymous unions). 11401 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 11402 // assuming that's the intent. 11403 if (IsLambda && !Var->getDeclName()) { 11404 if (Diagnose) { 11405 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 11406 S.Diag(Var->getLocation(), diag::note_declared_at); 11407 } 11408 return false; 11409 } 11410 11411 // Prohibit variably-modified types; they're difficult to deal with. 11412 if (Var->getType()->isVariablyModifiedType()) { 11413 if (Diagnose) { 11414 if (IsBlock) 11415 S.Diag(Loc, diag::err_ref_vm_type); 11416 else 11417 S.Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName(); 11418 S.Diag(Var->getLocation(), diag::note_previous_decl) 11419 << Var->getDeclName(); 11420 } 11421 return false; 11422 } 11423 // Prohibit structs with flexible array members too. 11424 // We cannot capture what is in the tail end of the struct. 11425 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 11426 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 11427 if (Diagnose) { 11428 if (IsBlock) 11429 S.Diag(Loc, diag::err_ref_flexarray_type); 11430 else 11431 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 11432 << Var->getDeclName(); 11433 S.Diag(Var->getLocation(), diag::note_previous_decl) 11434 << Var->getDeclName(); 11435 } 11436 return false; 11437 } 11438 } 11439 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 11440 // Lambdas and captured statements are not allowed to capture __block 11441 // variables; they don't support the expected semantics. 11442 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 11443 if (Diagnose) { 11444 S.Diag(Loc, diag::err_capture_block_variable) 11445 << Var->getDeclName() << !IsLambda; 11446 S.Diag(Var->getLocation(), diag::note_previous_decl) 11447 << Var->getDeclName(); 11448 } 11449 return false; 11450 } 11451 11452 return true; 11453} 11454 11455// Returns true if the capture by block was successful. 11456static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 11457 SourceLocation Loc, 11458 const bool BuildAndDiagnose, 11459 QualType &CaptureType, 11460 QualType &DeclRefType, 11461 const bool Nested, 11462 Sema &S) { 11463 Expr *CopyExpr = 0; 11464 bool ByRef = false; 11465 11466 // Blocks are not allowed to capture arrays. 11467 if (CaptureType->isArrayType()) { 11468 if (BuildAndDiagnose) { 11469 S.Diag(Loc, diag::err_ref_array_type); 11470 S.Diag(Var->getLocation(), diag::note_previous_decl) 11471 << Var->getDeclName(); 11472 } 11473 return false; 11474 } 11475 11476 // Forbid the block-capture of autoreleasing variables. 11477 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 11478 if (BuildAndDiagnose) { 11479 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 11480 << /*block*/ 0; 11481 S.Diag(Var->getLocation(), diag::note_previous_decl) 11482 << Var->getDeclName(); 11483 } 11484 return false; 11485 } 11486 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 11487 if (HasBlocksAttr || CaptureType->isReferenceType()) { 11488 // Block capture by reference does not change the capture or 11489 // declaration reference types. 11490 ByRef = true; 11491 } else { 11492 // Block capture by copy introduces 'const'. 11493 CaptureType = CaptureType.getNonReferenceType().withConst(); 11494 DeclRefType = CaptureType; 11495 11496 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 11497 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 11498 // The capture logic needs the destructor, so make sure we mark it. 11499 // Usually this is unnecessary because most local variables have 11500 // their destructors marked at declaration time, but parameters are 11501 // an exception because it's technically only the call site that 11502 // actually requires the destructor. 11503 if (isa<ParmVarDecl>(Var)) 11504 S.FinalizeVarWithDestructor(Var, Record); 11505 11506 // Enter a new evaluation context to insulate the copy 11507 // full-expression. 11508 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated); 11509 11510 // According to the blocks spec, the capture of a variable from 11511 // the stack requires a const copy constructor. This is not true 11512 // of the copy/move done to move a __block variable to the heap. 11513 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 11514 DeclRefType.withConst(), 11515 VK_LValue, Loc); 11516 11517 ExprResult Result 11518 = S.PerformCopyInitialization( 11519 InitializedEntity::InitializeBlock(Var->getLocation(), 11520 CaptureType, false), 11521 Loc, S.Owned(DeclRef)); 11522 11523 // Build a full-expression copy expression if initialization 11524 // succeeded and used a non-trivial constructor. Recover from 11525 // errors by pretending that the copy isn't necessary. 11526 if (!Result.isInvalid() && 11527 !cast<CXXConstructExpr>(Result.get())->getConstructor() 11528 ->isTrivial()) { 11529 Result = S.MaybeCreateExprWithCleanups(Result); 11530 CopyExpr = Result.take(); 11531 } 11532 } 11533 } 11534 } 11535 11536 // Actually capture the variable. 11537 if (BuildAndDiagnose) 11538 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 11539 SourceLocation(), CaptureType, CopyExpr); 11540 11541 return true; 11542 11543} 11544 11545 11546/// \brief Capture the given variable in the captured region. 11547static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 11548 VarDecl *Var, 11549 SourceLocation Loc, 11550 const bool BuildAndDiagnose, 11551 QualType &CaptureType, 11552 QualType &DeclRefType, 11553 const bool RefersToEnclosingLocal, 11554 Sema &S) { 11555 11556 // By default, capture variables by reference. 11557 bool ByRef = true; 11558 // Using an LValue reference type is consistent with Lambdas (see below). 11559 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 11560 Expr *CopyExpr = 0; 11561 if (BuildAndDiagnose) { 11562 // The current implementation assumes that all variables are captured 11563 // by references. Since there is no capture by copy, no expression evaluation 11564 // will be needed. 11565 // 11566 RecordDecl *RD = RSI->TheRecordDecl; 11567 11568 FieldDecl *Field 11569 = FieldDecl::Create(S.Context, RD, Loc, Loc, 0, CaptureType, 11570 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 11571 0, false, ICIS_NoInit); 11572 Field->setImplicit(true); 11573 Field->setAccess(AS_private); 11574 RD->addDecl(Field); 11575 11576 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 11577 DeclRefType, VK_LValue, Loc); 11578 Var->setReferenced(true); 11579 Var->markUsed(S.Context); 11580 } 11581 11582 // Actually capture the variable. 11583 if (BuildAndDiagnose) 11584 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToEnclosingLocal, Loc, 11585 SourceLocation(), CaptureType, CopyExpr); 11586 11587 11588 return true; 11589} 11590 11591/// \brief Create a field within the lambda class for the variable 11592/// being captured. Handle Array captures. 11593static ExprResult addAsFieldToClosureType(Sema &S, 11594 LambdaScopeInfo *LSI, 11595 VarDecl *Var, QualType FieldType, 11596 QualType DeclRefType, 11597 SourceLocation Loc, 11598 bool RefersToEnclosingLocal) { 11599 CXXRecordDecl *Lambda = LSI->Lambda; 11600 11601 // Build the non-static data member. 11602 FieldDecl *Field 11603 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType, 11604 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 11605 0, false, ICIS_NoInit); 11606 Field->setImplicit(true); 11607 Field->setAccess(AS_private); 11608 Lambda->addDecl(Field); 11609 11610 // C++11 [expr.prim.lambda]p21: 11611 // When the lambda-expression is evaluated, the entities that 11612 // are captured by copy are used to direct-initialize each 11613 // corresponding non-static data member of the resulting closure 11614 // object. (For array members, the array elements are 11615 // direct-initialized in increasing subscript order.) These 11616 // initializations are performed in the (unspecified) order in 11617 // which the non-static data members are declared. 11618 11619 // Introduce a new evaluation context for the initialization, so 11620 // that temporaries introduced as part of the capture are retained 11621 // to be re-"exported" from the lambda expression itself. 11622 EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated); 11623 11624 // C++ [expr.prim.labda]p12: 11625 // An entity captured by a lambda-expression is odr-used (3.2) in 11626 // the scope containing the lambda-expression. 11627 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 11628 DeclRefType, VK_LValue, Loc); 11629 Var->setReferenced(true); 11630 Var->markUsed(S.Context); 11631 11632 // When the field has array type, create index variables for each 11633 // dimension of the array. We use these index variables to subscript 11634 // the source array, and other clients (e.g., CodeGen) will perform 11635 // the necessary iteration with these index variables. 11636 SmallVector<VarDecl *, 4> IndexVariables; 11637 QualType BaseType = FieldType; 11638 QualType SizeType = S.Context.getSizeType(); 11639 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size()); 11640 while (const ConstantArrayType *Array 11641 = S.Context.getAsConstantArrayType(BaseType)) { 11642 // Create the iteration variable for this array index. 11643 IdentifierInfo *IterationVarName = 0; 11644 { 11645 SmallString<8> Str; 11646 llvm::raw_svector_ostream OS(Str); 11647 OS << "__i" << IndexVariables.size(); 11648 IterationVarName = &S.Context.Idents.get(OS.str()); 11649 } 11650 VarDecl *IterationVar 11651 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 11652 IterationVarName, SizeType, 11653 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 11654 SC_None); 11655 IndexVariables.push_back(IterationVar); 11656 LSI->ArrayIndexVars.push_back(IterationVar); 11657 11658 // Create a reference to the iteration variable. 11659 ExprResult IterationVarRef 11660 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 11661 assert(!IterationVarRef.isInvalid() && 11662 "Reference to invented variable cannot fail!"); 11663 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take()); 11664 assert(!IterationVarRef.isInvalid() && 11665 "Conversion of invented variable cannot fail!"); 11666 11667 // Subscript the array with this iteration variable. 11668 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr( 11669 Ref, Loc, IterationVarRef.take(), Loc); 11670 if (Subscript.isInvalid()) { 11671 S.CleanupVarDeclMarking(); 11672 S.DiscardCleanupsInEvaluationContext(); 11673 return ExprError(); 11674 } 11675 11676 Ref = Subscript.take(); 11677 BaseType = Array->getElementType(); 11678 } 11679 11680 // Construct the entity that we will be initializing. For an array, this 11681 // will be first element in the array, which may require several levels 11682 // of array-subscript entities. 11683 SmallVector<InitializedEntity, 4> Entities; 11684 Entities.reserve(1 + IndexVariables.size()); 11685 Entities.push_back( 11686 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc)); 11687 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 11688 Entities.push_back(InitializedEntity::InitializeElement(S.Context, 11689 0, 11690 Entities.back())); 11691 11692 InitializationKind InitKind 11693 = InitializationKind::CreateDirect(Loc, Loc, Loc); 11694 InitializationSequence Init(S, Entities.back(), InitKind, Ref); 11695 ExprResult Result(true); 11696 if (!Init.Diagnose(S, Entities.back(), InitKind, Ref)) 11697 Result = Init.Perform(S, Entities.back(), InitKind, Ref); 11698 11699 // If this initialization requires any cleanups (e.g., due to a 11700 // default argument to a copy constructor), note that for the 11701 // lambda. 11702 if (S.ExprNeedsCleanups) 11703 LSI->ExprNeedsCleanups = true; 11704 11705 // Exit the expression evaluation context used for the capture. 11706 S.CleanupVarDeclMarking(); 11707 S.DiscardCleanupsInEvaluationContext(); 11708 return Result; 11709} 11710 11711 11712 11713/// \brief Capture the given variable in the lambda. 11714static bool captureInLambda(LambdaScopeInfo *LSI, 11715 VarDecl *Var, 11716 SourceLocation Loc, 11717 const bool BuildAndDiagnose, 11718 QualType &CaptureType, 11719 QualType &DeclRefType, 11720 const bool RefersToEnclosingLocal, 11721 const Sema::TryCaptureKind Kind, 11722 SourceLocation EllipsisLoc, 11723 const bool IsTopScope, 11724 Sema &S) { 11725 11726 // Determine whether we are capturing by reference or by value. 11727 bool ByRef = false; 11728 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 11729 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 11730 } else { 11731 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 11732 } 11733 11734 // Compute the type of the field that will capture this variable. 11735 if (ByRef) { 11736 // C++11 [expr.prim.lambda]p15: 11737 // An entity is captured by reference if it is implicitly or 11738 // explicitly captured but not captured by copy. It is 11739 // unspecified whether additional unnamed non-static data 11740 // members are declared in the closure type for entities 11741 // captured by reference. 11742 // 11743 // FIXME: It is not clear whether we want to build an lvalue reference 11744 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 11745 // to do the former, while EDG does the latter. Core issue 1249 will 11746 // clarify, but for now we follow GCC because it's a more permissive and 11747 // easily defensible position. 11748 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 11749 } else { 11750 // C++11 [expr.prim.lambda]p14: 11751 // For each entity captured by copy, an unnamed non-static 11752 // data member is declared in the closure type. The 11753 // declaration order of these members is unspecified. The type 11754 // of such a data member is the type of the corresponding 11755 // captured entity if the entity is not a reference to an 11756 // object, or the referenced type otherwise. [Note: If the 11757 // captured entity is a reference to a function, the 11758 // corresponding data member is also a reference to a 11759 // function. - end note ] 11760 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 11761 if (!RefType->getPointeeType()->isFunctionType()) 11762 CaptureType = RefType->getPointeeType(); 11763 } 11764 11765 // Forbid the lambda copy-capture of autoreleasing variables. 11766 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 11767 if (BuildAndDiagnose) { 11768 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 11769 S.Diag(Var->getLocation(), diag::note_previous_decl) 11770 << Var->getDeclName(); 11771 } 11772 return false; 11773 } 11774 11775 if (S.RequireNonAbstractType(Loc, CaptureType, 11776 diag::err_capture_of_abstract_type)) 11777 return false; 11778 } 11779 11780 // Capture this variable in the lambda. 11781 Expr *CopyExpr = 0; 11782 if (BuildAndDiagnose) { 11783 ExprResult Result = addAsFieldToClosureType(S, LSI, Var, 11784 CaptureType, DeclRefType, Loc, 11785 RefersToEnclosingLocal); 11786 if (!Result.isInvalid()) 11787 CopyExpr = Result.take(); 11788 } 11789 11790 // Compute the type of a reference to this captured variable. 11791 if (ByRef) 11792 DeclRefType = CaptureType.getNonReferenceType(); 11793 else { 11794 // C++ [expr.prim.lambda]p5: 11795 // The closure type for a lambda-expression has a public inline 11796 // function call operator [...]. This function call operator is 11797 // declared const (9.3.1) if and only if the lambda-expression’s 11798 // parameter-declaration-clause is not followed by mutable. 11799 DeclRefType = CaptureType.getNonReferenceType(); 11800 if (!LSI->Mutable && !CaptureType->isReferenceType()) 11801 DeclRefType.addConst(); 11802 } 11803 11804 // Add the capture. 11805 if (BuildAndDiagnose) 11806 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToEnclosingLocal, 11807 Loc, EllipsisLoc, CaptureType, CopyExpr); 11808 11809 return true; 11810} 11811 11812 11813bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation ExprLoc, 11814 TryCaptureKind Kind, SourceLocation EllipsisLoc, 11815 bool BuildAndDiagnose, 11816 QualType &CaptureType, 11817 QualType &DeclRefType) { 11818 bool Nested = false; 11819 11820 DeclContext *DC = CurContext; 11821 const unsigned MaxFunctionScopesIndex = FunctionScopes.size() - 1; 11822 11823 // If the variable is declared in the current context (and is not an 11824 // init-capture), there is no need to capture it. 11825 if (!Var->isInitCapture() && Var->getDeclContext() == DC) return true; 11826 if (!Var->hasLocalStorage()) return true; 11827 11828 // Walk up the stack to determine whether we can capture the variable, 11829 // performing the "simple" checks that don't depend on type. We stop when 11830 // we've either hit the declared scope of the variable or find an existing 11831 // capture of that variable. We start from the innermost capturing-entity 11832 // (the DC) and ensure that all intervening capturing-entities 11833 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 11834 // declcontext can either capture the variable or have already captured 11835 // the variable. 11836 CaptureType = Var->getType(); 11837 DeclRefType = CaptureType.getNonReferenceType(); 11838 bool Explicit = (Kind != TryCapture_Implicit); 11839 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 11840 do { 11841 // Only block literals, captured statements, and lambda expressions can 11842 // capture; other scopes don't work. 11843 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 11844 ExprLoc, 11845 BuildAndDiagnose, 11846 *this); 11847 if (!ParentDC) return true; 11848 11849 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 11850 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 11851 11852 11853 // Check whether we've already captured it. 11854 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 11855 DeclRefType)) 11856 break; 11857 11858 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 11859 // certain types of variables (unnamed, variably modified types etc.) 11860 // so check for eligibility. 11861 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 11862 return true; 11863 11864 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 11865 // No capture-default, and this is not an explicit capture 11866 // so cannot capture this variable. 11867 if (BuildAndDiagnose) { 11868 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 11869 Diag(Var->getLocation(), diag::note_previous_decl) 11870 << Var->getDeclName(); 11871 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 11872 diag::note_lambda_decl); 11873 } 11874 return true; 11875 } 11876 11877 FunctionScopesIndex--; 11878 DC = ParentDC; 11879 Explicit = false; 11880 } while (!Var->getDeclContext()->Equals(DC)); 11881 11882 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 11883 // computing the type of the capture at each step, checking type-specific 11884 // requirements, and adding captures if requested. 11885 // If the variable had already been captured previously, we start capturing 11886 // at the lambda nested within that one. 11887 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 11888 ++I) { 11889 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 11890 11891 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 11892 if (!captureInBlock(BSI, Var, ExprLoc, 11893 BuildAndDiagnose, CaptureType, 11894 DeclRefType, Nested, *this)) 11895 return true; 11896 Nested = true; 11897 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 11898 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 11899 BuildAndDiagnose, CaptureType, 11900 DeclRefType, Nested, *this)) 11901 return true; 11902 Nested = true; 11903 } else { 11904 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 11905 if (!captureInLambda(LSI, Var, ExprLoc, 11906 BuildAndDiagnose, CaptureType, 11907 DeclRefType, Nested, Kind, EllipsisLoc, 11908 /*IsTopScope*/I == N - 1, *this)) 11909 return true; 11910 Nested = true; 11911 } 11912 } 11913 return false; 11914} 11915 11916bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 11917 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 11918 QualType CaptureType; 11919 QualType DeclRefType; 11920 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 11921 /*BuildAndDiagnose=*/true, CaptureType, 11922 DeclRefType); 11923} 11924 11925QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 11926 QualType CaptureType; 11927 QualType DeclRefType; 11928 11929 // Determine whether we can capture this variable. 11930 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 11931 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType)) 11932 return QualType(); 11933 11934 return DeclRefType; 11935} 11936 11937static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var, 11938 SourceLocation Loc) { 11939 // Keep track of used but undefined variables. 11940 // FIXME: We shouldn't suppress this warning for static data members. 11941 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 11942 !Var->isExternallyVisible() && 11943 !(Var->isStaticDataMember() && Var->hasInit())) { 11944 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 11945 if (old.isInvalid()) old = Loc; 11946 } 11947 11948 SemaRef.tryCaptureVariable(Var, Loc); 11949 11950 Var->markUsed(SemaRef.Context); 11951} 11952 11953void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 11954 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 11955 // an object that satisfies the requirements for appearing in a 11956 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 11957 // is immediately applied." This function handles the lvalue-to-rvalue 11958 // conversion part. 11959 MaybeODRUseExprs.erase(E->IgnoreParens()); 11960} 11961 11962ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 11963 if (!Res.isUsable()) 11964 return Res; 11965 11966 // If a constant-expression is a reference to a variable where we delay 11967 // deciding whether it is an odr-use, just assume we will apply the 11968 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 11969 // (a non-type template argument), we have special handling anyway. 11970 UpdateMarkingForLValueToRValue(Res.get()); 11971 return Res; 11972} 11973 11974void Sema::CleanupVarDeclMarking() { 11975 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(), 11976 e = MaybeODRUseExprs.end(); 11977 i != e; ++i) { 11978 VarDecl *Var; 11979 SourceLocation Loc; 11980 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) { 11981 Var = cast<VarDecl>(DRE->getDecl()); 11982 Loc = DRE->getLocation(); 11983 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) { 11984 Var = cast<VarDecl>(ME->getMemberDecl()); 11985 Loc = ME->getMemberLoc(); 11986 } else { 11987 llvm_unreachable("Unexpcted expression"); 11988 } 11989 11990 MarkVarDeclODRUsed(*this, Var, Loc); 11991 } 11992 11993 MaybeODRUseExprs.clear(); 11994} 11995 11996// Mark a VarDecl referenced, and perform the necessary handling to compute 11997// odr-uses. 11998static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 11999 VarDecl *Var, Expr *E) { 12000 Var->setReferenced(); 12001 12002 if (!IsPotentiallyEvaluatedContext(SemaRef)) 12003 return; 12004 12005 VarTemplateSpecializationDecl *VarSpec = 12006 dyn_cast<VarTemplateSpecializationDecl>(Var); 12007 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 12008 "Can't instantiate a partial template specialization."); 12009 12010 // Implicit instantiation of static data members, static data member 12011 // templates of class templates, and variable template specializations. 12012 // Delay instantiations of variable templates, except for those 12013 // that could be used in a constant expression. 12014 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 12015 if (isTemplateInstantiation(TSK)) { 12016 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 12017 12018 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 12019 if (Var->getPointOfInstantiation().isInvalid()) { 12020 // This is a modification of an existing AST node. Notify listeners. 12021 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 12022 L->StaticDataMemberInstantiated(Var); 12023 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 12024 // Don't bother trying to instantiate it again, unless we might need 12025 // its initializer before we get to the end of the TU. 12026 TryInstantiating = false; 12027 } 12028 12029 if (Var->getPointOfInstantiation().isInvalid()) 12030 Var->setTemplateSpecializationKind(TSK, Loc); 12031 12032 if (TryInstantiating) { 12033 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 12034 bool InstantiationDependent = false; 12035 bool IsNonDependent = 12036 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 12037 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 12038 : true; 12039 12040 // Do not instantiate specializations that are still type-dependent. 12041 if (IsNonDependent) { 12042 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 12043 // Do not defer instantiations of variables which could be used in a 12044 // constant expression. 12045 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 12046 } else { 12047 SemaRef.PendingInstantiations 12048 .push_back(std::make_pair(Var, PointOfInstantiation)); 12049 } 12050 } 12051 } 12052 } 12053 12054 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 12055 // the requirements for appearing in a constant expression (5.19) and, if 12056 // it is an object, the lvalue-to-rvalue conversion (4.1) 12057 // is immediately applied." We check the first part here, and 12058 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 12059 // Note that we use the C++11 definition everywhere because nothing in 12060 // C++03 depends on whether we get the C++03 version correct. The second 12061 // part does not apply to references, since they are not objects. 12062 const VarDecl *DefVD; 12063 if (E && !isa<ParmVarDecl>(Var) && 12064 Var->isUsableInConstantExpressions(SemaRef.Context) && 12065 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE()) { 12066 if (!Var->getType()->isReferenceType()) 12067 SemaRef.MaybeODRUseExprs.insert(E); 12068 } else 12069 MarkVarDeclODRUsed(SemaRef, Var, Loc); 12070} 12071 12072/// \brief Mark a variable referenced, and check whether it is odr-used 12073/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 12074/// used directly for normal expressions referring to VarDecl. 12075void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 12076 DoMarkVarDeclReferenced(*this, Loc, Var, 0); 12077} 12078 12079static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 12080 Decl *D, Expr *E, bool OdrUse) { 12081 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 12082 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 12083 return; 12084 } 12085 12086 SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse); 12087 12088 // If this is a call to a method via a cast, also mark the method in the 12089 // derived class used in case codegen can devirtualize the call. 12090 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12091 if (!ME) 12092 return; 12093 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 12094 if (!MD) 12095 return; 12096 const Expr *Base = ME->getBase(); 12097 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 12098 if (!MostDerivedClassDecl) 12099 return; 12100 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 12101 if (!DM || DM->isPure()) 12102 return; 12103 SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse); 12104} 12105 12106/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 12107void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 12108 // TODO: update this with DR# once a defect report is filed. 12109 // C++11 defect. The address of a pure member should not be an ODR use, even 12110 // if it's a qualified reference. 12111 bool OdrUse = true; 12112 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 12113 if (Method->isVirtual()) 12114 OdrUse = false; 12115 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 12116} 12117 12118/// \brief Perform reference-marking and odr-use handling for a MemberExpr. 12119void Sema::MarkMemberReferenced(MemberExpr *E) { 12120 // C++11 [basic.def.odr]p2: 12121 // A non-overloaded function whose name appears as a potentially-evaluated 12122 // expression or a member of a set of candidate functions, if selected by 12123 // overload resolution when referred to from a potentially-evaluated 12124 // expression, is odr-used, unless it is a pure virtual function and its 12125 // name is not explicitly qualified. 12126 bool OdrUse = true; 12127 if (!E->hasQualifier()) { 12128 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 12129 if (Method->isPure()) 12130 OdrUse = false; 12131 } 12132 SourceLocation Loc = E->getMemberLoc().isValid() ? 12133 E->getMemberLoc() : E->getLocStart(); 12134 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse); 12135} 12136 12137/// \brief Perform marking for a reference to an arbitrary declaration. It 12138/// marks the declaration referenced, and performs odr-use checking for functions 12139/// and variables. This method should not be used when building an normal 12140/// expression which refers to a variable. 12141void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) { 12142 if (OdrUse) { 12143 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 12144 MarkVariableReferenced(Loc, VD); 12145 return; 12146 } 12147 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 12148 MarkFunctionReferenced(Loc, FD); 12149 return; 12150 } 12151 } 12152 D->setReferenced(); 12153} 12154 12155namespace { 12156 // Mark all of the declarations referenced 12157 // FIXME: Not fully implemented yet! We need to have a better understanding 12158 // of when we're entering 12159 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 12160 Sema &S; 12161 SourceLocation Loc; 12162 12163 public: 12164 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 12165 12166 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 12167 12168 bool TraverseTemplateArgument(const TemplateArgument &Arg); 12169 bool TraverseRecordType(RecordType *T); 12170 }; 12171} 12172 12173bool MarkReferencedDecls::TraverseTemplateArgument( 12174 const TemplateArgument &Arg) { 12175 if (Arg.getKind() == TemplateArgument::Declaration) { 12176 if (Decl *D = Arg.getAsDecl()) 12177 S.MarkAnyDeclReferenced(Loc, D, true); 12178 } 12179 12180 return Inherited::TraverseTemplateArgument(Arg); 12181} 12182 12183bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 12184 if (ClassTemplateSpecializationDecl *Spec 12185 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 12186 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 12187 return TraverseTemplateArguments(Args.data(), Args.size()); 12188 } 12189 12190 return true; 12191} 12192 12193void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 12194 MarkReferencedDecls Marker(*this, Loc); 12195 Marker.TraverseType(Context.getCanonicalType(T)); 12196} 12197 12198namespace { 12199 /// \brief Helper class that marks all of the declarations referenced by 12200 /// potentially-evaluated subexpressions as "referenced". 12201 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 12202 Sema &S; 12203 bool SkipLocalVariables; 12204 12205 public: 12206 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 12207 12208 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 12209 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 12210 12211 void VisitDeclRefExpr(DeclRefExpr *E) { 12212 // If we were asked not to visit local variables, don't. 12213 if (SkipLocalVariables) { 12214 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 12215 if (VD->hasLocalStorage()) 12216 return; 12217 } 12218 12219 S.MarkDeclRefReferenced(E); 12220 } 12221 12222 void VisitMemberExpr(MemberExpr *E) { 12223 S.MarkMemberReferenced(E); 12224 Inherited::VisitMemberExpr(E); 12225 } 12226 12227 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 12228 S.MarkFunctionReferenced(E->getLocStart(), 12229 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 12230 Visit(E->getSubExpr()); 12231 } 12232 12233 void VisitCXXNewExpr(CXXNewExpr *E) { 12234 if (E->getOperatorNew()) 12235 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 12236 if (E->getOperatorDelete()) 12237 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 12238 Inherited::VisitCXXNewExpr(E); 12239 } 12240 12241 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 12242 if (E->getOperatorDelete()) 12243 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 12244 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 12245 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 12246 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 12247 S.MarkFunctionReferenced(E->getLocStart(), 12248 S.LookupDestructor(Record)); 12249 } 12250 12251 Inherited::VisitCXXDeleteExpr(E); 12252 } 12253 12254 void VisitCXXConstructExpr(CXXConstructExpr *E) { 12255 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 12256 Inherited::VisitCXXConstructExpr(E); 12257 } 12258 12259 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 12260 Visit(E->getExpr()); 12261 } 12262 12263 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 12264 Inherited::VisitImplicitCastExpr(E); 12265 12266 if (E->getCastKind() == CK_LValueToRValue) 12267 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 12268 } 12269 }; 12270} 12271 12272/// \brief Mark any declarations that appear within this expression or any 12273/// potentially-evaluated subexpressions as "referenced". 12274/// 12275/// \param SkipLocalVariables If true, don't mark local variables as 12276/// 'referenced'. 12277void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 12278 bool SkipLocalVariables) { 12279 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 12280} 12281 12282/// \brief Emit a diagnostic that describes an effect on the run-time behavior 12283/// of the program being compiled. 12284/// 12285/// This routine emits the given diagnostic when the code currently being 12286/// type-checked is "potentially evaluated", meaning that there is a 12287/// possibility that the code will actually be executable. Code in sizeof() 12288/// expressions, code used only during overload resolution, etc., are not 12289/// potentially evaluated. This routine will suppress such diagnostics or, 12290/// in the absolutely nutty case of potentially potentially evaluated 12291/// expressions (C++ typeid), queue the diagnostic to potentially emit it 12292/// later. 12293/// 12294/// This routine should be used for all diagnostics that describe the run-time 12295/// behavior of a program, such as passing a non-POD value through an ellipsis. 12296/// Failure to do so will likely result in spurious diagnostics or failures 12297/// during overload resolution or within sizeof/alignof/typeof/typeid. 12298bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 12299 const PartialDiagnostic &PD) { 12300 switch (ExprEvalContexts.back().Context) { 12301 case Unevaluated: 12302 case UnevaluatedAbstract: 12303 // The argument will never be evaluated, so don't complain. 12304 break; 12305 12306 case ConstantEvaluated: 12307 // Relevant diagnostics should be produced by constant evaluation. 12308 break; 12309 12310 case PotentiallyEvaluated: 12311 case PotentiallyEvaluatedIfUsed: 12312 if (Statement && getCurFunctionOrMethodDecl()) { 12313 FunctionScopes.back()->PossiblyUnreachableDiags. 12314 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 12315 } 12316 else 12317 Diag(Loc, PD); 12318 12319 return true; 12320 } 12321 12322 return false; 12323} 12324 12325bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 12326 CallExpr *CE, FunctionDecl *FD) { 12327 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 12328 return false; 12329 12330 // If we're inside a decltype's expression, don't check for a valid return 12331 // type or construct temporaries until we know whether this is the last call. 12332 if (ExprEvalContexts.back().IsDecltype) { 12333 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 12334 return false; 12335 } 12336 12337 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 12338 FunctionDecl *FD; 12339 CallExpr *CE; 12340 12341 public: 12342 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 12343 : FD(FD), CE(CE) { } 12344 12345 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 12346 if (!FD) { 12347 S.Diag(Loc, diag::err_call_incomplete_return) 12348 << T << CE->getSourceRange(); 12349 return; 12350 } 12351 12352 S.Diag(Loc, diag::err_call_function_incomplete_return) 12353 << CE->getSourceRange() << FD->getDeclName() << T; 12354 S.Diag(FD->getLocation(), 12355 diag::note_function_with_incomplete_return_type_declared_here) 12356 << FD->getDeclName(); 12357 } 12358 } Diagnoser(FD, CE); 12359 12360 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 12361 return true; 12362 12363 return false; 12364} 12365 12366// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 12367// will prevent this condition from triggering, which is what we want. 12368void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 12369 SourceLocation Loc; 12370 12371 unsigned diagnostic = diag::warn_condition_is_assignment; 12372 bool IsOrAssign = false; 12373 12374 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 12375 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 12376 return; 12377 12378 IsOrAssign = Op->getOpcode() == BO_OrAssign; 12379 12380 // Greylist some idioms by putting them into a warning subcategory. 12381 if (ObjCMessageExpr *ME 12382 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 12383 Selector Sel = ME->getSelector(); 12384 12385 // self = [<foo> init...] 12386 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 12387 diagnostic = diag::warn_condition_is_idiomatic_assignment; 12388 12389 // <foo> = [<bar> nextObject] 12390 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 12391 diagnostic = diag::warn_condition_is_idiomatic_assignment; 12392 } 12393 12394 Loc = Op->getOperatorLoc(); 12395 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 12396 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 12397 return; 12398 12399 IsOrAssign = Op->getOperator() == OO_PipeEqual; 12400 Loc = Op->getOperatorLoc(); 12401 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 12402 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 12403 else { 12404 // Not an assignment. 12405 return; 12406 } 12407 12408 Diag(Loc, diagnostic) << E->getSourceRange(); 12409 12410 SourceLocation Open = E->getLocStart(); 12411 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd()); 12412 Diag(Loc, diag::note_condition_assign_silence) 12413 << FixItHint::CreateInsertion(Open, "(") 12414 << FixItHint::CreateInsertion(Close, ")"); 12415 12416 if (IsOrAssign) 12417 Diag(Loc, diag::note_condition_or_assign_to_comparison) 12418 << FixItHint::CreateReplacement(Loc, "!="); 12419 else 12420 Diag(Loc, diag::note_condition_assign_to_comparison) 12421 << FixItHint::CreateReplacement(Loc, "=="); 12422} 12423 12424/// \brief Redundant parentheses over an equality comparison can indicate 12425/// that the user intended an assignment used as condition. 12426void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 12427 // Don't warn if the parens came from a macro. 12428 SourceLocation parenLoc = ParenE->getLocStart(); 12429 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 12430 return; 12431 // Don't warn for dependent expressions. 12432 if (ParenE->isTypeDependent()) 12433 return; 12434 12435 Expr *E = ParenE->IgnoreParens(); 12436 12437 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 12438 if (opE->getOpcode() == BO_EQ && 12439 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 12440 == Expr::MLV_Valid) { 12441 SourceLocation Loc = opE->getOperatorLoc(); 12442 12443 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 12444 SourceRange ParenERange = ParenE->getSourceRange(); 12445 Diag(Loc, diag::note_equality_comparison_silence) 12446 << FixItHint::CreateRemoval(ParenERange.getBegin()) 12447 << FixItHint::CreateRemoval(ParenERange.getEnd()); 12448 Diag(Loc, diag::note_equality_comparison_to_assign) 12449 << FixItHint::CreateReplacement(Loc, "="); 12450 } 12451} 12452 12453ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) { 12454 DiagnoseAssignmentAsCondition(E); 12455 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 12456 DiagnoseEqualityWithExtraParens(parenE); 12457 12458 ExprResult result = CheckPlaceholderExpr(E); 12459 if (result.isInvalid()) return ExprError(); 12460 E = result.take(); 12461 12462 if (!E->isTypeDependent()) { 12463 if (getLangOpts().CPlusPlus) 12464 return CheckCXXBooleanCondition(E); // C++ 6.4p4 12465 12466 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 12467 if (ERes.isInvalid()) 12468 return ExprError(); 12469 E = ERes.take(); 12470 12471 QualType T = E->getType(); 12472 if (!T->isScalarType()) { // C99 6.8.4.1p1 12473 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 12474 << T << E->getSourceRange(); 12475 return ExprError(); 12476 } 12477 } 12478 12479 return Owned(E); 12480} 12481 12482ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc, 12483 Expr *SubExpr) { 12484 if (!SubExpr) 12485 return ExprError(); 12486 12487 return CheckBooleanCondition(SubExpr, Loc); 12488} 12489 12490namespace { 12491 /// A visitor for rebuilding a call to an __unknown_any expression 12492 /// to have an appropriate type. 12493 struct RebuildUnknownAnyFunction 12494 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 12495 12496 Sema &S; 12497 12498 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 12499 12500 ExprResult VisitStmt(Stmt *S) { 12501 llvm_unreachable("unexpected statement!"); 12502 } 12503 12504 ExprResult VisitExpr(Expr *E) { 12505 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 12506 << E->getSourceRange(); 12507 return ExprError(); 12508 } 12509 12510 /// Rebuild an expression which simply semantically wraps another 12511 /// expression which it shares the type and value kind of. 12512 template <class T> ExprResult rebuildSugarExpr(T *E) { 12513 ExprResult SubResult = Visit(E->getSubExpr()); 12514 if (SubResult.isInvalid()) return ExprError(); 12515 12516 Expr *SubExpr = SubResult.take(); 12517 E->setSubExpr(SubExpr); 12518 E->setType(SubExpr->getType()); 12519 E->setValueKind(SubExpr->getValueKind()); 12520 assert(E->getObjectKind() == OK_Ordinary); 12521 return E; 12522 } 12523 12524 ExprResult VisitParenExpr(ParenExpr *E) { 12525 return rebuildSugarExpr(E); 12526 } 12527 12528 ExprResult VisitUnaryExtension(UnaryOperator *E) { 12529 return rebuildSugarExpr(E); 12530 } 12531 12532 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 12533 ExprResult SubResult = Visit(E->getSubExpr()); 12534 if (SubResult.isInvalid()) return ExprError(); 12535 12536 Expr *SubExpr = SubResult.take(); 12537 E->setSubExpr(SubExpr); 12538 E->setType(S.Context.getPointerType(SubExpr->getType())); 12539 assert(E->getValueKind() == VK_RValue); 12540 assert(E->getObjectKind() == OK_Ordinary); 12541 return E; 12542 } 12543 12544 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 12545 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 12546 12547 E->setType(VD->getType()); 12548 12549 assert(E->getValueKind() == VK_RValue); 12550 if (S.getLangOpts().CPlusPlus && 12551 !(isa<CXXMethodDecl>(VD) && 12552 cast<CXXMethodDecl>(VD)->isInstance())) 12553 E->setValueKind(VK_LValue); 12554 12555 return E; 12556 } 12557 12558 ExprResult VisitMemberExpr(MemberExpr *E) { 12559 return resolveDecl(E, E->getMemberDecl()); 12560 } 12561 12562 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 12563 return resolveDecl(E, E->getDecl()); 12564 } 12565 }; 12566} 12567 12568/// Given a function expression of unknown-any type, try to rebuild it 12569/// to have a function type. 12570static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 12571 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 12572 if (Result.isInvalid()) return ExprError(); 12573 return S.DefaultFunctionArrayConversion(Result.take()); 12574} 12575 12576namespace { 12577 /// A visitor for rebuilding an expression of type __unknown_anytype 12578 /// into one which resolves the type directly on the referring 12579 /// expression. Strict preservation of the original source 12580 /// structure is not a goal. 12581 struct RebuildUnknownAnyExpr 12582 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 12583 12584 Sema &S; 12585 12586 /// The current destination type. 12587 QualType DestType; 12588 12589 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 12590 : S(S), DestType(CastType) {} 12591 12592 ExprResult VisitStmt(Stmt *S) { 12593 llvm_unreachable("unexpected statement!"); 12594 } 12595 12596 ExprResult VisitExpr(Expr *E) { 12597 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 12598 << E->getSourceRange(); 12599 return ExprError(); 12600 } 12601 12602 ExprResult VisitCallExpr(CallExpr *E); 12603 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 12604 12605 /// Rebuild an expression which simply semantically wraps another 12606 /// expression which it shares the type and value kind of. 12607 template <class T> ExprResult rebuildSugarExpr(T *E) { 12608 ExprResult SubResult = Visit(E->getSubExpr()); 12609 if (SubResult.isInvalid()) return ExprError(); 12610 Expr *SubExpr = SubResult.take(); 12611 E->setSubExpr(SubExpr); 12612 E->setType(SubExpr->getType()); 12613 E->setValueKind(SubExpr->getValueKind()); 12614 assert(E->getObjectKind() == OK_Ordinary); 12615 return E; 12616 } 12617 12618 ExprResult VisitParenExpr(ParenExpr *E) { 12619 return rebuildSugarExpr(E); 12620 } 12621 12622 ExprResult VisitUnaryExtension(UnaryOperator *E) { 12623 return rebuildSugarExpr(E); 12624 } 12625 12626 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 12627 const PointerType *Ptr = DestType->getAs<PointerType>(); 12628 if (!Ptr) { 12629 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 12630 << E->getSourceRange(); 12631 return ExprError(); 12632 } 12633 assert(E->getValueKind() == VK_RValue); 12634 assert(E->getObjectKind() == OK_Ordinary); 12635 E->setType(DestType); 12636 12637 // Build the sub-expression as if it were an object of the pointee type. 12638 DestType = Ptr->getPointeeType(); 12639 ExprResult SubResult = Visit(E->getSubExpr()); 12640 if (SubResult.isInvalid()) return ExprError(); 12641 E->setSubExpr(SubResult.take()); 12642 return E; 12643 } 12644 12645 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 12646 12647 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 12648 12649 ExprResult VisitMemberExpr(MemberExpr *E) { 12650 return resolveDecl(E, E->getMemberDecl()); 12651 } 12652 12653 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 12654 return resolveDecl(E, E->getDecl()); 12655 } 12656 }; 12657} 12658 12659/// Rebuilds a call expression which yielded __unknown_anytype. 12660ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 12661 Expr *CalleeExpr = E->getCallee(); 12662 12663 enum FnKind { 12664 FK_MemberFunction, 12665 FK_FunctionPointer, 12666 FK_BlockPointer 12667 }; 12668 12669 FnKind Kind; 12670 QualType CalleeType = CalleeExpr->getType(); 12671 if (CalleeType == S.Context.BoundMemberTy) { 12672 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 12673 Kind = FK_MemberFunction; 12674 CalleeType = Expr::findBoundMemberType(CalleeExpr); 12675 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 12676 CalleeType = Ptr->getPointeeType(); 12677 Kind = FK_FunctionPointer; 12678 } else { 12679 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 12680 Kind = FK_BlockPointer; 12681 } 12682 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 12683 12684 // Verify that this is a legal result type of a function. 12685 if (DestType->isArrayType() || DestType->isFunctionType()) { 12686 unsigned diagID = diag::err_func_returning_array_function; 12687 if (Kind == FK_BlockPointer) 12688 diagID = diag::err_block_returning_array_function; 12689 12690 S.Diag(E->getExprLoc(), diagID) 12691 << DestType->isFunctionType() << DestType; 12692 return ExprError(); 12693 } 12694 12695 // Otherwise, go ahead and set DestType as the call's result. 12696 E->setType(DestType.getNonLValueExprType(S.Context)); 12697 E->setValueKind(Expr::getValueKindForType(DestType)); 12698 assert(E->getObjectKind() == OK_Ordinary); 12699 12700 // Rebuild the function type, replacing the result type with DestType. 12701 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 12702 if (Proto) { 12703 // __unknown_anytype(...) is a special case used by the debugger when 12704 // it has no idea what a function's signature is. 12705 // 12706 // We want to build this call essentially under the K&R 12707 // unprototyped rules, but making a FunctionNoProtoType in C++ 12708 // would foul up all sorts of assumptions. However, we cannot 12709 // simply pass all arguments as variadic arguments, nor can we 12710 // portably just call the function under a non-variadic type; see 12711 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 12712 // However, it turns out that in practice it is generally safe to 12713 // call a function declared as "A foo(B,C,D);" under the prototype 12714 // "A foo(B,C,D,...);". The only known exception is with the 12715 // Windows ABI, where any variadic function is implicitly cdecl 12716 // regardless of its normal CC. Therefore we change the parameter 12717 // types to match the types of the arguments. 12718 // 12719 // This is a hack, but it is far superior to moving the 12720 // corresponding target-specific code from IR-gen to Sema/AST. 12721 12722 ArrayRef<QualType> ParamTypes = Proto->getArgTypes(); 12723 SmallVector<QualType, 8> ArgTypes; 12724 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 12725 ArgTypes.reserve(E->getNumArgs()); 12726 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 12727 Expr *Arg = E->getArg(i); 12728 QualType ArgType = Arg->getType(); 12729 if (E->isLValue()) { 12730 ArgType = S.Context.getLValueReferenceType(ArgType); 12731 } else if (E->isXValue()) { 12732 ArgType = S.Context.getRValueReferenceType(ArgType); 12733 } 12734 ArgTypes.push_back(ArgType); 12735 } 12736 ParamTypes = ArgTypes; 12737 } 12738 DestType = S.Context.getFunctionType(DestType, ParamTypes, 12739 Proto->getExtProtoInfo()); 12740 } else { 12741 DestType = S.Context.getFunctionNoProtoType(DestType, 12742 FnType->getExtInfo()); 12743 } 12744 12745 // Rebuild the appropriate pointer-to-function type. 12746 switch (Kind) { 12747 case FK_MemberFunction: 12748 // Nothing to do. 12749 break; 12750 12751 case FK_FunctionPointer: 12752 DestType = S.Context.getPointerType(DestType); 12753 break; 12754 12755 case FK_BlockPointer: 12756 DestType = S.Context.getBlockPointerType(DestType); 12757 break; 12758 } 12759 12760 // Finally, we can recurse. 12761 ExprResult CalleeResult = Visit(CalleeExpr); 12762 if (!CalleeResult.isUsable()) return ExprError(); 12763 E->setCallee(CalleeResult.take()); 12764 12765 // Bind a temporary if necessary. 12766 return S.MaybeBindToTemporary(E); 12767} 12768 12769ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 12770 // Verify that this is a legal result type of a call. 12771 if (DestType->isArrayType() || DestType->isFunctionType()) { 12772 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 12773 << DestType->isFunctionType() << DestType; 12774 return ExprError(); 12775 } 12776 12777 // Rewrite the method result type if available. 12778 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 12779 assert(Method->getResultType() == S.Context.UnknownAnyTy); 12780 Method->setResultType(DestType); 12781 } 12782 12783 // Change the type of the message. 12784 E->setType(DestType.getNonReferenceType()); 12785 E->setValueKind(Expr::getValueKindForType(DestType)); 12786 12787 return S.MaybeBindToTemporary(E); 12788} 12789 12790ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 12791 // The only case we should ever see here is a function-to-pointer decay. 12792 if (E->getCastKind() == CK_FunctionToPointerDecay) { 12793 assert(E->getValueKind() == VK_RValue); 12794 assert(E->getObjectKind() == OK_Ordinary); 12795 12796 E->setType(DestType); 12797 12798 // Rebuild the sub-expression as the pointee (function) type. 12799 DestType = DestType->castAs<PointerType>()->getPointeeType(); 12800 12801 ExprResult Result = Visit(E->getSubExpr()); 12802 if (!Result.isUsable()) return ExprError(); 12803 12804 E->setSubExpr(Result.take()); 12805 return S.Owned(E); 12806 } else if (E->getCastKind() == CK_LValueToRValue) { 12807 assert(E->getValueKind() == VK_RValue); 12808 assert(E->getObjectKind() == OK_Ordinary); 12809 12810 assert(isa<BlockPointerType>(E->getType())); 12811 12812 E->setType(DestType); 12813 12814 // The sub-expression has to be a lvalue reference, so rebuild it as such. 12815 DestType = S.Context.getLValueReferenceType(DestType); 12816 12817 ExprResult Result = Visit(E->getSubExpr()); 12818 if (!Result.isUsable()) return ExprError(); 12819 12820 E->setSubExpr(Result.take()); 12821 return S.Owned(E); 12822 } else { 12823 llvm_unreachable("Unhandled cast type!"); 12824 } 12825} 12826 12827ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 12828 ExprValueKind ValueKind = VK_LValue; 12829 QualType Type = DestType; 12830 12831 // We know how to make this work for certain kinds of decls: 12832 12833 // - functions 12834 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 12835 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 12836 DestType = Ptr->getPointeeType(); 12837 ExprResult Result = resolveDecl(E, VD); 12838 if (Result.isInvalid()) return ExprError(); 12839 return S.ImpCastExprToType(Result.take(), Type, 12840 CK_FunctionToPointerDecay, VK_RValue); 12841 } 12842 12843 if (!Type->isFunctionType()) { 12844 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 12845 << VD << E->getSourceRange(); 12846 return ExprError(); 12847 } 12848 12849 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 12850 if (MD->isInstance()) { 12851 ValueKind = VK_RValue; 12852 Type = S.Context.BoundMemberTy; 12853 } 12854 12855 // Function references aren't l-values in C. 12856 if (!S.getLangOpts().CPlusPlus) 12857 ValueKind = VK_RValue; 12858 12859 // - variables 12860 } else if (isa<VarDecl>(VD)) { 12861 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 12862 Type = RefTy->getPointeeType(); 12863 } else if (Type->isFunctionType()) { 12864 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 12865 << VD << E->getSourceRange(); 12866 return ExprError(); 12867 } 12868 12869 // - nothing else 12870 } else { 12871 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 12872 << VD << E->getSourceRange(); 12873 return ExprError(); 12874 } 12875 12876 // Modifying the declaration like this is friendly to IR-gen but 12877 // also really dangerous. 12878 VD->setType(DestType); 12879 E->setType(Type); 12880 E->setValueKind(ValueKind); 12881 return S.Owned(E); 12882} 12883 12884/// Check a cast of an unknown-any type. We intentionally only 12885/// trigger this for C-style casts. 12886ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 12887 Expr *CastExpr, CastKind &CastKind, 12888 ExprValueKind &VK, CXXCastPath &Path) { 12889 // Rewrite the casted expression from scratch. 12890 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 12891 if (!result.isUsable()) return ExprError(); 12892 12893 CastExpr = result.take(); 12894 VK = CastExpr->getValueKind(); 12895 CastKind = CK_NoOp; 12896 12897 return CastExpr; 12898} 12899 12900ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 12901 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 12902} 12903 12904ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 12905 Expr *arg, QualType ¶mType) { 12906 // If the syntactic form of the argument is not an explicit cast of 12907 // any sort, just do default argument promotion. 12908 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 12909 if (!castArg) { 12910 ExprResult result = DefaultArgumentPromotion(arg); 12911 if (result.isInvalid()) return ExprError(); 12912 paramType = result.get()->getType(); 12913 return result; 12914 } 12915 12916 // Otherwise, use the type that was written in the explicit cast. 12917 assert(!arg->hasPlaceholderType()); 12918 paramType = castArg->getTypeAsWritten(); 12919 12920 // Copy-initialize a parameter of that type. 12921 InitializedEntity entity = 12922 InitializedEntity::InitializeParameter(Context, paramType, 12923 /*consumed*/ false); 12924 return PerformCopyInitialization(entity, callLoc, Owned(arg)); 12925} 12926 12927static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 12928 Expr *orig = E; 12929 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 12930 while (true) { 12931 E = E->IgnoreParenImpCasts(); 12932 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 12933 E = call->getCallee(); 12934 diagID = diag::err_uncasted_call_of_unknown_any; 12935 } else { 12936 break; 12937 } 12938 } 12939 12940 SourceLocation loc; 12941 NamedDecl *d; 12942 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 12943 loc = ref->getLocation(); 12944 d = ref->getDecl(); 12945 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 12946 loc = mem->getMemberLoc(); 12947 d = mem->getMemberDecl(); 12948 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 12949 diagID = diag::err_uncasted_call_of_unknown_any; 12950 loc = msg->getSelectorStartLoc(); 12951 d = msg->getMethodDecl(); 12952 if (!d) { 12953 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 12954 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 12955 << orig->getSourceRange(); 12956 return ExprError(); 12957 } 12958 } else { 12959 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 12960 << E->getSourceRange(); 12961 return ExprError(); 12962 } 12963 12964 S.Diag(loc, diagID) << d << orig->getSourceRange(); 12965 12966 // Never recoverable. 12967 return ExprError(); 12968} 12969 12970/// Check for operands with placeholder types and complain if found. 12971/// Returns true if there was an error and no recovery was possible. 12972ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 12973 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 12974 if (!placeholderType) return Owned(E); 12975 12976 switch (placeholderType->getKind()) { 12977 12978 // Overloaded expressions. 12979 case BuiltinType::Overload: { 12980 // Try to resolve a single function template specialization. 12981 // This is obligatory. 12982 ExprResult result = Owned(E); 12983 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) { 12984 return result; 12985 12986 // If that failed, try to recover with a call. 12987 } else { 12988 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable), 12989 /*complain*/ true); 12990 return result; 12991 } 12992 } 12993 12994 // Bound member functions. 12995 case BuiltinType::BoundMember: { 12996 ExprResult result = Owned(E); 12997 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function), 12998 /*complain*/ true); 12999 return result; 13000 } 13001 13002 // ARC unbridged casts. 13003 case BuiltinType::ARCUnbridgedCast: { 13004 Expr *realCast = stripARCUnbridgedCast(E); 13005 diagnoseARCUnbridgedCast(realCast); 13006 return Owned(realCast); 13007 } 13008 13009 // Expressions of unknown type. 13010 case BuiltinType::UnknownAny: 13011 return diagnoseUnknownAnyExpr(*this, E); 13012 13013 // Pseudo-objects. 13014 case BuiltinType::PseudoObject: 13015 return checkPseudoObjectRValue(E); 13016 13017 case BuiltinType::BuiltinFn: 13018 Diag(E->getLocStart(), diag::err_builtin_fn_use); 13019 return ExprError(); 13020 13021 // Everything else should be impossible. 13022#define BUILTIN_TYPE(Id, SingletonId) \ 13023 case BuiltinType::Id: 13024#define PLACEHOLDER_TYPE(Id, SingletonId) 13025#include "clang/AST/BuiltinTypes.def" 13026 break; 13027 } 13028 13029 llvm_unreachable("invalid placeholder type!"); 13030} 13031 13032bool Sema::CheckCaseExpression(Expr *E) { 13033 if (E->isTypeDependent()) 13034 return true; 13035 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 13036 return E->getType()->isIntegralOrEnumerationType(); 13037 return false; 13038} 13039 13040/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 13041ExprResult 13042Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 13043 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 13044 "Unknown Objective-C Boolean value!"); 13045 QualType BoolT = Context.ObjCBuiltinBoolTy; 13046 if (!Context.getBOOLDecl()) { 13047 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 13048 Sema::LookupOrdinaryName); 13049 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 13050 NamedDecl *ND = Result.getFoundDecl(); 13051 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 13052 Context.setBOOLDecl(TD); 13053 } 13054 } 13055 if (Context.getBOOLDecl()) 13056 BoolT = Context.getBOOLType(); 13057 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, 13058 BoolT, OpLoc)); 13059} 13060