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" 44 using namespace clang; 45 using namespace sema; 46 47 /// \brief Determine whether the use of this declaration is valid, without 48 /// emitting diagnostics. 49 bool Sema::CanUseDecl(NamedDecl *D) { 50 // See if this is an auto-typed variable whose initializer we are parsing. 51 if (ParsingInitForAutoVars.count(D)) 52 return false; 53 54 // See if this is a deleted function. 55 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 56 if (FD->isDeleted()) 57 return false; 58 59 // 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 74 static 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 83 static 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. 144 void 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. 184 static 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. 202 static 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 247 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 248 const FunctionDecl *First = Cur->getFirstDeclaration(); 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 /// 270 bool 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. 323 std::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. 335 void 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 426 SourceRange 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). 435 ExprResult 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 468 static 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 487 static 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 543 ExprResult 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 635 ExprResult 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. 651 ExprResult 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(). 700 ExprResult 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. 743 Sema::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 787 void 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. 826 ExprResult 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. 889 static 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() 911 static QualType 912 handleComplexFloatToComplexFloatConverstion(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() 932 static 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() 973 static 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() 1020 static 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() 1051 static 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 1082 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1083 1084 namespace { 1085 /// These helper callbacks are placed in an anonymous namespace to 1086 /// permit their use as function template parameters. 1087 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1088 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1089 } 1090 1091 ExprResult 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() 1099 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1100 static 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() 1150 static 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. 1197 QualType 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 1271 ExprResult 1272 Sema::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 1297 ExprResult 1298 Sema::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. 1435 static 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. 1443 static 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 /// 1477 ExprResult 1478 Sema::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 1593 ExprResult 1594 Sema::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. 1603 ExprResult 1604 Sema::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. 1675 void 1676 Sema::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 1701 bool 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 1910 ExprResult 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 type dependent. The 2024 // goal is to postpone name lookup to instantiation time to be able to 2025 // search into the type dependent base classes. 2026 if (getLangOpts().MicrosoftMode) { 2027 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext); 2028 if (MD && MD->getParent()->hasAnyDependentBases()) 2029 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2030 IsAddressOfOperand, TemplateArgs); 2031 } 2032 2033 // Don't diagnose an empty lookup for inline assmebly. 2034 if (IsInlineAsmIdentifier) 2035 return ExprError(); 2036 2037 CorrectionCandidateCallback DefaultValidator; 2038 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator)) 2039 return ExprError(); 2040 2041 assert(!R.empty() && 2042 "DiagnoseEmptyLookup returned false but added no results"); 2043 2044 // If we found an Objective-C instance variable, let 2045 // LookupInObjCMethod build the appropriate expression to 2046 // reference the ivar. 2047 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2048 R.clear(); 2049 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2050 // In a hopelessly buggy code, Objective-C instance variable 2051 // lookup fails and no expression will be built to reference it. 2052 if (!E.isInvalid() && !E.get()) 2053 return ExprError(); 2054 return E; 2055 } 2056 } 2057 } 2058 2059 // This is guaranteed from this point on. 2060 assert(!R.empty() || ADL); 2061 2062 // Check whether this might be a C++ implicit instance member access. 2063 // C++ [class.mfct.non-static]p3: 2064 // When an id-expression that is not part of a class member access 2065 // syntax and not used to form a pointer to member is used in the 2066 // body of a non-static member function of class X, if name lookup 2067 // resolves the name in the id-expression to a non-static non-type 2068 // member of some class C, the id-expression is transformed into a 2069 // class member access expression using (*this) as the 2070 // postfix-expression to the left of the . operator. 2071 // 2072 // But we don't actually need to do this for '&' operands if R 2073 // resolved to a function or overloaded function set, because the 2074 // expression is ill-formed if it actually works out to be a 2075 // non-static member function: 2076 // 2077 // C++ [expr.ref]p4: 2078 // Otherwise, if E1.E2 refers to a non-static member function. . . 2079 // [t]he expression can be used only as the left-hand operand of a 2080 // member function call. 2081 // 2082 // There are other safeguards against such uses, but it's important 2083 // to get this right here so that we don't end up making a 2084 // spuriously dependent expression if we're inside a dependent 2085 // instance method. 2086 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2087 bool MightBeImplicitMember; 2088 if (!IsAddressOfOperand) 2089 MightBeImplicitMember = true; 2090 else if (!SS.isEmpty()) 2091 MightBeImplicitMember = false; 2092 else if (R.isOverloadedResult()) 2093 MightBeImplicitMember = false; 2094 else if (R.isUnresolvableResult()) 2095 MightBeImplicitMember = true; 2096 else 2097 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2098 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2099 isa<MSPropertyDecl>(R.getFoundDecl()); 2100 2101 if (MightBeImplicitMember) 2102 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2103 R, TemplateArgs); 2104 } 2105 2106 if (TemplateArgs || TemplateKWLoc.isValid()) { 2107 2108 // In C++1y, if this is a variable template id, then check it 2109 // in BuildTemplateIdExpr(). 2110 // The single lookup result must be a variable template declaration. 2111 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2112 Id.TemplateId->Kind == TNK_Var_template) { 2113 assert(R.getAsSingle<VarTemplateDecl>() && 2114 "There should only be one declaration found."); 2115 } 2116 2117 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2118 } 2119 2120 return BuildDeclarationNameExpr(SS, R, ADL); 2121 } 2122 2123 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2124 /// declaration name, generally during template instantiation. 2125 /// There's a large number of things which don't need to be done along 2126 /// this path. 2127 ExprResult 2128 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 2129 const DeclarationNameInfo &NameInfo, 2130 bool IsAddressOfOperand) { 2131 DeclContext *DC = computeDeclContext(SS, false); 2132 if (!DC) 2133 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2134 NameInfo, /*TemplateArgs=*/0); 2135 2136 if (RequireCompleteDeclContext(SS, DC)) 2137 return ExprError(); 2138 2139 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2140 LookupQualifiedName(R, DC); 2141 2142 if (R.isAmbiguous()) 2143 return ExprError(); 2144 2145 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2146 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2147 NameInfo, /*TemplateArgs=*/0); 2148 2149 if (R.empty()) { 2150 Diag(NameInfo.getLoc(), diag::err_no_member) 2151 << NameInfo.getName() << DC << SS.getRange(); 2152 return ExprError(); 2153 } 2154 2155 // Defend against this resolving to an implicit member access. We usually 2156 // won't get here if this might be a legitimate a class member (we end up in 2157 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2158 // a pointer-to-member or in an unevaluated context in C++11. 2159 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2160 return BuildPossibleImplicitMemberExpr(SS, 2161 /*TemplateKWLoc=*/SourceLocation(), 2162 R, /*TemplateArgs=*/0); 2163 2164 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2165 } 2166 2167 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2168 /// detected that we're currently inside an ObjC method. Perform some 2169 /// additional lookup. 2170 /// 2171 /// Ideally, most of this would be done by lookup, but there's 2172 /// actually quite a lot of extra work involved. 2173 /// 2174 /// Returns a null sentinel to indicate trivial success. 2175 ExprResult 2176 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2177 IdentifierInfo *II, bool AllowBuiltinCreation) { 2178 SourceLocation Loc = Lookup.getNameLoc(); 2179 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2180 2181 // Check for error condition which is already reported. 2182 if (!CurMethod) 2183 return ExprError(); 2184 2185 // There are two cases to handle here. 1) scoped lookup could have failed, 2186 // in which case we should look for an ivar. 2) scoped lookup could have 2187 // found a decl, but that decl is outside the current instance method (i.e. 2188 // a global variable). In these two cases, we do a lookup for an ivar with 2189 // this name, if the lookup sucedes, we replace it our current decl. 2190 2191 // If we're in a class method, we don't normally want to look for 2192 // ivars. But if we don't find anything else, and there's an 2193 // ivar, that's an error. 2194 bool IsClassMethod = CurMethod->isClassMethod(); 2195 2196 bool LookForIvars; 2197 if (Lookup.empty()) 2198 LookForIvars = true; 2199 else if (IsClassMethod) 2200 LookForIvars = false; 2201 else 2202 LookForIvars = (Lookup.isSingleResult() && 2203 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2204 ObjCInterfaceDecl *IFace = 0; 2205 if (LookForIvars) { 2206 IFace = CurMethod->getClassInterface(); 2207 ObjCInterfaceDecl *ClassDeclared; 2208 ObjCIvarDecl *IV = 0; 2209 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2210 // Diagnose using an ivar in a class method. 2211 if (IsClassMethod) 2212 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2213 << IV->getDeclName()); 2214 2215 // If we're referencing an invalid decl, just return this as a silent 2216 // error node. The error diagnostic was already emitted on the decl. 2217 if (IV->isInvalidDecl()) 2218 return ExprError(); 2219 2220 // Check if referencing a field with __attribute__((deprecated)). 2221 if (DiagnoseUseOfDecl(IV, Loc)) 2222 return ExprError(); 2223 2224 // Diagnose the use of an ivar outside of the declaring class. 2225 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2226 !declaresSameEntity(ClassDeclared, IFace) && 2227 !getLangOpts().DebuggerSupport) 2228 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2229 2230 // FIXME: This should use a new expr for a direct reference, don't 2231 // turn this into Self->ivar, just return a BareIVarExpr or something. 2232 IdentifierInfo &II = Context.Idents.get("self"); 2233 UnqualifiedId SelfName; 2234 SelfName.setIdentifier(&II, SourceLocation()); 2235 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2236 CXXScopeSpec SelfScopeSpec; 2237 SourceLocation TemplateKWLoc; 2238 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2239 SelfName, false, false); 2240 if (SelfExpr.isInvalid()) 2241 return ExprError(); 2242 2243 SelfExpr = DefaultLvalueConversion(SelfExpr.take()); 2244 if (SelfExpr.isInvalid()) 2245 return ExprError(); 2246 2247 MarkAnyDeclReferenced(Loc, IV, true); 2248 2249 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2250 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2251 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2252 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2253 2254 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(), 2255 Loc, IV->getLocation(), 2256 SelfExpr.take(), 2257 true, true); 2258 2259 if (getLangOpts().ObjCAutoRefCount) { 2260 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2261 DiagnosticsEngine::Level Level = 2262 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc); 2263 if (Level != DiagnosticsEngine::Ignored) 2264 recordUseOfEvaluatedWeak(Result); 2265 } 2266 if (CurContext->isClosure()) 2267 Diag(Loc, diag::warn_implicitly_retains_self) 2268 << FixItHint::CreateInsertion(Loc, "self->"); 2269 } 2270 2271 return Owned(Result); 2272 } 2273 } else if (CurMethod->isInstanceMethod()) { 2274 // We should warn if a local variable hides an ivar. 2275 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2276 ObjCInterfaceDecl *ClassDeclared; 2277 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2278 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2279 declaresSameEntity(IFace, ClassDeclared)) 2280 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2281 } 2282 } 2283 } else if (Lookup.isSingleResult() && 2284 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2285 // If accessing a stand-alone ivar in a class method, this is an error. 2286 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2287 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2288 << IV->getDeclName()); 2289 } 2290 2291 if (Lookup.empty() && II && AllowBuiltinCreation) { 2292 // FIXME. Consolidate this with similar code in LookupName. 2293 if (unsigned BuiltinID = II->getBuiltinID()) { 2294 if (!(getLangOpts().CPlusPlus && 2295 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2296 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2297 S, Lookup.isForRedeclaration(), 2298 Lookup.getNameLoc()); 2299 if (D) Lookup.addDecl(D); 2300 } 2301 } 2302 } 2303 // Sentinel value saying that we didn't do anything special. 2304 return Owned((Expr*) 0); 2305 } 2306 2307 /// \brief Cast a base object to a member's actual type. 2308 /// 2309 /// Logically this happens in three phases: 2310 /// 2311 /// * First we cast from the base type to the naming class. 2312 /// The naming class is the class into which we were looking 2313 /// when we found the member; it's the qualifier type if a 2314 /// qualifier was provided, and otherwise it's the base type. 2315 /// 2316 /// * Next we cast from the naming class to the declaring class. 2317 /// If the member we found was brought into a class's scope by 2318 /// a using declaration, this is that class; otherwise it's 2319 /// the class declaring the member. 2320 /// 2321 /// * Finally we cast from the declaring class to the "true" 2322 /// declaring class of the member. This conversion does not 2323 /// obey access control. 2324 ExprResult 2325 Sema::PerformObjectMemberConversion(Expr *From, 2326 NestedNameSpecifier *Qualifier, 2327 NamedDecl *FoundDecl, 2328 NamedDecl *Member) { 2329 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2330 if (!RD) 2331 return Owned(From); 2332 2333 QualType DestRecordType; 2334 QualType DestType; 2335 QualType FromRecordType; 2336 QualType FromType = From->getType(); 2337 bool PointerConversions = false; 2338 if (isa<FieldDecl>(Member)) { 2339 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2340 2341 if (FromType->getAs<PointerType>()) { 2342 DestType = Context.getPointerType(DestRecordType); 2343 FromRecordType = FromType->getPointeeType(); 2344 PointerConversions = true; 2345 } else { 2346 DestType = DestRecordType; 2347 FromRecordType = FromType; 2348 } 2349 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2350 if (Method->isStatic()) 2351 return Owned(From); 2352 2353 DestType = Method->getThisType(Context); 2354 DestRecordType = DestType->getPointeeType(); 2355 2356 if (FromType->getAs<PointerType>()) { 2357 FromRecordType = FromType->getPointeeType(); 2358 PointerConversions = true; 2359 } else { 2360 FromRecordType = FromType; 2361 DestType = DestRecordType; 2362 } 2363 } else { 2364 // No conversion necessary. 2365 return Owned(From); 2366 } 2367 2368 if (DestType->isDependentType() || FromType->isDependentType()) 2369 return Owned(From); 2370 2371 // If the unqualified types are the same, no conversion is necessary. 2372 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2373 return Owned(From); 2374 2375 SourceRange FromRange = From->getSourceRange(); 2376 SourceLocation FromLoc = FromRange.getBegin(); 2377 2378 ExprValueKind VK = From->getValueKind(); 2379 2380 // C++ [class.member.lookup]p8: 2381 // [...] Ambiguities can often be resolved by qualifying a name with its 2382 // class name. 2383 // 2384 // If the member was a qualified name and the qualified referred to a 2385 // specific base subobject type, we'll cast to that intermediate type 2386 // first and then to the object in which the member is declared. That allows 2387 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2388 // 2389 // class Base { public: int x; }; 2390 // class Derived1 : public Base { }; 2391 // class Derived2 : public Base { }; 2392 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2393 // 2394 // void VeryDerived::f() { 2395 // x = 17; // error: ambiguous base subobjects 2396 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2397 // } 2398 if (Qualifier && Qualifier->getAsType()) { 2399 QualType QType = QualType(Qualifier->getAsType(), 0); 2400 assert(QType->isRecordType() && "lookup done with non-record type"); 2401 2402 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2403 2404 // In C++98, the qualifier type doesn't actually have to be a base 2405 // type of the object type, in which case we just ignore it. 2406 // Otherwise build the appropriate casts. 2407 if (IsDerivedFrom(FromRecordType, QRecordType)) { 2408 CXXCastPath BasePath; 2409 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2410 FromLoc, FromRange, &BasePath)) 2411 return ExprError(); 2412 2413 if (PointerConversions) 2414 QType = Context.getPointerType(QType); 2415 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2416 VK, &BasePath).take(); 2417 2418 FromType = QType; 2419 FromRecordType = QRecordType; 2420 2421 // If the qualifier type was the same as the destination type, 2422 // we're done. 2423 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2424 return Owned(From); 2425 } 2426 } 2427 2428 bool IgnoreAccess = false; 2429 2430 // If we actually found the member through a using declaration, cast 2431 // down to the using declaration's type. 2432 // 2433 // Pointer equality is fine here because only one declaration of a 2434 // class ever has member declarations. 2435 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2436 assert(isa<UsingShadowDecl>(FoundDecl)); 2437 QualType URecordType = Context.getTypeDeclType( 2438 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2439 2440 // We only need to do this if the naming-class to declaring-class 2441 // conversion is non-trivial. 2442 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2443 assert(IsDerivedFrom(FromRecordType, URecordType)); 2444 CXXCastPath BasePath; 2445 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2446 FromLoc, FromRange, &BasePath)) 2447 return ExprError(); 2448 2449 QualType UType = URecordType; 2450 if (PointerConversions) 2451 UType = Context.getPointerType(UType); 2452 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2453 VK, &BasePath).take(); 2454 FromType = UType; 2455 FromRecordType = URecordType; 2456 } 2457 2458 // We don't do access control for the conversion from the 2459 // declaring class to the true declaring class. 2460 IgnoreAccess = true; 2461 } 2462 2463 CXXCastPath BasePath; 2464 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2465 FromLoc, FromRange, &BasePath, 2466 IgnoreAccess)) 2467 return ExprError(); 2468 2469 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2470 VK, &BasePath); 2471 } 2472 2473 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2474 const LookupResult &R, 2475 bool HasTrailingLParen) { 2476 // Only when used directly as the postfix-expression of a call. 2477 if (!HasTrailingLParen) 2478 return false; 2479 2480 // Never if a scope specifier was provided. 2481 if (SS.isSet()) 2482 return false; 2483 2484 // Only in C++ or ObjC++. 2485 if (!getLangOpts().CPlusPlus) 2486 return false; 2487 2488 // Turn off ADL when we find certain kinds of declarations during 2489 // normal lookup: 2490 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2491 NamedDecl *D = *I; 2492 2493 // C++0x [basic.lookup.argdep]p3: 2494 // -- a declaration of a class member 2495 // Since using decls preserve this property, we check this on the 2496 // original decl. 2497 if (D->isCXXClassMember()) 2498 return false; 2499 2500 // C++0x [basic.lookup.argdep]p3: 2501 // -- a block-scope function declaration that is not a 2502 // using-declaration 2503 // NOTE: we also trigger this for function templates (in fact, we 2504 // don't check the decl type at all, since all other decl types 2505 // turn off ADL anyway). 2506 if (isa<UsingShadowDecl>(D)) 2507 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2508 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2509 return false; 2510 2511 // C++0x [basic.lookup.argdep]p3: 2512 // -- a declaration that is neither a function or a function 2513 // template 2514 // And also for builtin functions. 2515 if (isa<FunctionDecl>(D)) { 2516 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2517 2518 // But also builtin functions. 2519 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2520 return false; 2521 } else if (!isa<FunctionTemplateDecl>(D)) 2522 return false; 2523 } 2524 2525 return true; 2526 } 2527 2528 2529 /// Diagnoses obvious problems with the use of the given declaration 2530 /// as an expression. This is only actually called for lookups that 2531 /// were not overloaded, and it doesn't promise that the declaration 2532 /// will in fact be used. 2533 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2534 if (isa<TypedefNameDecl>(D)) { 2535 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2536 return true; 2537 } 2538 2539 if (isa<ObjCInterfaceDecl>(D)) { 2540 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2541 return true; 2542 } 2543 2544 if (isa<NamespaceDecl>(D)) { 2545 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2546 return true; 2547 } 2548 2549 return false; 2550 } 2551 2552 ExprResult 2553 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2554 LookupResult &R, 2555 bool NeedsADL) { 2556 // If this is a single, fully-resolved result and we don't need ADL, 2557 // just build an ordinary singleton decl ref. 2558 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2559 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2560 R.getRepresentativeDecl()); 2561 2562 // We only need to check the declaration if there's exactly one 2563 // result, because in the overloaded case the results can only be 2564 // functions and function templates. 2565 if (R.isSingleResult() && 2566 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2567 return ExprError(); 2568 2569 // Otherwise, just build an unresolved lookup expression. Suppress 2570 // any lookup-related diagnostics; we'll hash these out later, when 2571 // we've picked a target. 2572 R.suppressDiagnostics(); 2573 2574 UnresolvedLookupExpr *ULE 2575 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2576 SS.getWithLocInContext(Context), 2577 R.getLookupNameInfo(), 2578 NeedsADL, R.isOverloadedResult(), 2579 R.begin(), R.end()); 2580 2581 return Owned(ULE); 2582 } 2583 2584 /// \brief Complete semantic analysis for a reference to the given declaration. 2585 ExprResult Sema::BuildDeclarationNameExpr( 2586 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2587 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs) { 2588 assert(D && "Cannot refer to a NULL declaration"); 2589 assert(!isa<FunctionTemplateDecl>(D) && 2590 "Cannot refer unambiguously to a function template"); 2591 2592 SourceLocation Loc = NameInfo.getLoc(); 2593 if (CheckDeclInExpr(*this, Loc, D)) 2594 return ExprError(); 2595 2596 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2597 // Specifically diagnose references to class templates that are missing 2598 // a template argument list. 2599 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2600 << Template << SS.getRange(); 2601 Diag(Template->getLocation(), diag::note_template_decl_here); 2602 return ExprError(); 2603 } 2604 2605 // Make sure that we're referring to a value. 2606 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2607 if (!VD) { 2608 Diag(Loc, diag::err_ref_non_value) 2609 << D << SS.getRange(); 2610 Diag(D->getLocation(), diag::note_declared_at); 2611 return ExprError(); 2612 } 2613 2614 // Check whether this declaration can be used. Note that we suppress 2615 // this check when we're going to perform argument-dependent lookup 2616 // on this function name, because this might not be the function 2617 // that overload resolution actually selects. 2618 if (DiagnoseUseOfDecl(VD, Loc)) 2619 return ExprError(); 2620 2621 // Only create DeclRefExpr's for valid Decl's. 2622 if (VD->isInvalidDecl()) 2623 return ExprError(); 2624 2625 // Handle members of anonymous structs and unions. If we got here, 2626 // and the reference is to a class member indirect field, then this 2627 // must be the subject of a pointer-to-member expression. 2628 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2629 if (!indirectField->isCXXClassMember()) 2630 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2631 indirectField); 2632 2633 { 2634 QualType type = VD->getType(); 2635 ExprValueKind valueKind = VK_RValue; 2636 2637 switch (D->getKind()) { 2638 // Ignore all the non-ValueDecl kinds. 2639 #define ABSTRACT_DECL(kind) 2640 #define VALUE(type, base) 2641 #define DECL(type, base) \ 2642 case Decl::type: 2643 #include "clang/AST/DeclNodes.inc" 2644 llvm_unreachable("invalid value decl kind"); 2645 2646 // These shouldn't make it here. 2647 case Decl::ObjCAtDefsField: 2648 case Decl::ObjCIvar: 2649 llvm_unreachable("forming non-member reference to ivar?"); 2650 2651 // Enum constants are always r-values and never references. 2652 // Unresolved using declarations are dependent. 2653 case Decl::EnumConstant: 2654 case Decl::UnresolvedUsingValue: 2655 valueKind = VK_RValue; 2656 break; 2657 2658 // Fields and indirect fields that got here must be for 2659 // pointer-to-member expressions; we just call them l-values for 2660 // internal consistency, because this subexpression doesn't really 2661 // exist in the high-level semantics. 2662 case Decl::Field: 2663 case Decl::IndirectField: 2664 assert(getLangOpts().CPlusPlus && 2665 "building reference to field in C?"); 2666 2667 // These can't have reference type in well-formed programs, but 2668 // for internal consistency we do this anyway. 2669 type = type.getNonReferenceType(); 2670 valueKind = VK_LValue; 2671 break; 2672 2673 // Non-type template parameters are either l-values or r-values 2674 // depending on the type. 2675 case Decl::NonTypeTemplateParm: { 2676 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2677 type = reftype->getPointeeType(); 2678 valueKind = VK_LValue; // even if the parameter is an r-value reference 2679 break; 2680 } 2681 2682 // For non-references, we need to strip qualifiers just in case 2683 // the template parameter was declared as 'const int' or whatever. 2684 valueKind = VK_RValue; 2685 type = type.getUnqualifiedType(); 2686 break; 2687 } 2688 2689 case Decl::Var: 2690 case Decl::VarTemplateSpecialization: 2691 case Decl::VarTemplatePartialSpecialization: 2692 // In C, "extern void blah;" is valid and is an r-value. 2693 if (!getLangOpts().CPlusPlus && 2694 !type.hasQualifiers() && 2695 type->isVoidType()) { 2696 valueKind = VK_RValue; 2697 break; 2698 } 2699 // fallthrough 2700 2701 case Decl::ImplicitParam: 2702 case Decl::ParmVar: { 2703 // These are always l-values. 2704 valueKind = VK_LValue; 2705 type = type.getNonReferenceType(); 2706 2707 // FIXME: Does the addition of const really only apply in 2708 // potentially-evaluated contexts? Since the variable isn't actually 2709 // captured in an unevaluated context, it seems that the answer is no. 2710 if (!isUnevaluatedContext()) { 2711 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2712 if (!CapturedType.isNull()) 2713 type = CapturedType; 2714 } 2715 2716 break; 2717 } 2718 2719 case Decl::Function: { 2720 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2721 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2722 type = Context.BuiltinFnTy; 2723 valueKind = VK_RValue; 2724 break; 2725 } 2726 } 2727 2728 const FunctionType *fty = type->castAs<FunctionType>(); 2729 2730 // If we're referring to a function with an __unknown_anytype 2731 // result type, make the entire expression __unknown_anytype. 2732 if (fty->getResultType() == Context.UnknownAnyTy) { 2733 type = Context.UnknownAnyTy; 2734 valueKind = VK_RValue; 2735 break; 2736 } 2737 2738 // Functions are l-values in C++. 2739 if (getLangOpts().CPlusPlus) { 2740 valueKind = VK_LValue; 2741 break; 2742 } 2743 2744 // C99 DR 316 says that, if a function type comes from a 2745 // function definition (without a prototype), that type is only 2746 // used for checking compatibility. Therefore, when referencing 2747 // the function, we pretend that we don't have the full function 2748 // type. 2749 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2750 isa<FunctionProtoType>(fty)) 2751 type = Context.getFunctionNoProtoType(fty->getResultType(), 2752 fty->getExtInfo()); 2753 2754 // Functions are r-values in C. 2755 valueKind = VK_RValue; 2756 break; 2757 } 2758 2759 case Decl::MSProperty: 2760 valueKind = VK_LValue; 2761 break; 2762 2763 case Decl::CXXMethod: 2764 // If we're referring to a method with an __unknown_anytype 2765 // result type, make the entire expression __unknown_anytype. 2766 // This should only be possible with a type written directly. 2767 if (const FunctionProtoType *proto 2768 = dyn_cast<FunctionProtoType>(VD->getType())) 2769 if (proto->getResultType() == Context.UnknownAnyTy) { 2770 type = Context.UnknownAnyTy; 2771 valueKind = VK_RValue; 2772 break; 2773 } 2774 2775 // C++ methods are l-values if static, r-values if non-static. 2776 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2777 valueKind = VK_LValue; 2778 break; 2779 } 2780 // fallthrough 2781 2782 case Decl::CXXConversion: 2783 case Decl::CXXDestructor: 2784 case Decl::CXXConstructor: 2785 valueKind = VK_RValue; 2786 break; 2787 } 2788 2789 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 2790 TemplateArgs); 2791 } 2792 } 2793 2794 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 2795 PredefinedExpr::IdentType IT) { 2796 // Pick the current block, lambda, captured statement or function. 2797 Decl *currentDecl = 0; 2798 if (const BlockScopeInfo *BSI = getCurBlock()) 2799 currentDecl = BSI->TheDecl; 2800 else if (const LambdaScopeInfo *LSI = getCurLambda()) 2801 currentDecl = LSI->CallOperator; 2802 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 2803 currentDecl = CSI->TheCapturedDecl; 2804 else 2805 currentDecl = getCurFunctionOrMethodDecl(); 2806 2807 if (!currentDecl) { 2808 Diag(Loc, diag::ext_predef_outside_function); 2809 currentDecl = Context.getTranslationUnitDecl(); 2810 } 2811 2812 QualType ResTy; 2813 if (cast<DeclContext>(currentDecl)->isDependentContext()) 2814 ResTy = Context.DependentTy; 2815 else { 2816 // Pre-defined identifiers are of type char[x], where x is the length of 2817 // the string. 2818 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length(); 2819 2820 llvm::APInt LengthI(32, Length + 1); 2821 if (IT == PredefinedExpr::LFunction) 2822 ResTy = Context.WideCharTy.withConst(); 2823 else 2824 ResTy = Context.CharTy.withConst(); 2825 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); 2826 } 2827 2828 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT)); 2829 } 2830 2831 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 2832 PredefinedExpr::IdentType IT; 2833 2834 switch (Kind) { 2835 default: llvm_unreachable("Unknown simple primary expr!"); 2836 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 2837 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 2838 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 2839 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 2840 } 2841 2842 return BuildPredefinedExpr(Loc, IT); 2843 } 2844 2845 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 2846 SmallString<16> CharBuffer; 2847 bool Invalid = false; 2848 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 2849 if (Invalid) 2850 return ExprError(); 2851 2852 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 2853 PP, Tok.getKind()); 2854 if (Literal.hadError()) 2855 return ExprError(); 2856 2857 QualType Ty; 2858 if (Literal.isWide()) 2859 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 2860 else if (Literal.isUTF16()) 2861 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 2862 else if (Literal.isUTF32()) 2863 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 2864 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 2865 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 2866 else 2867 Ty = Context.CharTy; // 'x' -> char in C++ 2868 2869 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 2870 if (Literal.isWide()) 2871 Kind = CharacterLiteral::Wide; 2872 else if (Literal.isUTF16()) 2873 Kind = CharacterLiteral::UTF16; 2874 else if (Literal.isUTF32()) 2875 Kind = CharacterLiteral::UTF32; 2876 2877 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 2878 Tok.getLocation()); 2879 2880 if (Literal.getUDSuffix().empty()) 2881 return Owned(Lit); 2882 2883 // We're building a user-defined literal. 2884 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 2885 SourceLocation UDSuffixLoc = 2886 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 2887 2888 // Make sure we're allowed user-defined literals here. 2889 if (!UDLScope) 2890 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 2891 2892 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 2893 // operator "" X (ch) 2894 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 2895 Lit, Tok.getLocation()); 2896 } 2897 2898 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 2899 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 2900 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 2901 Context.IntTy, Loc)); 2902 } 2903 2904 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 2905 QualType Ty, SourceLocation Loc) { 2906 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 2907 2908 using llvm::APFloat; 2909 APFloat Val(Format); 2910 2911 APFloat::opStatus result = Literal.GetFloatValue(Val); 2912 2913 // Overflow is always an error, but underflow is only an error if 2914 // we underflowed to zero (APFloat reports denormals as underflow). 2915 if ((result & APFloat::opOverflow) || 2916 ((result & APFloat::opUnderflow) && Val.isZero())) { 2917 unsigned diagnostic; 2918 SmallString<20> buffer; 2919 if (result & APFloat::opOverflow) { 2920 diagnostic = diag::warn_float_overflow; 2921 APFloat::getLargest(Format).toString(buffer); 2922 } else { 2923 diagnostic = diag::warn_float_underflow; 2924 APFloat::getSmallest(Format).toString(buffer); 2925 } 2926 2927 S.Diag(Loc, diagnostic) 2928 << Ty 2929 << StringRef(buffer.data(), buffer.size()); 2930 } 2931 2932 bool isExact = (result == APFloat::opOK); 2933 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 2934 } 2935 2936 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 2937 // Fast path for a single digit (which is quite common). A single digit 2938 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 2939 if (Tok.getLength() == 1) { 2940 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 2941 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 2942 } 2943 2944 SmallString<128> SpellingBuffer; 2945 // NumericLiteralParser wants to overread by one character. Add padding to 2946 // the buffer in case the token is copied to the buffer. If getSpelling() 2947 // returns a StringRef to the memory buffer, it should have a null char at 2948 // the EOF, so it is also safe. 2949 SpellingBuffer.resize(Tok.getLength() + 1); 2950 2951 // Get the spelling of the token, which eliminates trigraphs, etc. 2952 bool Invalid = false; 2953 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 2954 if (Invalid) 2955 return ExprError(); 2956 2957 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 2958 if (Literal.hadError) 2959 return ExprError(); 2960 2961 if (Literal.hasUDSuffix()) { 2962 // We're building a user-defined literal. 2963 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 2964 SourceLocation UDSuffixLoc = 2965 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 2966 2967 // Make sure we're allowed user-defined literals here. 2968 if (!UDLScope) 2969 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 2970 2971 QualType CookedTy; 2972 if (Literal.isFloatingLiteral()) { 2973 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 2974 // long double, the literal is treated as a call of the form 2975 // operator "" X (f L) 2976 CookedTy = Context.LongDoubleTy; 2977 } else { 2978 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 2979 // unsigned long long, the literal is treated as a call of the form 2980 // operator "" X (n ULL) 2981 CookedTy = Context.UnsignedLongLongTy; 2982 } 2983 2984 DeclarationName OpName = 2985 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 2986 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 2987 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 2988 2989 SourceLocation TokLoc = Tok.getLocation(); 2990 2991 // Perform literal operator lookup to determine if we're building a raw 2992 // literal or a cooked one. 2993 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 2994 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 2995 /*AllowRaw*/true, /*AllowTemplate*/true, 2996 /*AllowStringTemplate*/false)) { 2997 case LOLR_Error: 2998 return ExprError(); 2999 3000 case LOLR_Cooked: { 3001 Expr *Lit; 3002 if (Literal.isFloatingLiteral()) { 3003 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3004 } else { 3005 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3006 if (Literal.GetIntegerValue(ResultVal)) 3007 Diag(Tok.getLocation(), diag::err_integer_too_large); 3008 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3009 Tok.getLocation()); 3010 } 3011 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3012 } 3013 3014 case LOLR_Raw: { 3015 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3016 // literal is treated as a call of the form 3017 // operator "" X ("n") 3018 unsigned Length = Literal.getUDSuffixOffset(); 3019 QualType StrTy = Context.getConstantArrayType( 3020 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3021 ArrayType::Normal, 0); 3022 Expr *Lit = StringLiteral::Create( 3023 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3024 /*Pascal*/false, StrTy, &TokLoc, 1); 3025 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3026 } 3027 3028 case LOLR_Template: { 3029 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3030 // template), L is treated as a call fo the form 3031 // operator "" X <'c1', 'c2', ... 'ck'>() 3032 // where n is the source character sequence c1 c2 ... ck. 3033 TemplateArgumentListInfo ExplicitArgs; 3034 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3035 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3036 llvm::APSInt Value(CharBits, CharIsUnsigned); 3037 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3038 Value = TokSpelling[I]; 3039 TemplateArgument Arg(Context, Value, Context.CharTy); 3040 TemplateArgumentLocInfo ArgInfo; 3041 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3042 } 3043 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3044 &ExplicitArgs); 3045 } 3046 case LOLR_StringTemplate: 3047 llvm_unreachable("unexpected literal operator lookup result"); 3048 } 3049 } 3050 3051 Expr *Res; 3052 3053 if (Literal.isFloatingLiteral()) { 3054 QualType Ty; 3055 if (Literal.isFloat) 3056 Ty = Context.FloatTy; 3057 else if (!Literal.isLong) 3058 Ty = Context.DoubleTy; 3059 else 3060 Ty = Context.LongDoubleTy; 3061 3062 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3063 3064 if (Ty == Context.DoubleTy) { 3065 if (getLangOpts().SinglePrecisionConstants) { 3066 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 3067 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) { 3068 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3069 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 3070 } 3071 } 3072 } else if (!Literal.isIntegerLiteral()) { 3073 return ExprError(); 3074 } else { 3075 QualType Ty; 3076 3077 // 'long long' is a C99 or C++11 feature. 3078 if (!getLangOpts().C99 && Literal.isLongLong) { 3079 if (getLangOpts().CPlusPlus) 3080 Diag(Tok.getLocation(), 3081 getLangOpts().CPlusPlus11 ? 3082 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3083 else 3084 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3085 } 3086 3087 // Get the value in the widest-possible width. 3088 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3089 // The microsoft literal suffix extensions support 128-bit literals, which 3090 // may be wider than [u]intmax_t. 3091 // FIXME: Actually, they don't. We seem to have accidentally invented the 3092 // i128 suffix. 3093 if (Literal.isMicrosoftInteger && MaxWidth < 128 && 3094 PP.getTargetInfo().hasInt128Type()) 3095 MaxWidth = 128; 3096 llvm::APInt ResultVal(MaxWidth, 0); 3097 3098 if (Literal.GetIntegerValue(ResultVal)) { 3099 // If this value didn't fit into uintmax_t, error and force to ull. 3100 Diag(Tok.getLocation(), diag::err_integer_too_large); 3101 Ty = Context.UnsignedLongLongTy; 3102 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3103 "long long is not intmax_t?"); 3104 } else { 3105 // If this value fits into a ULL, try to figure out what else it fits into 3106 // according to the rules of C99 6.4.4.1p5. 3107 3108 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3109 // be an unsigned int. 3110 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3111 3112 // Check from smallest to largest, picking the smallest type we can. 3113 unsigned Width = 0; 3114 if (!Literal.isLong && !Literal.isLongLong) { 3115 // Are int/unsigned possibilities? 3116 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3117 3118 // Does it fit in a unsigned int? 3119 if (ResultVal.isIntN(IntSize)) { 3120 // Does it fit in a signed int? 3121 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3122 Ty = Context.IntTy; 3123 else if (AllowUnsigned) 3124 Ty = Context.UnsignedIntTy; 3125 Width = IntSize; 3126 } 3127 } 3128 3129 // Are long/unsigned long possibilities? 3130 if (Ty.isNull() && !Literal.isLongLong) { 3131 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3132 3133 // Does it fit in a unsigned long? 3134 if (ResultVal.isIntN(LongSize)) { 3135 // Does it fit in a signed long? 3136 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3137 Ty = Context.LongTy; 3138 else if (AllowUnsigned) 3139 Ty = Context.UnsignedLongTy; 3140 Width = LongSize; 3141 } 3142 } 3143 3144 // Check long long if needed. 3145 if (Ty.isNull()) { 3146 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3147 3148 // Does it fit in a unsigned long long? 3149 if (ResultVal.isIntN(LongLongSize)) { 3150 // Does it fit in a signed long long? 3151 // To be compatible with MSVC, hex integer literals ending with the 3152 // LL or i64 suffix are always signed in Microsoft mode. 3153 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3154 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 3155 Ty = Context.LongLongTy; 3156 else if (AllowUnsigned) 3157 Ty = Context.UnsignedLongLongTy; 3158 Width = LongLongSize; 3159 } 3160 } 3161 3162 // If it doesn't fit in unsigned long long, and we're using Microsoft 3163 // extensions, then its a 128-bit integer literal. 3164 if (Ty.isNull() && Literal.isMicrosoftInteger && 3165 PP.getTargetInfo().hasInt128Type()) { 3166 if (Literal.isUnsigned) 3167 Ty = Context.UnsignedInt128Ty; 3168 else 3169 Ty = Context.Int128Ty; 3170 Width = 128; 3171 } 3172 3173 // If we still couldn't decide a type, we probably have something that 3174 // does not fit in a signed long long, but has no U suffix. 3175 if (Ty.isNull()) { 3176 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed); 3177 Ty = Context.UnsignedLongLongTy; 3178 Width = Context.getTargetInfo().getLongLongWidth(); 3179 } 3180 3181 if (ResultVal.getBitWidth() != Width) 3182 ResultVal = ResultVal.trunc(Width); 3183 } 3184 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3185 } 3186 3187 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3188 if (Literal.isImaginary) 3189 Res = new (Context) ImaginaryLiteral(Res, 3190 Context.getComplexType(Res->getType())); 3191 3192 return Owned(Res); 3193 } 3194 3195 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3196 assert((E != 0) && "ActOnParenExpr() missing expr"); 3197 return Owned(new (Context) ParenExpr(L, R, E)); 3198 } 3199 3200 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3201 SourceLocation Loc, 3202 SourceRange ArgRange) { 3203 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3204 // scalar or vector data type argument..." 3205 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3206 // type (C99 6.2.5p18) or void. 3207 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3208 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3209 << T << ArgRange; 3210 return true; 3211 } 3212 3213 assert((T->isVoidType() || !T->isIncompleteType()) && 3214 "Scalar types should always be complete"); 3215 return false; 3216 } 3217 3218 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3219 SourceLocation Loc, 3220 SourceRange ArgRange, 3221 UnaryExprOrTypeTrait TraitKind) { 3222 // Invalid types must be hard errors for SFINAE in C++. 3223 if (S.LangOpts.CPlusPlus) 3224 return true; 3225 3226 // C99 6.5.3.4p1: 3227 if (T->isFunctionType() && 3228 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3229 // sizeof(function)/alignof(function) is allowed as an extension. 3230 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3231 << TraitKind << ArgRange; 3232 return false; 3233 } 3234 3235 // Allow sizeof(void)/alignof(void) as an extension. 3236 if (T->isVoidType()) { 3237 S.Diag(Loc, diag::ext_sizeof_alignof_void_type) << TraitKind << ArgRange; 3238 return false; 3239 } 3240 3241 return true; 3242 } 3243 3244 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3245 SourceLocation Loc, 3246 SourceRange ArgRange, 3247 UnaryExprOrTypeTrait TraitKind) { 3248 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3249 // runtime doesn't allow it. 3250 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3251 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3252 << T << (TraitKind == UETT_SizeOf) 3253 << ArgRange; 3254 return true; 3255 } 3256 3257 return false; 3258 } 3259 3260 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3261 /// pointer type is equal to T) and emit a warning if it is. 3262 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3263 Expr *E) { 3264 // Don't warn if the operation changed the type. 3265 if (T != E->getType()) 3266 return; 3267 3268 // Now look for array decays. 3269 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3270 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3271 return; 3272 3273 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3274 << ICE->getType() 3275 << ICE->getSubExpr()->getType(); 3276 } 3277 3278 /// \brief Check the constrains on expression operands to unary type expression 3279 /// and type traits. 3280 /// 3281 /// Completes any types necessary and validates the constraints on the operand 3282 /// expression. The logic mostly mirrors the type-based overload, but may modify 3283 /// the expression as it completes the type for that expression through template 3284 /// instantiation, etc. 3285 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3286 UnaryExprOrTypeTrait ExprKind) { 3287 QualType ExprTy = E->getType(); 3288 assert(!ExprTy->isReferenceType()); 3289 3290 if (ExprKind == UETT_VecStep) 3291 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3292 E->getSourceRange()); 3293 3294 // Whitelist some types as extensions 3295 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3296 E->getSourceRange(), ExprKind)) 3297 return false; 3298 3299 if (RequireCompleteExprType(E, 3300 diag::err_sizeof_alignof_incomplete_type, 3301 ExprKind, E->getSourceRange())) 3302 return true; 3303 3304 // Completing the expression's type may have changed it. 3305 ExprTy = E->getType(); 3306 assert(!ExprTy->isReferenceType()); 3307 3308 if (ExprTy->isFunctionType()) { 3309 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3310 << ExprKind << E->getSourceRange(); 3311 return true; 3312 } 3313 3314 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3315 E->getSourceRange(), ExprKind)) 3316 return true; 3317 3318 if (ExprKind == UETT_SizeOf) { 3319 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3320 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3321 QualType OType = PVD->getOriginalType(); 3322 QualType Type = PVD->getType(); 3323 if (Type->isPointerType() && OType->isArrayType()) { 3324 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3325 << Type << OType; 3326 Diag(PVD->getLocation(), diag::note_declared_at); 3327 } 3328 } 3329 } 3330 3331 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3332 // decays into a pointer and returns an unintended result. This is most 3333 // likely a typo for "sizeof(array) op x". 3334 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3335 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3336 BO->getLHS()); 3337 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3338 BO->getRHS()); 3339 } 3340 } 3341 3342 return false; 3343 } 3344 3345 /// \brief Check the constraints on operands to unary expression and type 3346 /// traits. 3347 /// 3348 /// This will complete any types necessary, and validate the various constraints 3349 /// on those operands. 3350 /// 3351 /// The UsualUnaryConversions() function is *not* called by this routine. 3352 /// C99 6.3.2.1p[2-4] all state: 3353 /// Except when it is the operand of the sizeof operator ... 3354 /// 3355 /// C++ [expr.sizeof]p4 3356 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3357 /// standard conversions are not applied to the operand of sizeof. 3358 /// 3359 /// This policy is followed for all of the unary trait expressions. 3360 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3361 SourceLocation OpLoc, 3362 SourceRange ExprRange, 3363 UnaryExprOrTypeTrait ExprKind) { 3364 if (ExprType->isDependentType()) 3365 return false; 3366 3367 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 3368 // the result is the size of the referenced type." 3369 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 3370 // result shall be the alignment of the referenced type." 3371 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3372 ExprType = Ref->getPointeeType(); 3373 3374 if (ExprKind == UETT_VecStep) 3375 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3376 3377 // Whitelist some types as extensions 3378 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3379 ExprKind)) 3380 return false; 3381 3382 if (RequireCompleteType(OpLoc, ExprType, 3383 diag::err_sizeof_alignof_incomplete_type, 3384 ExprKind, ExprRange)) 3385 return true; 3386 3387 if (ExprType->isFunctionType()) { 3388 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3389 << ExprKind << ExprRange; 3390 return true; 3391 } 3392 3393 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3394 ExprKind)) 3395 return true; 3396 3397 return false; 3398 } 3399 3400 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3401 E = E->IgnoreParens(); 3402 3403 // Cannot know anything else if the expression is dependent. 3404 if (E->isTypeDependent()) 3405 return false; 3406 3407 if (E->getObjectKind() == OK_BitField) { 3408 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) 3409 << 1 << E->getSourceRange(); 3410 return true; 3411 } 3412 3413 ValueDecl *D = 0; 3414 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3415 D = DRE->getDecl(); 3416 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3417 D = ME->getMemberDecl(); 3418 } 3419 3420 // If it's a field, require the containing struct to have a 3421 // complete definition so that we can compute the layout. 3422 // 3423 // This requires a very particular set of circumstances. For a 3424 // field to be contained within an incomplete type, we must in the 3425 // process of parsing that type. To have an expression refer to a 3426 // field, it must be an id-expression or a member-expression, but 3427 // the latter are always ill-formed when the base type is 3428 // incomplete, including only being partially complete. An 3429 // id-expression can never refer to a field in C because fields 3430 // are not in the ordinary namespace. In C++, an id-expression 3431 // can implicitly be a member access, but only if there's an 3432 // implicit 'this' value, and all such contexts are subject to 3433 // delayed parsing --- except for trailing return types in C++11. 3434 // And if an id-expression referring to a field occurs in a 3435 // context that lacks a 'this' value, it's ill-formed --- except, 3436 // agian, in C++11, where such references are allowed in an 3437 // unevaluated context. So C++11 introduces some new complexity. 3438 // 3439 // For the record, since __alignof__ on expressions is a GCC 3440 // extension, GCC seems to permit this but always gives the 3441 // nonsensical answer 0. 3442 // 3443 // We don't really need the layout here --- we could instead just 3444 // directly check for all the appropriate alignment-lowing 3445 // attributes --- but that would require duplicating a lot of 3446 // logic that just isn't worth duplicating for such a marginal 3447 // use-case. 3448 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3449 // Fast path this check, since we at least know the record has a 3450 // definition if we can find a member of it. 3451 if (!FD->getParent()->isCompleteDefinition()) { 3452 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3453 << E->getSourceRange(); 3454 return true; 3455 } 3456 3457 // Otherwise, if it's a field, and the field doesn't have 3458 // reference type, then it must have a complete type (or be a 3459 // flexible array member, which we explicitly want to 3460 // white-list anyway), which makes the following checks trivial. 3461 if (!FD->getType()->isReferenceType()) 3462 return false; 3463 } 3464 3465 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3466 } 3467 3468 bool Sema::CheckVecStepExpr(Expr *E) { 3469 E = E->IgnoreParens(); 3470 3471 // Cannot know anything else if the expression is dependent. 3472 if (E->isTypeDependent()) 3473 return false; 3474 3475 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3476 } 3477 3478 /// \brief Build a sizeof or alignof expression given a type operand. 3479 ExprResult 3480 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3481 SourceLocation OpLoc, 3482 UnaryExprOrTypeTrait ExprKind, 3483 SourceRange R) { 3484 if (!TInfo) 3485 return ExprError(); 3486 3487 QualType T = TInfo->getType(); 3488 3489 if (!T->isDependentType() && 3490 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3491 return ExprError(); 3492 3493 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3494 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo, 3495 Context.getSizeType(), 3496 OpLoc, R.getEnd())); 3497 } 3498 3499 /// \brief Build a sizeof or alignof expression given an expression 3500 /// operand. 3501 ExprResult 3502 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3503 UnaryExprOrTypeTrait ExprKind) { 3504 ExprResult PE = CheckPlaceholderExpr(E); 3505 if (PE.isInvalid()) 3506 return ExprError(); 3507 3508 E = PE.get(); 3509 3510 // Verify that the operand is valid. 3511 bool isInvalid = false; 3512 if (E->isTypeDependent()) { 3513 // Delay type-checking for type-dependent expressions. 3514 } else if (ExprKind == UETT_AlignOf) { 3515 isInvalid = CheckAlignOfExpr(*this, E); 3516 } else if (ExprKind == UETT_VecStep) { 3517 isInvalid = CheckVecStepExpr(E); 3518 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 3519 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0; 3520 isInvalid = true; 3521 } else { 3522 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3523 } 3524 3525 if (isInvalid) 3526 return ExprError(); 3527 3528 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3529 PE = TransformToPotentiallyEvaluated(E); 3530 if (PE.isInvalid()) return ExprError(); 3531 E = PE.take(); 3532 } 3533 3534 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3535 return Owned(new (Context) UnaryExprOrTypeTraitExpr( 3536 ExprKind, E, Context.getSizeType(), OpLoc, 3537 E->getSourceRange().getEnd())); 3538 } 3539 3540 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 3541 /// expr and the same for @c alignof and @c __alignof 3542 /// Note that the ArgRange is invalid if isType is false. 3543 ExprResult 3544 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 3545 UnaryExprOrTypeTrait ExprKind, bool IsType, 3546 void *TyOrEx, const SourceRange &ArgRange) { 3547 // If error parsing type, ignore. 3548 if (TyOrEx == 0) return ExprError(); 3549 3550 if (IsType) { 3551 TypeSourceInfo *TInfo; 3552 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 3553 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 3554 } 3555 3556 Expr *ArgEx = (Expr *)TyOrEx; 3557 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 3558 return Result; 3559 } 3560 3561 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 3562 bool IsReal) { 3563 if (V.get()->isTypeDependent()) 3564 return S.Context.DependentTy; 3565 3566 // _Real and _Imag are only l-values for normal l-values. 3567 if (V.get()->getObjectKind() != OK_Ordinary) { 3568 V = S.DefaultLvalueConversion(V.take()); 3569 if (V.isInvalid()) 3570 return QualType(); 3571 } 3572 3573 // These operators return the element type of a complex type. 3574 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 3575 return CT->getElementType(); 3576 3577 // Otherwise they pass through real integer and floating point types here. 3578 if (V.get()->getType()->isArithmeticType()) 3579 return V.get()->getType(); 3580 3581 // Test for placeholders. 3582 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 3583 if (PR.isInvalid()) return QualType(); 3584 if (PR.get() != V.get()) { 3585 V = PR; 3586 return CheckRealImagOperand(S, V, Loc, IsReal); 3587 } 3588 3589 // Reject anything else. 3590 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 3591 << (IsReal ? "__real" : "__imag"); 3592 return QualType(); 3593 } 3594 3595 3596 3597 ExprResult 3598 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 3599 tok::TokenKind Kind, Expr *Input) { 3600 UnaryOperatorKind Opc; 3601 switch (Kind) { 3602 default: llvm_unreachable("Unknown unary op!"); 3603 case tok::plusplus: Opc = UO_PostInc; break; 3604 case tok::minusminus: Opc = UO_PostDec; break; 3605 } 3606 3607 // Since this might is a postfix expression, get rid of ParenListExprs. 3608 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 3609 if (Result.isInvalid()) return ExprError(); 3610 Input = Result.take(); 3611 3612 return BuildUnaryOp(S, OpLoc, Opc, Input); 3613 } 3614 3615 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 3616 /// 3617 /// \return true on error 3618 static bool checkArithmeticOnObjCPointer(Sema &S, 3619 SourceLocation opLoc, 3620 Expr *op) { 3621 assert(op->getType()->isObjCObjectPointerType()); 3622 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic()) 3623 return false; 3624 3625 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 3626 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 3627 << op->getSourceRange(); 3628 return true; 3629 } 3630 3631 ExprResult 3632 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 3633 Expr *idx, SourceLocation rbLoc) { 3634 // Since this might be a postfix expression, get rid of ParenListExprs. 3635 if (isa<ParenListExpr>(base)) { 3636 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 3637 if (result.isInvalid()) return ExprError(); 3638 base = result.take(); 3639 } 3640 3641 // Handle any non-overload placeholder types in the base and index 3642 // expressions. We can't handle overloads here because the other 3643 // operand might be an overloadable type, in which case the overload 3644 // resolution for the operator overload should get the first crack 3645 // at the overload. 3646 if (base->getType()->isNonOverloadPlaceholderType()) { 3647 ExprResult result = CheckPlaceholderExpr(base); 3648 if (result.isInvalid()) return ExprError(); 3649 base = result.take(); 3650 } 3651 if (idx->getType()->isNonOverloadPlaceholderType()) { 3652 ExprResult result = CheckPlaceholderExpr(idx); 3653 if (result.isInvalid()) return ExprError(); 3654 idx = result.take(); 3655 } 3656 3657 // Build an unanalyzed expression if either operand is type-dependent. 3658 if (getLangOpts().CPlusPlus && 3659 (base->isTypeDependent() || idx->isTypeDependent())) { 3660 return Owned(new (Context) ArraySubscriptExpr(base, idx, 3661 Context.DependentTy, 3662 VK_LValue, OK_Ordinary, 3663 rbLoc)); 3664 } 3665 3666 // Use C++ overloaded-operator rules if either operand has record 3667 // type. The spec says to do this if either type is *overloadable*, 3668 // but enum types can't declare subscript operators or conversion 3669 // operators, so there's nothing interesting for overload resolution 3670 // to do if there aren't any record types involved. 3671 // 3672 // ObjC pointers have their own subscripting logic that is not tied 3673 // to overload resolution and so should not take this path. 3674 if (getLangOpts().CPlusPlus && 3675 (base->getType()->isRecordType() || 3676 (!base->getType()->isObjCObjectPointerType() && 3677 idx->getType()->isRecordType()))) { 3678 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 3679 } 3680 3681 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 3682 } 3683 3684 ExprResult 3685 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 3686 Expr *Idx, SourceLocation RLoc) { 3687 Expr *LHSExp = Base; 3688 Expr *RHSExp = Idx; 3689 3690 // Perform default conversions. 3691 if (!LHSExp->getType()->getAs<VectorType>()) { 3692 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 3693 if (Result.isInvalid()) 3694 return ExprError(); 3695 LHSExp = Result.take(); 3696 } 3697 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 3698 if (Result.isInvalid()) 3699 return ExprError(); 3700 RHSExp = Result.take(); 3701 3702 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 3703 ExprValueKind VK = VK_LValue; 3704 ExprObjectKind OK = OK_Ordinary; 3705 3706 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 3707 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 3708 // in the subscript position. As a result, we need to derive the array base 3709 // and index from the expression types. 3710 Expr *BaseExpr, *IndexExpr; 3711 QualType ResultType; 3712 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 3713 BaseExpr = LHSExp; 3714 IndexExpr = RHSExp; 3715 ResultType = Context.DependentTy; 3716 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 3717 BaseExpr = LHSExp; 3718 IndexExpr = RHSExp; 3719 ResultType = PTy->getPointeeType(); 3720 } else if (const ObjCObjectPointerType *PTy = 3721 LHSTy->getAs<ObjCObjectPointerType>()) { 3722 BaseExpr = LHSExp; 3723 IndexExpr = RHSExp; 3724 3725 // Use custom logic if this should be the pseudo-object subscript 3726 // expression. 3727 if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic()) 3728 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0); 3729 3730 ResultType = PTy->getPointeeType(); 3731 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) { 3732 Diag(LLoc, diag::err_subscript_nonfragile_interface) 3733 << ResultType << BaseExpr->getSourceRange(); 3734 return ExprError(); 3735 } 3736 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 3737 // Handle the uncommon case of "123[Ptr]". 3738 BaseExpr = RHSExp; 3739 IndexExpr = LHSExp; 3740 ResultType = PTy->getPointeeType(); 3741 } else if (const ObjCObjectPointerType *PTy = 3742 RHSTy->getAs<ObjCObjectPointerType>()) { 3743 // Handle the uncommon case of "123[Ptr]". 3744 BaseExpr = RHSExp; 3745 IndexExpr = LHSExp; 3746 ResultType = PTy->getPointeeType(); 3747 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) { 3748 Diag(LLoc, diag::err_subscript_nonfragile_interface) 3749 << ResultType << BaseExpr->getSourceRange(); 3750 return ExprError(); 3751 } 3752 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 3753 BaseExpr = LHSExp; // vectors: V[123] 3754 IndexExpr = RHSExp; 3755 VK = LHSExp->getValueKind(); 3756 if (VK != VK_RValue) 3757 OK = OK_VectorComponent; 3758 3759 // FIXME: need to deal with const... 3760 ResultType = VTy->getElementType(); 3761 } else if (LHSTy->isArrayType()) { 3762 // If we see an array that wasn't promoted by 3763 // DefaultFunctionArrayLvalueConversion, it must be an array that 3764 // wasn't promoted because of the C90 rule that doesn't 3765 // allow promoting non-lvalue arrays. Warn, then 3766 // force the promotion here. 3767 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3768 LHSExp->getSourceRange(); 3769 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 3770 CK_ArrayToPointerDecay).take(); 3771 LHSTy = LHSExp->getType(); 3772 3773 BaseExpr = LHSExp; 3774 IndexExpr = RHSExp; 3775 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 3776 } else if (RHSTy->isArrayType()) { 3777 // Same as previous, except for 123[f().a] case 3778 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3779 RHSExp->getSourceRange(); 3780 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 3781 CK_ArrayToPointerDecay).take(); 3782 RHSTy = RHSExp->getType(); 3783 3784 BaseExpr = RHSExp; 3785 IndexExpr = LHSExp; 3786 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 3787 } else { 3788 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 3789 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 3790 } 3791 // C99 6.5.2.1p1 3792 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 3793 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 3794 << IndexExpr->getSourceRange()); 3795 3796 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 3797 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 3798 && !IndexExpr->isTypeDependent()) 3799 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 3800 3801 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 3802 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 3803 // type. Note that Functions are not objects, and that (in C99 parlance) 3804 // incomplete types are not object types. 3805 if (ResultType->isFunctionType()) { 3806 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 3807 << ResultType << BaseExpr->getSourceRange(); 3808 return ExprError(); 3809 } 3810 3811 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 3812 // GNU extension: subscripting on pointer to void 3813 Diag(LLoc, diag::ext_gnu_subscript_void_type) 3814 << BaseExpr->getSourceRange(); 3815 3816 // C forbids expressions of unqualified void type from being l-values. 3817 // See IsCForbiddenLValueType. 3818 if (!ResultType.hasQualifiers()) VK = VK_RValue; 3819 } else if (!ResultType->isDependentType() && 3820 RequireCompleteType(LLoc, ResultType, 3821 diag::err_subscript_incomplete_type, BaseExpr)) 3822 return ExprError(); 3823 3824 assert(VK == VK_RValue || LangOpts.CPlusPlus || 3825 !ResultType.isCForbiddenLValueType()); 3826 3827 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 3828 ResultType, VK, OK, RLoc)); 3829 } 3830 3831 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 3832 FunctionDecl *FD, 3833 ParmVarDecl *Param) { 3834 if (Param->hasUnparsedDefaultArg()) { 3835 Diag(CallLoc, 3836 diag::err_use_of_default_argument_to_function_declared_later) << 3837 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 3838 Diag(UnparsedDefaultArgLocs[Param], 3839 diag::note_default_argument_declared_here); 3840 return ExprError(); 3841 } 3842 3843 if (Param->hasUninstantiatedDefaultArg()) { 3844 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 3845 3846 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 3847 Param); 3848 3849 // Instantiate the expression. 3850 MultiLevelTemplateArgumentList MutiLevelArgList 3851 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true); 3852 3853 InstantiatingTemplate Inst(*this, CallLoc, Param, 3854 MutiLevelArgList.getInnermost()); 3855 if (Inst.isInvalid()) 3856 return ExprError(); 3857 3858 ExprResult Result; 3859 { 3860 // C++ [dcl.fct.default]p5: 3861 // The names in the [default argument] expression are bound, and 3862 // the semantic constraints are checked, at the point where the 3863 // default argument expression appears. 3864 ContextRAII SavedContext(*this, FD); 3865 LocalInstantiationScope Local(*this); 3866 Result = SubstExpr(UninstExpr, MutiLevelArgList); 3867 } 3868 if (Result.isInvalid()) 3869 return ExprError(); 3870 3871 // Check the expression as an initializer for the parameter. 3872 InitializedEntity Entity 3873 = InitializedEntity::InitializeParameter(Context, Param); 3874 InitializationKind Kind 3875 = InitializationKind::CreateCopy(Param->getLocation(), 3876 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 3877 Expr *ResultE = Result.takeAs<Expr>(); 3878 3879 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 3880 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 3881 if (Result.isInvalid()) 3882 return ExprError(); 3883 3884 Expr *Arg = Result.takeAs<Expr>(); 3885 CheckCompletedExpr(Arg, Param->getOuterLocStart()); 3886 // Build the default argument expression. 3887 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg)); 3888 } 3889 3890 // If the default expression creates temporaries, we need to 3891 // push them to the current stack of expression temporaries so they'll 3892 // be properly destroyed. 3893 // FIXME: We should really be rebuilding the default argument with new 3894 // bound temporaries; see the comment in PR5810. 3895 // We don't need to do that with block decls, though, because 3896 // blocks in default argument expression can never capture anything. 3897 if (isa<ExprWithCleanups>(Param->getInit())) { 3898 // Set the "needs cleanups" bit regardless of whether there are 3899 // any explicit objects. 3900 ExprNeedsCleanups = true; 3901 3902 // Append all the objects to the cleanup list. Right now, this 3903 // should always be a no-op, because blocks in default argument 3904 // expressions should never be able to capture anything. 3905 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() && 3906 "default argument expression has capturing blocks?"); 3907 } 3908 3909 // We already type-checked the argument, so we know it works. 3910 // Just mark all of the declarations in this potentially-evaluated expression 3911 // as being "referenced". 3912 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 3913 /*SkipLocalVariables=*/true); 3914 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param)); 3915 } 3916 3917 3918 Sema::VariadicCallType 3919 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 3920 Expr *Fn) { 3921 if (Proto && Proto->isVariadic()) { 3922 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 3923 return VariadicConstructor; 3924 else if (Fn && Fn->getType()->isBlockPointerType()) 3925 return VariadicBlock; 3926 else if (FDecl) { 3927 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 3928 if (Method->isInstance()) 3929 return VariadicMethod; 3930 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 3931 return VariadicMethod; 3932 return VariadicFunction; 3933 } 3934 return VariadicDoesNotApply; 3935 } 3936 3937 namespace { 3938 class FunctionCallCCC : public FunctionCallFilterCCC { 3939 public: 3940 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 3941 unsigned NumArgs, bool HasExplicitTemplateArgs) 3942 : FunctionCallFilterCCC(SemaRef, NumArgs, HasExplicitTemplateArgs), 3943 FunctionName(FuncName) {} 3944 3945 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 3946 if (!candidate.getCorrectionSpecifier() || 3947 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 3948 return false; 3949 } 3950 3951 return FunctionCallFilterCCC::ValidateCandidate(candidate); 3952 } 3953 3954 private: 3955 const IdentifierInfo *const FunctionName; 3956 }; 3957 } 3958 3959 static TypoCorrection TryTypoCorrectionForCall(Sema &S, 3960 DeclarationNameInfo FuncName, 3961 ArrayRef<Expr *> Args) { 3962 FunctionCallCCC CCC(S, FuncName.getName().getAsIdentifierInfo(), 3963 Args.size(), false); 3964 if (TypoCorrection Corrected = 3965 S.CorrectTypo(FuncName, Sema::LookupOrdinaryName, 3966 S.getScopeForContext(S.CurContext), NULL, CCC)) { 3967 if (NamedDecl *ND = Corrected.getCorrectionDecl()) { 3968 if (Corrected.isOverloaded()) { 3969 OverloadCandidateSet OCS(FuncName.getLoc()); 3970 OverloadCandidateSet::iterator Best; 3971 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 3972 CDEnd = Corrected.end(); 3973 CD != CDEnd; ++CD) { 3974 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 3975 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 3976 OCS); 3977 } 3978 switch (OCS.BestViableFunction(S, FuncName.getLoc(), Best)) { 3979 case OR_Success: 3980 ND = Best->Function; 3981 Corrected.setCorrectionDecl(ND); 3982 break; 3983 default: 3984 break; 3985 } 3986 } 3987 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) { 3988 return Corrected; 3989 } 3990 } 3991 } 3992 return TypoCorrection(); 3993 } 3994 3995 /// ConvertArgumentsForCall - Converts the arguments specified in 3996 /// Args/NumArgs to the parameter types of the function FDecl with 3997 /// function prototype Proto. Call is the call expression itself, and 3998 /// Fn is the function expression. For a C++ member function, this 3999 /// routine does not attempt to convert the object argument. Returns 4000 /// true if the call is ill-formed. 4001 bool 4002 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4003 FunctionDecl *FDecl, 4004 const FunctionProtoType *Proto, 4005 ArrayRef<Expr *> Args, 4006 SourceLocation RParenLoc, 4007 bool IsExecConfig) { 4008 // Bail out early if calling a builtin with custom typechecking. 4009 // We don't need to do this in the 4010 if (FDecl) 4011 if (unsigned ID = FDecl->getBuiltinID()) 4012 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4013 return false; 4014 4015 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4016 // assignment, to the types of the corresponding parameter, ... 4017 unsigned NumArgsInProto = Proto->getNumArgs(); 4018 bool Invalid = false; 4019 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto; 4020 unsigned FnKind = Fn->getType()->isBlockPointerType() 4021 ? 1 /* block */ 4022 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4023 : 0 /* function */); 4024 4025 // If too few arguments are available (and we don't have default 4026 // arguments for the remaining parameters), don't make the call. 4027 if (Args.size() < NumArgsInProto) { 4028 if (Args.size() < MinArgs) { 4029 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4030 TypoCorrection TC; 4031 if (FDecl && (TC = TryTypoCorrectionForCall( 4032 *this, DeclarationNameInfo(FDecl->getDeclName(), 4033 (ME ? ME->getMemberLoc() 4034 : Fn->getLocStart())), 4035 Args))) { 4036 unsigned diag_id = 4037 MinArgs == NumArgsInProto && !Proto->isVariadic() 4038 ? diag::err_typecheck_call_too_few_args_suggest 4039 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4040 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4041 << static_cast<unsigned>(Args.size()) 4042 << Fn->getSourceRange()); 4043 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4044 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic() 4045 ? diag::err_typecheck_call_too_few_args_one 4046 : diag::err_typecheck_call_too_few_args_at_least_one) 4047 << FnKind 4048 << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4049 else 4050 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic() 4051 ? diag::err_typecheck_call_too_few_args 4052 : diag::err_typecheck_call_too_few_args_at_least) 4053 << FnKind 4054 << MinArgs << static_cast<unsigned>(Args.size()) 4055 << Fn->getSourceRange(); 4056 4057 // Emit the location of the prototype. 4058 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4059 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4060 << FDecl; 4061 4062 return true; 4063 } 4064 Call->setNumArgs(Context, NumArgsInProto); 4065 } 4066 4067 // If too many are passed and not variadic, error on the extras and drop 4068 // them. 4069 if (Args.size() > NumArgsInProto) { 4070 if (!Proto->isVariadic()) { 4071 TypoCorrection TC; 4072 if (FDecl && (TC = TryTypoCorrectionForCall( 4073 *this, DeclarationNameInfo(FDecl->getDeclName(), 4074 Fn->getLocStart()), 4075 Args))) { 4076 unsigned diag_id = 4077 MinArgs == NumArgsInProto && !Proto->isVariadic() 4078 ? diag::err_typecheck_call_too_many_args_suggest 4079 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4080 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumArgsInProto 4081 << static_cast<unsigned>(Args.size()) 4082 << Fn->getSourceRange()); 4083 } else if (NumArgsInProto == 1 && FDecl && 4084 FDecl->getParamDecl(0)->getDeclName()) 4085 Diag(Args[NumArgsInProto]->getLocStart(), 4086 MinArgs == NumArgsInProto 4087 ? diag::err_typecheck_call_too_many_args_one 4088 : diag::err_typecheck_call_too_many_args_at_most_one) 4089 << FnKind 4090 << FDecl->getParamDecl(0) << static_cast<unsigned>(Args.size()) 4091 << Fn->getSourceRange() 4092 << SourceRange(Args[NumArgsInProto]->getLocStart(), 4093 Args.back()->getLocEnd()); 4094 else 4095 Diag(Args[NumArgsInProto]->getLocStart(), 4096 MinArgs == NumArgsInProto 4097 ? diag::err_typecheck_call_too_many_args 4098 : diag::err_typecheck_call_too_many_args_at_most) 4099 << FnKind 4100 << NumArgsInProto << static_cast<unsigned>(Args.size()) 4101 << Fn->getSourceRange() 4102 << SourceRange(Args[NumArgsInProto]->getLocStart(), 4103 Args.back()->getLocEnd()); 4104 4105 // Emit the location of the prototype. 4106 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4107 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4108 << FDecl; 4109 4110 // This deletes the extra arguments. 4111 Call->setNumArgs(Context, NumArgsInProto); 4112 return true; 4113 } 4114 } 4115 SmallVector<Expr *, 8> AllArgs; 4116 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4117 4118 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4119 Proto, 0, Args, AllArgs, CallType); 4120 if (Invalid) 4121 return true; 4122 unsigned TotalNumArgs = AllArgs.size(); 4123 for (unsigned i = 0; i < TotalNumArgs; ++i) 4124 Call->setArg(i, AllArgs[i]); 4125 4126 return false; 4127 } 4128 4129 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, 4130 FunctionDecl *FDecl, 4131 const FunctionProtoType *Proto, 4132 unsigned FirstProtoArg, 4133 ArrayRef<Expr *> Args, 4134 SmallVectorImpl<Expr *> &AllArgs, 4135 VariadicCallType CallType, 4136 bool AllowExplicit, 4137 bool IsListInitialization) { 4138 unsigned NumArgsInProto = Proto->getNumArgs(); 4139 unsigned NumArgsToCheck = Args.size(); 4140 bool Invalid = false; 4141 if (Args.size() != NumArgsInProto) 4142 // Use default arguments for missing arguments 4143 NumArgsToCheck = NumArgsInProto; 4144 unsigned ArgIx = 0; 4145 // Continue to check argument types (even if we have too few/many args). 4146 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) { 4147 QualType ProtoArgType = Proto->getArgType(i); 4148 4149 Expr *Arg; 4150 ParmVarDecl *Param; 4151 if (ArgIx < Args.size()) { 4152 Arg = Args[ArgIx++]; 4153 4154 if (RequireCompleteType(Arg->getLocStart(), 4155 ProtoArgType, 4156 diag::err_call_incomplete_argument, Arg)) 4157 return true; 4158 4159 // Pass the argument 4160 Param = 0; 4161 if (FDecl && i < FDecl->getNumParams()) 4162 Param = FDecl->getParamDecl(i); 4163 4164 // Strip the unbridged-cast placeholder expression off, if applicable. 4165 bool CFAudited = false; 4166 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4167 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4168 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4169 Arg = stripARCUnbridgedCast(Arg); 4170 else if (getLangOpts().ObjCAutoRefCount && 4171 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4172 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4173 CFAudited = true; 4174 4175 InitializedEntity Entity = Param ? 4176 InitializedEntity::InitializeParameter(Context, Param, ProtoArgType) 4177 : InitializedEntity::InitializeParameter(Context, ProtoArgType, 4178 Proto->isArgConsumed(i)); 4179 4180 // Remember that parameter belongs to a CF audited API. 4181 if (CFAudited) 4182 Entity.setParameterCFAudited(); 4183 4184 ExprResult ArgE = PerformCopyInitialization(Entity, 4185 SourceLocation(), 4186 Owned(Arg), 4187 IsListInitialization, 4188 AllowExplicit); 4189 if (ArgE.isInvalid()) 4190 return true; 4191 4192 Arg = ArgE.takeAs<Expr>(); 4193 } else { 4194 assert(FDecl && "can't use default arguments without a known callee"); 4195 Param = FDecl->getParamDecl(i); 4196 4197 ExprResult ArgExpr = 4198 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4199 if (ArgExpr.isInvalid()) 4200 return true; 4201 4202 Arg = ArgExpr.takeAs<Expr>(); 4203 } 4204 4205 // Check for array bounds violations for each argument to the call. This 4206 // check only triggers warnings when the argument isn't a more complex Expr 4207 // with its own checking, such as a BinaryOperator. 4208 CheckArrayAccess(Arg); 4209 4210 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4211 CheckStaticArrayArgument(CallLoc, Param, Arg); 4212 4213 AllArgs.push_back(Arg); 4214 } 4215 4216 // If this is a variadic call, handle args passed through "...". 4217 if (CallType != VariadicDoesNotApply) { 4218 // Assume that extern "C" functions with variadic arguments that 4219 // return __unknown_anytype aren't *really* variadic. 4220 if (Proto->getResultType() == Context.UnknownAnyTy && 4221 FDecl && FDecl->isExternC()) { 4222 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4223 QualType paramType; // ignored 4224 ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType); 4225 Invalid |= arg.isInvalid(); 4226 AllArgs.push_back(arg.take()); 4227 } 4228 4229 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4230 } else { 4231 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4232 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, 4233 FDecl); 4234 Invalid |= Arg.isInvalid(); 4235 AllArgs.push_back(Arg.take()); 4236 } 4237 } 4238 4239 // Check for array bounds violations. 4240 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) 4241 CheckArrayAccess(Args[i]); 4242 } 4243 return Invalid; 4244 } 4245 4246 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4247 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4248 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4249 TL = DTL.getOriginalLoc(); 4250 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4251 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4252 << ATL.getLocalSourceRange(); 4253 } 4254 4255 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4256 /// array parameter, check that it is non-null, and that if it is formed by 4257 /// array-to-pointer decay, the underlying array is sufficiently large. 4258 /// 4259 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4260 /// array type derivation, then for each call to the function, the value of the 4261 /// corresponding actual argument shall provide access to the first element of 4262 /// an array with at least as many elements as specified by the size expression. 4263 void 4264 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4265 ParmVarDecl *Param, 4266 const Expr *ArgExpr) { 4267 // Static array parameters are not supported in C++. 4268 if (!Param || getLangOpts().CPlusPlus) 4269 return; 4270 4271 QualType OrigTy = Param->getOriginalType(); 4272 4273 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4274 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4275 return; 4276 4277 if (ArgExpr->isNullPointerConstant(Context, 4278 Expr::NPC_NeverValueDependent)) { 4279 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4280 DiagnoseCalleeStaticArrayParam(*this, Param); 4281 return; 4282 } 4283 4284 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4285 if (!CAT) 4286 return; 4287 4288 const ConstantArrayType *ArgCAT = 4289 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4290 if (!ArgCAT) 4291 return; 4292 4293 if (ArgCAT->getSize().ult(CAT->getSize())) { 4294 Diag(CallLoc, diag::warn_static_array_too_small) 4295 << ArgExpr->getSourceRange() 4296 << (unsigned) ArgCAT->getSize().getZExtValue() 4297 << (unsigned) CAT->getSize().getZExtValue(); 4298 DiagnoseCalleeStaticArrayParam(*this, Param); 4299 } 4300 } 4301 4302 /// Given a function expression of unknown-any type, try to rebuild it 4303 /// to have a function type. 4304 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4305 4306 /// Is the given type a placeholder that we need to lower out 4307 /// immediately during argument processing? 4308 static bool isPlaceholderToRemoveAsArg(QualType type) { 4309 // Placeholders are never sugared. 4310 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4311 if (!placeholder) return false; 4312 4313 switch (placeholder->getKind()) { 4314 // Ignore all the non-placeholder types. 4315 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4316 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4317 #include "clang/AST/BuiltinTypes.def" 4318 return false; 4319 4320 // We cannot lower out overload sets; they might validly be resolved 4321 // by the call machinery. 4322 case BuiltinType::Overload: 4323 return false; 4324 4325 // Unbridged casts in ARC can be handled in some call positions and 4326 // should be left in place. 4327 case BuiltinType::ARCUnbridgedCast: 4328 return false; 4329 4330 // Pseudo-objects should be converted as soon as possible. 4331 case BuiltinType::PseudoObject: 4332 return true; 4333 4334 // The debugger mode could theoretically but currently does not try 4335 // to resolve unknown-typed arguments based on known parameter types. 4336 case BuiltinType::UnknownAny: 4337 return true; 4338 4339 // These are always invalid as call arguments and should be reported. 4340 case BuiltinType::BoundMember: 4341 case BuiltinType::BuiltinFn: 4342 return true; 4343 } 4344 llvm_unreachable("bad builtin type kind"); 4345 } 4346 4347 /// Check an argument list for placeholders that we won't try to 4348 /// handle later. 4349 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 4350 // Apply this processing to all the arguments at once instead of 4351 // dying at the first failure. 4352 bool hasInvalid = false; 4353 for (size_t i = 0, e = args.size(); i != e; i++) { 4354 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 4355 ExprResult result = S.CheckPlaceholderExpr(args[i]); 4356 if (result.isInvalid()) hasInvalid = true; 4357 else args[i] = result.take(); 4358 } 4359 } 4360 return hasInvalid; 4361 } 4362 4363 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 4364 /// This provides the location of the left/right parens and a list of comma 4365 /// locations. 4366 ExprResult 4367 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 4368 MultiExprArg ArgExprs, SourceLocation RParenLoc, 4369 Expr *ExecConfig, bool IsExecConfig) { 4370 // Since this might be a postfix expression, get rid of ParenListExprs. 4371 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 4372 if (Result.isInvalid()) return ExprError(); 4373 Fn = Result.take(); 4374 4375 if (checkArgsForPlaceholders(*this, ArgExprs)) 4376 return ExprError(); 4377 4378 if (getLangOpts().CPlusPlus) { 4379 // If this is a pseudo-destructor expression, build the call immediately. 4380 if (isa<CXXPseudoDestructorExpr>(Fn)) { 4381 if (!ArgExprs.empty()) { 4382 // Pseudo-destructor calls should not have any arguments. 4383 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 4384 << FixItHint::CreateRemoval( 4385 SourceRange(ArgExprs[0]->getLocStart(), 4386 ArgExprs.back()->getLocEnd())); 4387 } 4388 4389 return Owned(new (Context) CallExpr(Context, Fn, None, 4390 Context.VoidTy, VK_RValue, 4391 RParenLoc)); 4392 } 4393 if (Fn->getType() == Context.PseudoObjectTy) { 4394 ExprResult result = CheckPlaceholderExpr(Fn); 4395 if (result.isInvalid()) return ExprError(); 4396 Fn = result.take(); 4397 } 4398 4399 // Determine whether this is a dependent call inside a C++ template, 4400 // in which case we won't do any semantic analysis now. 4401 // FIXME: Will need to cache the results of name lookup (including ADL) in 4402 // Fn. 4403 bool Dependent = false; 4404 if (Fn->isTypeDependent()) 4405 Dependent = true; 4406 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 4407 Dependent = true; 4408 4409 if (Dependent) { 4410 if (ExecConfig) { 4411 return Owned(new (Context) CUDAKernelCallExpr( 4412 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 4413 Context.DependentTy, VK_RValue, RParenLoc)); 4414 } else { 4415 return Owned(new (Context) CallExpr(Context, Fn, ArgExprs, 4416 Context.DependentTy, VK_RValue, 4417 RParenLoc)); 4418 } 4419 } 4420 4421 // Determine whether this is a call to an object (C++ [over.call.object]). 4422 if (Fn->getType()->isRecordType()) 4423 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, 4424 ArgExprs, RParenLoc)); 4425 4426 if (Fn->getType() == Context.UnknownAnyTy) { 4427 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4428 if (result.isInvalid()) return ExprError(); 4429 Fn = result.take(); 4430 } 4431 4432 if (Fn->getType() == Context.BoundMemberTy) { 4433 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 4434 } 4435 } 4436 4437 // Check for overloaded calls. This can happen even in C due to extensions. 4438 if (Fn->getType() == Context.OverloadTy) { 4439 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 4440 4441 // We aren't supposed to apply this logic for if there's an '&' involved. 4442 if (!find.HasFormOfMemberPointer) { 4443 OverloadExpr *ovl = find.Expression; 4444 if (isa<UnresolvedLookupExpr>(ovl)) { 4445 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl); 4446 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs, 4447 RParenLoc, ExecConfig); 4448 } else { 4449 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, 4450 RParenLoc); 4451 } 4452 } 4453 } 4454 4455 // If we're directly calling a function, get the appropriate declaration. 4456 if (Fn->getType() == Context.UnknownAnyTy) { 4457 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4458 if (result.isInvalid()) return ExprError(); 4459 Fn = result.take(); 4460 } 4461 4462 Expr *NakedFn = Fn->IgnoreParens(); 4463 4464 NamedDecl *NDecl = 0; 4465 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) 4466 if (UnOp->getOpcode() == UO_AddrOf) 4467 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 4468 4469 if (isa<DeclRefExpr>(NakedFn)) 4470 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 4471 else if (isa<MemberExpr>(NakedFn)) 4472 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 4473 4474 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 4475 ExecConfig, IsExecConfig); 4476 } 4477 4478 ExprResult 4479 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 4480 MultiExprArg ExecConfig, SourceLocation GGGLoc) { 4481 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl(); 4482 if (!ConfigDecl) 4483 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use) 4484 << "cudaConfigureCall"); 4485 QualType ConfigQTy = ConfigDecl->getType(); 4486 4487 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr( 4488 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc); 4489 MarkFunctionReferenced(LLLLoc, ConfigDecl); 4490 4491 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0, 4492 /*IsExecConfig=*/true); 4493 } 4494 4495 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 4496 /// 4497 /// __builtin_astype( value, dst type ) 4498 /// 4499 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 4500 SourceLocation BuiltinLoc, 4501 SourceLocation RParenLoc) { 4502 ExprValueKind VK = VK_RValue; 4503 ExprObjectKind OK = OK_Ordinary; 4504 QualType DstTy = GetTypeFromParser(ParsedDestTy); 4505 QualType SrcTy = E->getType(); 4506 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 4507 return ExprError(Diag(BuiltinLoc, 4508 diag::err_invalid_astype_of_different_size) 4509 << DstTy 4510 << SrcTy 4511 << E->getSourceRange()); 4512 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, 4513 RParenLoc)); 4514 } 4515 4516 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 4517 /// provided arguments. 4518 /// 4519 /// __builtin_convertvector( value, dst type ) 4520 /// 4521 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 4522 SourceLocation BuiltinLoc, 4523 SourceLocation RParenLoc) { 4524 TypeSourceInfo *TInfo; 4525 GetTypeFromParser(ParsedDestTy, &TInfo); 4526 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 4527 } 4528 4529 /// BuildResolvedCallExpr - Build a call to a resolved expression, 4530 /// i.e. an expression not of \p OverloadTy. The expression should 4531 /// unary-convert to an expression of function-pointer or 4532 /// block-pointer type. 4533 /// 4534 /// \param NDecl the declaration being called, if available 4535 ExprResult 4536 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 4537 SourceLocation LParenLoc, 4538 ArrayRef<Expr *> Args, 4539 SourceLocation RParenLoc, 4540 Expr *Config, bool IsExecConfig) { 4541 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 4542 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 4543 4544 // Promote the function operand. 4545 // We special-case function promotion here because we only allow promoting 4546 // builtin functions to function pointers in the callee of a call. 4547 ExprResult Result; 4548 if (BuiltinID && 4549 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 4550 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 4551 CK_BuiltinFnToFnPtr).take(); 4552 } else { 4553 Result = UsualUnaryConversions(Fn); 4554 } 4555 if (Result.isInvalid()) 4556 return ExprError(); 4557 Fn = Result.take(); 4558 4559 // Make the call expr early, before semantic checks. This guarantees cleanup 4560 // of arguments and function on error. 4561 CallExpr *TheCall; 4562 if (Config) 4563 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 4564 cast<CallExpr>(Config), Args, 4565 Context.BoolTy, VK_RValue, 4566 RParenLoc); 4567 else 4568 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 4569 VK_RValue, RParenLoc); 4570 4571 // Bail out early if calling a builtin with custom typechecking. 4572 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 4573 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 4574 4575 retry: 4576 const FunctionType *FuncT; 4577 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 4578 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 4579 // have type pointer to function". 4580 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 4581 if (FuncT == 0) 4582 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4583 << Fn->getType() << Fn->getSourceRange()); 4584 } else if (const BlockPointerType *BPT = 4585 Fn->getType()->getAs<BlockPointerType>()) { 4586 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 4587 } else { 4588 // Handle calls to expressions of unknown-any type. 4589 if (Fn->getType() == Context.UnknownAnyTy) { 4590 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 4591 if (rewrite.isInvalid()) return ExprError(); 4592 Fn = rewrite.take(); 4593 TheCall->setCallee(Fn); 4594 goto retry; 4595 } 4596 4597 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4598 << Fn->getType() << Fn->getSourceRange()); 4599 } 4600 4601 if (getLangOpts().CUDA) { 4602 if (Config) { 4603 // CUDA: Kernel calls must be to global functions 4604 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 4605 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 4606 << FDecl->getName() << Fn->getSourceRange()); 4607 4608 // CUDA: Kernel function must have 'void' return type 4609 if (!FuncT->getResultType()->isVoidType()) 4610 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 4611 << Fn->getType() << Fn->getSourceRange()); 4612 } else { 4613 // CUDA: Calls to global functions must be configured 4614 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 4615 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 4616 << FDecl->getName() << Fn->getSourceRange()); 4617 } 4618 } 4619 4620 // Check for a valid return type 4621 if (CheckCallReturnType(FuncT->getResultType(), 4622 Fn->getLocStart(), TheCall, 4623 FDecl)) 4624 return ExprError(); 4625 4626 // We know the result type of the call, set it. 4627 TheCall->setType(FuncT->getCallResultType(Context)); 4628 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType())); 4629 4630 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 4631 if (Proto) { 4632 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 4633 IsExecConfig)) 4634 return ExprError(); 4635 } else { 4636 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 4637 4638 if (FDecl) { 4639 // Check if we have too few/too many template arguments, based 4640 // on our knowledge of the function definition. 4641 const FunctionDecl *Def = 0; 4642 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 4643 Proto = Def->getType()->getAs<FunctionProtoType>(); 4644 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 4645 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 4646 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 4647 } 4648 4649 // If the function we're calling isn't a function prototype, but we have 4650 // a function prototype from a prior declaratiom, use that prototype. 4651 if (!FDecl->hasPrototype()) 4652 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 4653 } 4654 4655 // Promote the arguments (C99 6.5.2.2p6). 4656 for (unsigned i = 0, e = Args.size(); i != e; i++) { 4657 Expr *Arg = Args[i]; 4658 4659 if (Proto && i < Proto->getNumArgs()) { 4660 InitializedEntity Entity 4661 = InitializedEntity::InitializeParameter(Context, 4662 Proto->getArgType(i), 4663 Proto->isArgConsumed(i)); 4664 ExprResult ArgE = PerformCopyInitialization(Entity, 4665 SourceLocation(), 4666 Owned(Arg)); 4667 if (ArgE.isInvalid()) 4668 return true; 4669 4670 Arg = ArgE.takeAs<Expr>(); 4671 4672 } else { 4673 ExprResult ArgE = DefaultArgumentPromotion(Arg); 4674 4675 if (ArgE.isInvalid()) 4676 return true; 4677 4678 Arg = ArgE.takeAs<Expr>(); 4679 } 4680 4681 if (RequireCompleteType(Arg->getLocStart(), 4682 Arg->getType(), 4683 diag::err_call_incomplete_argument, Arg)) 4684 return ExprError(); 4685 4686 TheCall->setArg(i, Arg); 4687 } 4688 } 4689 4690 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4691 if (!Method->isStatic()) 4692 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 4693 << Fn->getSourceRange()); 4694 4695 // Check for sentinels 4696 if (NDecl) 4697 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 4698 4699 // Do special checking on direct calls to functions. 4700 if (FDecl) { 4701 if (CheckFunctionCall(FDecl, TheCall, Proto)) 4702 return ExprError(); 4703 4704 if (BuiltinID) 4705 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 4706 } else if (NDecl) { 4707 if (CheckPointerCall(NDecl, TheCall, Proto)) 4708 return ExprError(); 4709 } else { 4710 if (CheckOtherCall(TheCall, Proto)) 4711 return ExprError(); 4712 } 4713 4714 return MaybeBindToTemporary(TheCall); 4715 } 4716 4717 ExprResult 4718 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 4719 SourceLocation RParenLoc, Expr *InitExpr) { 4720 assert(Ty && "ActOnCompoundLiteral(): missing type"); 4721 // FIXME: put back this assert when initializers are worked out. 4722 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 4723 4724 TypeSourceInfo *TInfo; 4725 QualType literalType = GetTypeFromParser(Ty, &TInfo); 4726 if (!TInfo) 4727 TInfo = Context.getTrivialTypeSourceInfo(literalType); 4728 4729 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 4730 } 4731 4732 ExprResult 4733 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 4734 SourceLocation RParenLoc, Expr *LiteralExpr) { 4735 QualType literalType = TInfo->getType(); 4736 4737 if (literalType->isArrayType()) { 4738 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 4739 diag::err_illegal_decl_array_incomplete_type, 4740 SourceRange(LParenLoc, 4741 LiteralExpr->getSourceRange().getEnd()))) 4742 return ExprError(); 4743 if (literalType->isVariableArrayType()) 4744 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 4745 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 4746 } else if (!literalType->isDependentType() && 4747 RequireCompleteType(LParenLoc, literalType, 4748 diag::err_typecheck_decl_incomplete_type, 4749 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 4750 return ExprError(); 4751 4752 InitializedEntity Entity 4753 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 4754 InitializationKind Kind 4755 = InitializationKind::CreateCStyleCast(LParenLoc, 4756 SourceRange(LParenLoc, RParenLoc), 4757 /*InitList=*/true); 4758 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 4759 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 4760 &literalType); 4761 if (Result.isInvalid()) 4762 return ExprError(); 4763 LiteralExpr = Result.get(); 4764 4765 bool isFileScope = getCurFunctionOrMethodDecl() == 0; 4766 if (isFileScope && 4767 !LiteralExpr->isTypeDependent() && 4768 !LiteralExpr->isValueDependent() && 4769 !literalType->isDependentType()) { // 6.5.2.5p3 4770 if (CheckForConstantInitializer(LiteralExpr, literalType)) 4771 return ExprError(); 4772 } 4773 4774 // In C, compound literals are l-values for some reason. 4775 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 4776 4777 return MaybeBindToTemporary( 4778 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 4779 VK, LiteralExpr, isFileScope)); 4780 } 4781 4782 ExprResult 4783 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 4784 SourceLocation RBraceLoc) { 4785 // Immediately handle non-overload placeholders. Overloads can be 4786 // resolved contextually, but everything else here can't. 4787 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 4788 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 4789 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 4790 4791 // Ignore failures; dropping the entire initializer list because 4792 // of one failure would be terrible for indexing/etc. 4793 if (result.isInvalid()) continue; 4794 4795 InitArgList[I] = result.take(); 4796 } 4797 } 4798 4799 // Semantic analysis for initializers is done by ActOnDeclarator() and 4800 // CheckInitializer() - it requires knowledge of the object being intialized. 4801 4802 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 4803 RBraceLoc); 4804 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 4805 return Owned(E); 4806 } 4807 4808 /// Do an explicit extend of the given block pointer if we're in ARC. 4809 static void maybeExtendBlockObject(Sema &S, ExprResult &E) { 4810 assert(E.get()->getType()->isBlockPointerType()); 4811 assert(E.get()->isRValue()); 4812 4813 // Only do this in an r-value context. 4814 if (!S.getLangOpts().ObjCAutoRefCount) return; 4815 4816 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), 4817 CK_ARCExtendBlockObject, E.get(), 4818 /*base path*/ 0, VK_RValue); 4819 S.ExprNeedsCleanups = true; 4820 } 4821 4822 /// Prepare a conversion of the given expression to an ObjC object 4823 /// pointer type. 4824 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 4825 QualType type = E.get()->getType(); 4826 if (type->isObjCObjectPointerType()) { 4827 return CK_BitCast; 4828 } else if (type->isBlockPointerType()) { 4829 maybeExtendBlockObject(*this, E); 4830 return CK_BlockPointerToObjCPointerCast; 4831 } else { 4832 assert(type->isPointerType()); 4833 return CK_CPointerToObjCPointerCast; 4834 } 4835 } 4836 4837 /// Prepares for a scalar cast, performing all the necessary stages 4838 /// except the final cast and returning the kind required. 4839 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 4840 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 4841 // Also, callers should have filtered out the invalid cases with 4842 // pointers. Everything else should be possible. 4843 4844 QualType SrcTy = Src.get()->getType(); 4845 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 4846 return CK_NoOp; 4847 4848 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 4849 case Type::STK_MemberPointer: 4850 llvm_unreachable("member pointer type in C"); 4851 4852 case Type::STK_CPointer: 4853 case Type::STK_BlockPointer: 4854 case Type::STK_ObjCObjectPointer: 4855 switch (DestTy->getScalarTypeKind()) { 4856 case Type::STK_CPointer: 4857 return CK_BitCast; 4858 case Type::STK_BlockPointer: 4859 return (SrcKind == Type::STK_BlockPointer 4860 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 4861 case Type::STK_ObjCObjectPointer: 4862 if (SrcKind == Type::STK_ObjCObjectPointer) 4863 return CK_BitCast; 4864 if (SrcKind == Type::STK_CPointer) 4865 return CK_CPointerToObjCPointerCast; 4866 maybeExtendBlockObject(*this, Src); 4867 return CK_BlockPointerToObjCPointerCast; 4868 case Type::STK_Bool: 4869 return CK_PointerToBoolean; 4870 case Type::STK_Integral: 4871 return CK_PointerToIntegral; 4872 case Type::STK_Floating: 4873 case Type::STK_FloatingComplex: 4874 case Type::STK_IntegralComplex: 4875 case Type::STK_MemberPointer: 4876 llvm_unreachable("illegal cast from pointer"); 4877 } 4878 llvm_unreachable("Should have returned before this"); 4879 4880 case Type::STK_Bool: // casting from bool is like casting from an integer 4881 case Type::STK_Integral: 4882 switch (DestTy->getScalarTypeKind()) { 4883 case Type::STK_CPointer: 4884 case Type::STK_ObjCObjectPointer: 4885 case Type::STK_BlockPointer: 4886 if (Src.get()->isNullPointerConstant(Context, 4887 Expr::NPC_ValueDependentIsNull)) 4888 return CK_NullToPointer; 4889 return CK_IntegralToPointer; 4890 case Type::STK_Bool: 4891 return CK_IntegralToBoolean; 4892 case Type::STK_Integral: 4893 return CK_IntegralCast; 4894 case Type::STK_Floating: 4895 return CK_IntegralToFloating; 4896 case Type::STK_IntegralComplex: 4897 Src = ImpCastExprToType(Src.take(), 4898 DestTy->castAs<ComplexType>()->getElementType(), 4899 CK_IntegralCast); 4900 return CK_IntegralRealToComplex; 4901 case Type::STK_FloatingComplex: 4902 Src = ImpCastExprToType(Src.take(), 4903 DestTy->castAs<ComplexType>()->getElementType(), 4904 CK_IntegralToFloating); 4905 return CK_FloatingRealToComplex; 4906 case Type::STK_MemberPointer: 4907 llvm_unreachable("member pointer type in C"); 4908 } 4909 llvm_unreachable("Should have returned before this"); 4910 4911 case Type::STK_Floating: 4912 switch (DestTy->getScalarTypeKind()) { 4913 case Type::STK_Floating: 4914 return CK_FloatingCast; 4915 case Type::STK_Bool: 4916 return CK_FloatingToBoolean; 4917 case Type::STK_Integral: 4918 return CK_FloatingToIntegral; 4919 case Type::STK_FloatingComplex: 4920 Src = ImpCastExprToType(Src.take(), 4921 DestTy->castAs<ComplexType>()->getElementType(), 4922 CK_FloatingCast); 4923 return CK_FloatingRealToComplex; 4924 case Type::STK_IntegralComplex: 4925 Src = ImpCastExprToType(Src.take(), 4926 DestTy->castAs<ComplexType>()->getElementType(), 4927 CK_FloatingToIntegral); 4928 return CK_IntegralRealToComplex; 4929 case Type::STK_CPointer: 4930 case Type::STK_ObjCObjectPointer: 4931 case Type::STK_BlockPointer: 4932 llvm_unreachable("valid float->pointer cast?"); 4933 case Type::STK_MemberPointer: 4934 llvm_unreachable("member pointer type in C"); 4935 } 4936 llvm_unreachable("Should have returned before this"); 4937 4938 case Type::STK_FloatingComplex: 4939 switch (DestTy->getScalarTypeKind()) { 4940 case Type::STK_FloatingComplex: 4941 return CK_FloatingComplexCast; 4942 case Type::STK_IntegralComplex: 4943 return CK_FloatingComplexToIntegralComplex; 4944 case Type::STK_Floating: { 4945 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 4946 if (Context.hasSameType(ET, DestTy)) 4947 return CK_FloatingComplexToReal; 4948 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal); 4949 return CK_FloatingCast; 4950 } 4951 case Type::STK_Bool: 4952 return CK_FloatingComplexToBoolean; 4953 case Type::STK_Integral: 4954 Src = ImpCastExprToType(Src.take(), 4955 SrcTy->castAs<ComplexType>()->getElementType(), 4956 CK_FloatingComplexToReal); 4957 return CK_FloatingToIntegral; 4958 case Type::STK_CPointer: 4959 case Type::STK_ObjCObjectPointer: 4960 case Type::STK_BlockPointer: 4961 llvm_unreachable("valid complex float->pointer cast?"); 4962 case Type::STK_MemberPointer: 4963 llvm_unreachable("member pointer type in C"); 4964 } 4965 llvm_unreachable("Should have returned before this"); 4966 4967 case Type::STK_IntegralComplex: 4968 switch (DestTy->getScalarTypeKind()) { 4969 case Type::STK_FloatingComplex: 4970 return CK_IntegralComplexToFloatingComplex; 4971 case Type::STK_IntegralComplex: 4972 return CK_IntegralComplexCast; 4973 case Type::STK_Integral: { 4974 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 4975 if (Context.hasSameType(ET, DestTy)) 4976 return CK_IntegralComplexToReal; 4977 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal); 4978 return CK_IntegralCast; 4979 } 4980 case Type::STK_Bool: 4981 return CK_IntegralComplexToBoolean; 4982 case Type::STK_Floating: 4983 Src = ImpCastExprToType(Src.take(), 4984 SrcTy->castAs<ComplexType>()->getElementType(), 4985 CK_IntegralComplexToReal); 4986 return CK_IntegralToFloating; 4987 case Type::STK_CPointer: 4988 case Type::STK_ObjCObjectPointer: 4989 case Type::STK_BlockPointer: 4990 llvm_unreachable("valid complex int->pointer cast?"); 4991 case Type::STK_MemberPointer: 4992 llvm_unreachable("member pointer type in C"); 4993 } 4994 llvm_unreachable("Should have returned before this"); 4995 } 4996 4997 llvm_unreachable("Unhandled scalar cast"); 4998 } 4999 5000 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5001 CastKind &Kind) { 5002 assert(VectorTy->isVectorType() && "Not a vector type!"); 5003 5004 if (Ty->isVectorType() || Ty->isIntegerType()) { 5005 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty)) 5006 return Diag(R.getBegin(), 5007 Ty->isVectorType() ? 5008 diag::err_invalid_conversion_between_vectors : 5009 diag::err_invalid_conversion_between_vector_and_integer) 5010 << VectorTy << Ty << R; 5011 } else 5012 return Diag(R.getBegin(), 5013 diag::err_invalid_conversion_between_vector_and_scalar) 5014 << VectorTy << Ty << R; 5015 5016 Kind = CK_BitCast; 5017 return false; 5018 } 5019 5020 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5021 Expr *CastExpr, CastKind &Kind) { 5022 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5023 5024 QualType SrcTy = CastExpr->getType(); 5025 5026 // If SrcTy is a VectorType, the total size must match to explicitly cast to 5027 // an ExtVectorType. 5028 // In OpenCL, casts between vectors of different types are not allowed. 5029 // (See OpenCL 6.2). 5030 if (SrcTy->isVectorType()) { 5031 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy) 5032 || (getLangOpts().OpenCL && 5033 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 5034 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 5035 << DestTy << SrcTy << R; 5036 return ExprError(); 5037 } 5038 Kind = CK_BitCast; 5039 return Owned(CastExpr); 5040 } 5041 5042 // All non-pointer scalars can be cast to ExtVector type. The appropriate 5043 // conversion will take place first from scalar to elt type, and then 5044 // splat from elt type to vector. 5045 if (SrcTy->isPointerType()) 5046 return Diag(R.getBegin(), 5047 diag::err_invalid_conversion_between_vector_and_scalar) 5048 << DestTy << SrcTy << R; 5049 5050 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType(); 5051 ExprResult CastExprRes = Owned(CastExpr); 5052 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy); 5053 if (CastExprRes.isInvalid()) 5054 return ExprError(); 5055 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take(); 5056 5057 Kind = CK_VectorSplat; 5058 return Owned(CastExpr); 5059 } 5060 5061 ExprResult 5062 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5063 Declarator &D, ParsedType &Ty, 5064 SourceLocation RParenLoc, Expr *CastExpr) { 5065 assert(!D.isInvalidType() && (CastExpr != 0) && 5066 "ActOnCastExpr(): missing type or expr"); 5067 5068 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 5069 if (D.isInvalidType()) 5070 return ExprError(); 5071 5072 if (getLangOpts().CPlusPlus) { 5073 // Check that there are no default arguments (C++ only). 5074 CheckExtraCXXDefaultArguments(D); 5075 } 5076 5077 checkUnusedDeclAttributes(D); 5078 5079 QualType castType = castTInfo->getType(); 5080 Ty = CreateParsedType(castType, castTInfo); 5081 5082 bool isVectorLiteral = false; 5083 5084 // Check for an altivec or OpenCL literal, 5085 // i.e. all the elements are integer constants. 5086 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 5087 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 5088 if ((getLangOpts().AltiVec || getLangOpts().OpenCL) 5089 && castType->isVectorType() && (PE || PLE)) { 5090 if (PLE && PLE->getNumExprs() == 0) { 5091 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 5092 return ExprError(); 5093 } 5094 if (PE || PLE->getNumExprs() == 1) { 5095 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 5096 if (!E->getType()->isVectorType()) 5097 isVectorLiteral = true; 5098 } 5099 else 5100 isVectorLiteral = true; 5101 } 5102 5103 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 5104 // then handle it as such. 5105 if (isVectorLiteral) 5106 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 5107 5108 // If the Expr being casted is a ParenListExpr, handle it specially. 5109 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 5110 // sequence of BinOp comma operators. 5111 if (isa<ParenListExpr>(CastExpr)) { 5112 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 5113 if (Result.isInvalid()) return ExprError(); 5114 CastExpr = Result.take(); 5115 } 5116 5117 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 5118 } 5119 5120 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 5121 SourceLocation RParenLoc, Expr *E, 5122 TypeSourceInfo *TInfo) { 5123 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 5124 "Expected paren or paren list expression"); 5125 5126 Expr **exprs; 5127 unsigned numExprs; 5128 Expr *subExpr; 5129 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 5130 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 5131 LiteralLParenLoc = PE->getLParenLoc(); 5132 LiteralRParenLoc = PE->getRParenLoc(); 5133 exprs = PE->getExprs(); 5134 numExprs = PE->getNumExprs(); 5135 } else { // isa<ParenExpr> by assertion at function entrance 5136 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 5137 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 5138 subExpr = cast<ParenExpr>(E)->getSubExpr(); 5139 exprs = &subExpr; 5140 numExprs = 1; 5141 } 5142 5143 QualType Ty = TInfo->getType(); 5144 assert(Ty->isVectorType() && "Expected vector type"); 5145 5146 SmallVector<Expr *, 8> initExprs; 5147 const VectorType *VTy = Ty->getAs<VectorType>(); 5148 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 5149 5150 // '(...)' form of vector initialization in AltiVec: the number of 5151 // initializers must be one or must match the size of the vector. 5152 // If a single value is specified in the initializer then it will be 5153 // replicated to all the components of the vector 5154 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 5155 // The number of initializers must be one or must match the size of the 5156 // vector. If a single value is specified in the initializer then it will 5157 // be replicated to all the components of the vector 5158 if (numExprs == 1) { 5159 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5160 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5161 if (Literal.isInvalid()) 5162 return ExprError(); 5163 Literal = ImpCastExprToType(Literal.take(), ElemTy, 5164 PrepareScalarCast(Literal, ElemTy)); 5165 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 5166 } 5167 else if (numExprs < numElems) { 5168 Diag(E->getExprLoc(), 5169 diag::err_incorrect_number_of_vector_initializers); 5170 return ExprError(); 5171 } 5172 else 5173 initExprs.append(exprs, exprs + numExprs); 5174 } 5175 else { 5176 // For OpenCL, when the number of initializers is a single value, 5177 // it will be replicated to all components of the vector. 5178 if (getLangOpts().OpenCL && 5179 VTy->getVectorKind() == VectorType::GenericVector && 5180 numExprs == 1) { 5181 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5182 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5183 if (Literal.isInvalid()) 5184 return ExprError(); 5185 Literal = ImpCastExprToType(Literal.take(), ElemTy, 5186 PrepareScalarCast(Literal, ElemTy)); 5187 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 5188 } 5189 5190 initExprs.append(exprs, exprs + numExprs); 5191 } 5192 // FIXME: This means that pretty-printing the final AST will produce curly 5193 // braces instead of the original commas. 5194 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 5195 initExprs, LiteralRParenLoc); 5196 initE->setType(Ty); 5197 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 5198 } 5199 5200 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 5201 /// the ParenListExpr into a sequence of comma binary operators. 5202 ExprResult 5203 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 5204 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 5205 if (!E) 5206 return Owned(OrigExpr); 5207 5208 ExprResult Result(E->getExpr(0)); 5209 5210 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 5211 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 5212 E->getExpr(i)); 5213 5214 if (Result.isInvalid()) return ExprError(); 5215 5216 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 5217 } 5218 5219 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 5220 SourceLocation R, 5221 MultiExprArg Val) { 5222 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 5223 return Owned(expr); 5224 } 5225 5226 /// \brief Emit a specialized diagnostic when one expression is a null pointer 5227 /// constant and the other is not a pointer. Returns true if a diagnostic is 5228 /// emitted. 5229 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 5230 SourceLocation QuestionLoc) { 5231 Expr *NullExpr = LHSExpr; 5232 Expr *NonPointerExpr = RHSExpr; 5233 Expr::NullPointerConstantKind NullKind = 5234 NullExpr->isNullPointerConstant(Context, 5235 Expr::NPC_ValueDependentIsNotNull); 5236 5237 if (NullKind == Expr::NPCK_NotNull) { 5238 NullExpr = RHSExpr; 5239 NonPointerExpr = LHSExpr; 5240 NullKind = 5241 NullExpr->isNullPointerConstant(Context, 5242 Expr::NPC_ValueDependentIsNotNull); 5243 } 5244 5245 if (NullKind == Expr::NPCK_NotNull) 5246 return false; 5247 5248 if (NullKind == Expr::NPCK_ZeroExpression) 5249 return false; 5250 5251 if (NullKind == Expr::NPCK_ZeroLiteral) { 5252 // In this case, check to make sure that we got here from a "NULL" 5253 // string in the source code. 5254 NullExpr = NullExpr->IgnoreParenImpCasts(); 5255 SourceLocation loc = NullExpr->getExprLoc(); 5256 if (!findMacroSpelling(loc, "NULL")) 5257 return false; 5258 } 5259 5260 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 5261 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 5262 << NonPointerExpr->getType() << DiagType 5263 << NonPointerExpr->getSourceRange(); 5264 return true; 5265 } 5266 5267 /// \brief Return false if the condition expression is valid, true otherwise. 5268 static bool checkCondition(Sema &S, Expr *Cond) { 5269 QualType CondTy = Cond->getType(); 5270 5271 // C99 6.5.15p2 5272 if (CondTy->isScalarType()) return false; 5273 5274 // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar. 5275 if (S.getLangOpts().OpenCL && CondTy->isVectorType()) 5276 return false; 5277 5278 // Emit the proper error message. 5279 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ? 5280 diag::err_typecheck_cond_expect_scalar : 5281 diag::err_typecheck_cond_expect_scalar_or_vector) 5282 << CondTy; 5283 return true; 5284 } 5285 5286 /// \brief Return false if the two expressions can be converted to a vector, 5287 /// true otherwise 5288 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS, 5289 ExprResult &RHS, 5290 QualType CondTy) { 5291 // Both operands should be of scalar type. 5292 if (!LHS.get()->getType()->isScalarType()) { 5293 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 5294 << CondTy; 5295 return true; 5296 } 5297 if (!RHS.get()->getType()->isScalarType()) { 5298 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 5299 << CondTy; 5300 return true; 5301 } 5302 5303 // Implicity convert these scalars to the type of the condition. 5304 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast); 5305 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast); 5306 return false; 5307 } 5308 5309 /// \brief Handle when one or both operands are void type. 5310 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 5311 ExprResult &RHS) { 5312 Expr *LHSExpr = LHS.get(); 5313 Expr *RHSExpr = RHS.get(); 5314 5315 if (!LHSExpr->getType()->isVoidType()) 5316 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5317 << RHSExpr->getSourceRange(); 5318 if (!RHSExpr->getType()->isVoidType()) 5319 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5320 << LHSExpr->getSourceRange(); 5321 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid); 5322 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid); 5323 return S.Context.VoidTy; 5324 } 5325 5326 /// \brief Return false if the NullExpr can be promoted to PointerTy, 5327 /// true otherwise. 5328 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 5329 QualType PointerTy) { 5330 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 5331 !NullExpr.get()->isNullPointerConstant(S.Context, 5332 Expr::NPC_ValueDependentIsNull)) 5333 return true; 5334 5335 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer); 5336 return false; 5337 } 5338 5339 /// \brief Checks compatibility between two pointers and return the resulting 5340 /// type. 5341 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 5342 ExprResult &RHS, 5343 SourceLocation Loc) { 5344 QualType LHSTy = LHS.get()->getType(); 5345 QualType RHSTy = RHS.get()->getType(); 5346 5347 if (S.Context.hasSameType(LHSTy, RHSTy)) { 5348 // Two identical pointers types are always compatible. 5349 return LHSTy; 5350 } 5351 5352 QualType lhptee, rhptee; 5353 5354 // Get the pointee types. 5355 bool IsBlockPointer = false; 5356 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 5357 lhptee = LHSBTy->getPointeeType(); 5358 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 5359 IsBlockPointer = true; 5360 } else { 5361 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 5362 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 5363 } 5364 5365 // C99 6.5.15p6: If both operands are pointers to compatible types or to 5366 // differently qualified versions of compatible types, the result type is 5367 // a pointer to an appropriately qualified version of the composite 5368 // type. 5369 5370 // Only CVR-qualifiers exist in the standard, and the differently-qualified 5371 // clause doesn't make sense for our extensions. E.g. address space 2 should 5372 // be incompatible with address space 3: they may live on different devices or 5373 // anything. 5374 Qualifiers lhQual = lhptee.getQualifiers(); 5375 Qualifiers rhQual = rhptee.getQualifiers(); 5376 5377 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 5378 lhQual.removeCVRQualifiers(); 5379 rhQual.removeCVRQualifiers(); 5380 5381 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 5382 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 5383 5384 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 5385 5386 if (CompositeTy.isNull()) { 5387 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers) 5388 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5389 << RHS.get()->getSourceRange(); 5390 // In this situation, we assume void* type. No especially good 5391 // reason, but this is what gcc does, and we do have to pick 5392 // to get a consistent AST. 5393 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy); 5394 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 5395 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 5396 return incompatTy; 5397 } 5398 5399 // The pointer types are compatible. 5400 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 5401 if (IsBlockPointer) 5402 ResultTy = S.Context.getBlockPointerType(ResultTy); 5403 else 5404 ResultTy = S.Context.getPointerType(ResultTy); 5405 5406 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast); 5407 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast); 5408 return ResultTy; 5409 } 5410 5411 /// \brief Return the resulting type when the operands are both block pointers. 5412 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 5413 ExprResult &LHS, 5414 ExprResult &RHS, 5415 SourceLocation Loc) { 5416 QualType LHSTy = LHS.get()->getType(); 5417 QualType RHSTy = RHS.get()->getType(); 5418 5419 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 5420 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 5421 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 5422 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5423 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5424 return destType; 5425 } 5426 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 5427 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5428 << RHS.get()->getSourceRange(); 5429 return QualType(); 5430 } 5431 5432 // We have 2 block pointer types. 5433 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 5434 } 5435 5436 /// \brief Return the resulting type when the operands are both pointers. 5437 static QualType 5438 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 5439 ExprResult &RHS, 5440 SourceLocation Loc) { 5441 // get the pointer types 5442 QualType LHSTy = LHS.get()->getType(); 5443 QualType RHSTy = RHS.get()->getType(); 5444 5445 // get the "pointed to" types 5446 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5447 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5448 5449 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 5450 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 5451 // Figure out necessary qualifiers (C99 6.5.15p6) 5452 QualType destPointee 5453 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5454 QualType destType = S.Context.getPointerType(destPointee); 5455 // Add qualifiers if necessary. 5456 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp); 5457 // Promote to void*. 5458 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5459 return destType; 5460 } 5461 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 5462 QualType destPointee 5463 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5464 QualType destType = S.Context.getPointerType(destPointee); 5465 // Add qualifiers if necessary. 5466 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp); 5467 // Promote to void*. 5468 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5469 return destType; 5470 } 5471 5472 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 5473 } 5474 5475 /// \brief Return false if the first expression is not an integer and the second 5476 /// expression is not a pointer, true otherwise. 5477 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 5478 Expr* PointerExpr, SourceLocation Loc, 5479 bool IsIntFirstExpr) { 5480 if (!PointerExpr->getType()->isPointerType() || 5481 !Int.get()->getType()->isIntegerType()) 5482 return false; 5483 5484 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 5485 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 5486 5487 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch) 5488 << Expr1->getType() << Expr2->getType() 5489 << Expr1->getSourceRange() << Expr2->getSourceRange(); 5490 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(), 5491 CK_IntegralToPointer); 5492 return true; 5493 } 5494 5495 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 5496 /// In that case, LHS = cond. 5497 /// C99 6.5.15 5498 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 5499 ExprResult &RHS, ExprValueKind &VK, 5500 ExprObjectKind &OK, 5501 SourceLocation QuestionLoc) { 5502 5503 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 5504 if (!LHSResult.isUsable()) return QualType(); 5505 LHS = LHSResult; 5506 5507 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 5508 if (!RHSResult.isUsable()) return QualType(); 5509 RHS = RHSResult; 5510 5511 // C++ is sufficiently different to merit its own checker. 5512 if (getLangOpts().CPlusPlus) 5513 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 5514 5515 VK = VK_RValue; 5516 OK = OK_Ordinary; 5517 5518 // First, check the condition. 5519 Cond = UsualUnaryConversions(Cond.take()); 5520 if (Cond.isInvalid()) 5521 return QualType(); 5522 if (checkCondition(*this, Cond.get())) 5523 return QualType(); 5524 5525 // Now check the two expressions. 5526 if (LHS.get()->getType()->isVectorType() || 5527 RHS.get()->getType()->isVectorType()) 5528 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false); 5529 5530 UsualArithmeticConversions(LHS, RHS); 5531 if (LHS.isInvalid() || RHS.isInvalid()) 5532 return QualType(); 5533 5534 QualType CondTy = Cond.get()->getType(); 5535 QualType LHSTy = LHS.get()->getType(); 5536 QualType RHSTy = RHS.get()->getType(); 5537 5538 // If the condition is a vector, and both operands are scalar, 5539 // attempt to implicity convert them to the vector type to act like the 5540 // built in select. (OpenCL v1.1 s6.3.i) 5541 if (getLangOpts().OpenCL && CondTy->isVectorType()) 5542 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy)) 5543 return QualType(); 5544 5545 // If both operands have arithmetic type, do the usual arithmetic conversions 5546 // to find a common type: C99 6.5.15p3,5. 5547 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) 5548 return LHS.get()->getType(); 5549 5550 // If both operands are the same structure or union type, the result is that 5551 // type. 5552 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 5553 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 5554 if (LHSRT->getDecl() == RHSRT->getDecl()) 5555 // "If both the operands have structure or union type, the result has 5556 // that type." This implies that CV qualifiers are dropped. 5557 return LHSTy.getUnqualifiedType(); 5558 // FIXME: Type of conditional expression must be complete in C mode. 5559 } 5560 5561 // C99 6.5.15p5: "If both operands have void type, the result has void type." 5562 // The following || allows only one side to be void (a GCC-ism). 5563 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 5564 return checkConditionalVoidType(*this, LHS, RHS); 5565 } 5566 5567 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 5568 // the type of the other operand." 5569 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 5570 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 5571 5572 // All objective-c pointer type analysis is done here. 5573 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 5574 QuestionLoc); 5575 if (LHS.isInvalid() || RHS.isInvalid()) 5576 return QualType(); 5577 if (!compositeType.isNull()) 5578 return compositeType; 5579 5580 5581 // Handle block pointer types. 5582 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 5583 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 5584 QuestionLoc); 5585 5586 // Check constraints for C object pointers types (C99 6.5.15p3,6). 5587 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 5588 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 5589 QuestionLoc); 5590 5591 // GCC compatibility: soften pointer/integer mismatch. Note that 5592 // null pointers have been filtered out by this point. 5593 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 5594 /*isIntFirstExpr=*/true)) 5595 return RHSTy; 5596 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 5597 /*isIntFirstExpr=*/false)) 5598 return LHSTy; 5599 5600 // Emit a better diagnostic if one of the expressions is a null pointer 5601 // constant and the other is not a pointer type. In this case, the user most 5602 // likely forgot to take the address of the other expression. 5603 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 5604 return QualType(); 5605 5606 // Otherwise, the operands are not compatible. 5607 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 5608 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5609 << RHS.get()->getSourceRange(); 5610 return QualType(); 5611 } 5612 5613 /// FindCompositeObjCPointerType - Helper method to find composite type of 5614 /// two objective-c pointer types of the two input expressions. 5615 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 5616 SourceLocation QuestionLoc) { 5617 QualType LHSTy = LHS.get()->getType(); 5618 QualType RHSTy = RHS.get()->getType(); 5619 5620 // Handle things like Class and struct objc_class*. Here we case the result 5621 // to the pseudo-builtin, because that will be implicitly cast back to the 5622 // redefinition type if an attempt is made to access its fields. 5623 if (LHSTy->isObjCClassType() && 5624 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 5625 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 5626 return LHSTy; 5627 } 5628 if (RHSTy->isObjCClassType() && 5629 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 5630 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 5631 return RHSTy; 5632 } 5633 // And the same for struct objc_object* / id 5634 if (LHSTy->isObjCIdType() && 5635 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 5636 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 5637 return LHSTy; 5638 } 5639 if (RHSTy->isObjCIdType() && 5640 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 5641 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 5642 return RHSTy; 5643 } 5644 // And the same for struct objc_selector* / SEL 5645 if (Context.isObjCSelType(LHSTy) && 5646 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 5647 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast); 5648 return LHSTy; 5649 } 5650 if (Context.isObjCSelType(RHSTy) && 5651 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 5652 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast); 5653 return RHSTy; 5654 } 5655 // Check constraints for Objective-C object pointers types. 5656 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 5657 5658 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 5659 // Two identical object pointer types are always compatible. 5660 return LHSTy; 5661 } 5662 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 5663 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 5664 QualType compositeType = LHSTy; 5665 5666 // If both operands are interfaces and either operand can be 5667 // assigned to the other, use that type as the composite 5668 // type. This allows 5669 // xxx ? (A*) a : (B*) b 5670 // where B is a subclass of A. 5671 // 5672 // Additionally, as for assignment, if either type is 'id' 5673 // allow silent coercion. Finally, if the types are 5674 // incompatible then make sure to use 'id' as the composite 5675 // type so the result is acceptable for sending messages to. 5676 5677 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 5678 // It could return the composite type. 5679 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 5680 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 5681 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 5682 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 5683 } else if ((LHSTy->isObjCQualifiedIdType() || 5684 RHSTy->isObjCQualifiedIdType()) && 5685 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 5686 // Need to handle "id<xx>" explicitly. 5687 // GCC allows qualified id and any Objective-C type to devolve to 5688 // id. Currently localizing to here until clear this should be 5689 // part of ObjCQualifiedIdTypesAreCompatible. 5690 compositeType = Context.getObjCIdType(); 5691 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 5692 compositeType = Context.getObjCIdType(); 5693 } else if (!(compositeType = 5694 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) 5695 ; 5696 else { 5697 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 5698 << LHSTy << RHSTy 5699 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5700 QualType incompatTy = Context.getObjCIdType(); 5701 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 5702 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 5703 return incompatTy; 5704 } 5705 // The object pointer types are compatible. 5706 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast); 5707 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast); 5708 return compositeType; 5709 } 5710 // Check Objective-C object pointer types and 'void *' 5711 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 5712 if (getLangOpts().ObjCAutoRefCount) { 5713 // ARC forbids the implicit conversion of object pointers to 'void *', 5714 // so these types are not compatible. 5715 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 5716 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5717 LHS = RHS = true; 5718 return QualType(); 5719 } 5720 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5721 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5722 QualType destPointee 5723 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5724 QualType destType = Context.getPointerType(destPointee); 5725 // Add qualifiers if necessary. 5726 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp); 5727 // Promote to void*. 5728 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5729 return destType; 5730 } 5731 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 5732 if (getLangOpts().ObjCAutoRefCount) { 5733 // ARC forbids the implicit conversion of object pointers to 'void *', 5734 // so these types are not compatible. 5735 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 5736 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5737 LHS = RHS = true; 5738 return QualType(); 5739 } 5740 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5741 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5742 QualType destPointee 5743 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5744 QualType destType = Context.getPointerType(destPointee); 5745 // Add qualifiers if necessary. 5746 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp); 5747 // Promote to void*. 5748 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5749 return destType; 5750 } 5751 return QualType(); 5752 } 5753 5754 /// SuggestParentheses - Emit a note with a fixit hint that wraps 5755 /// ParenRange in parentheses. 5756 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 5757 const PartialDiagnostic &Note, 5758 SourceRange ParenRange) { 5759 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd()); 5760 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 5761 EndLoc.isValid()) { 5762 Self.Diag(Loc, Note) 5763 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 5764 << FixItHint::CreateInsertion(EndLoc, ")"); 5765 } else { 5766 // We can't display the parentheses, so just show the bare note. 5767 Self.Diag(Loc, Note) << ParenRange; 5768 } 5769 } 5770 5771 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 5772 return Opc >= BO_Mul && Opc <= BO_Shr; 5773 } 5774 5775 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 5776 /// expression, either using a built-in or overloaded operator, 5777 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 5778 /// expression. 5779 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 5780 Expr **RHSExprs) { 5781 // Don't strip parenthesis: we should not warn if E is in parenthesis. 5782 E = E->IgnoreImpCasts(); 5783 E = E->IgnoreConversionOperator(); 5784 E = E->IgnoreImpCasts(); 5785 5786 // Built-in binary operator. 5787 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 5788 if (IsArithmeticOp(OP->getOpcode())) { 5789 *Opcode = OP->getOpcode(); 5790 *RHSExprs = OP->getRHS(); 5791 return true; 5792 } 5793 } 5794 5795 // Overloaded operator. 5796 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 5797 if (Call->getNumArgs() != 2) 5798 return false; 5799 5800 // Make sure this is really a binary operator that is safe to pass into 5801 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 5802 OverloadedOperatorKind OO = Call->getOperator(); 5803 if (OO < OO_Plus || OO > OO_Arrow || 5804 OO == OO_PlusPlus || OO == OO_MinusMinus) 5805 return false; 5806 5807 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 5808 if (IsArithmeticOp(OpKind)) { 5809 *Opcode = OpKind; 5810 *RHSExprs = Call->getArg(1); 5811 return true; 5812 } 5813 } 5814 5815 return false; 5816 } 5817 5818 static bool IsLogicOp(BinaryOperatorKind Opc) { 5819 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr); 5820 } 5821 5822 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 5823 /// or is a logical expression such as (x==y) which has int type, but is 5824 /// commonly interpreted as boolean. 5825 static bool ExprLooksBoolean(Expr *E) { 5826 E = E->IgnoreParenImpCasts(); 5827 5828 if (E->getType()->isBooleanType()) 5829 return true; 5830 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 5831 return IsLogicOp(OP->getOpcode()); 5832 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 5833 return OP->getOpcode() == UO_LNot; 5834 5835 return false; 5836 } 5837 5838 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 5839 /// and binary operator are mixed in a way that suggests the programmer assumed 5840 /// the conditional operator has higher precedence, for example: 5841 /// "int x = a + someBinaryCondition ? 1 : 2". 5842 static void DiagnoseConditionalPrecedence(Sema &Self, 5843 SourceLocation OpLoc, 5844 Expr *Condition, 5845 Expr *LHSExpr, 5846 Expr *RHSExpr) { 5847 BinaryOperatorKind CondOpcode; 5848 Expr *CondRHS; 5849 5850 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 5851 return; 5852 if (!ExprLooksBoolean(CondRHS)) 5853 return; 5854 5855 // The condition is an arithmetic binary expression, with a right- 5856 // hand side that looks boolean, so warn. 5857 5858 Self.Diag(OpLoc, diag::warn_precedence_conditional) 5859 << Condition->getSourceRange() 5860 << BinaryOperator::getOpcodeStr(CondOpcode); 5861 5862 SuggestParentheses(Self, OpLoc, 5863 Self.PDiag(diag::note_precedence_silence) 5864 << BinaryOperator::getOpcodeStr(CondOpcode), 5865 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 5866 5867 SuggestParentheses(Self, OpLoc, 5868 Self.PDiag(diag::note_precedence_conditional_first), 5869 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 5870 } 5871 5872 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 5873 /// in the case of a the GNU conditional expr extension. 5874 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 5875 SourceLocation ColonLoc, 5876 Expr *CondExpr, Expr *LHSExpr, 5877 Expr *RHSExpr) { 5878 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 5879 // was the condition. 5880 OpaqueValueExpr *opaqueValue = 0; 5881 Expr *commonExpr = 0; 5882 if (LHSExpr == 0) { 5883 commonExpr = CondExpr; 5884 // Lower out placeholder types first. This is important so that we don't 5885 // try to capture a placeholder. This happens in few cases in C++; such 5886 // as Objective-C++'s dictionary subscripting syntax. 5887 if (commonExpr->hasPlaceholderType()) { 5888 ExprResult result = CheckPlaceholderExpr(commonExpr); 5889 if (!result.isUsable()) return ExprError(); 5890 commonExpr = result.take(); 5891 } 5892 // We usually want to apply unary conversions *before* saving, except 5893 // in the special case of a C++ l-value conditional. 5894 if (!(getLangOpts().CPlusPlus 5895 && !commonExpr->isTypeDependent() 5896 && commonExpr->getValueKind() == RHSExpr->getValueKind() 5897 && commonExpr->isGLValue() 5898 && commonExpr->isOrdinaryOrBitFieldObject() 5899 && RHSExpr->isOrdinaryOrBitFieldObject() 5900 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 5901 ExprResult commonRes = UsualUnaryConversions(commonExpr); 5902 if (commonRes.isInvalid()) 5903 return ExprError(); 5904 commonExpr = commonRes.take(); 5905 } 5906 5907 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 5908 commonExpr->getType(), 5909 commonExpr->getValueKind(), 5910 commonExpr->getObjectKind(), 5911 commonExpr); 5912 LHSExpr = CondExpr = opaqueValue; 5913 } 5914 5915 ExprValueKind VK = VK_RValue; 5916 ExprObjectKind OK = OK_Ordinary; 5917 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 5918 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 5919 VK, OK, QuestionLoc); 5920 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 5921 RHS.isInvalid()) 5922 return ExprError(); 5923 5924 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 5925 RHS.get()); 5926 5927 if (!commonExpr) 5928 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc, 5929 LHS.take(), ColonLoc, 5930 RHS.take(), result, VK, OK)); 5931 5932 return Owned(new (Context) 5933 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(), 5934 RHS.take(), QuestionLoc, ColonLoc, result, VK, 5935 OK)); 5936 } 5937 5938 // checkPointerTypesForAssignment - This is a very tricky routine (despite 5939 // being closely modeled after the C99 spec:-). The odd characteristic of this 5940 // routine is it effectively iqnores the qualifiers on the top level pointee. 5941 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 5942 // FIXME: add a couple examples in this comment. 5943 static Sema::AssignConvertType 5944 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 5945 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 5946 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 5947 5948 // get the "pointed to" type (ignoring qualifiers at the top level) 5949 const Type *lhptee, *rhptee; 5950 Qualifiers lhq, rhq; 5951 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split(); 5952 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split(); 5953 5954 Sema::AssignConvertType ConvTy = Sema::Compatible; 5955 5956 // C99 6.5.16.1p1: This following citation is common to constraints 5957 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 5958 // qualifiers of the type *pointed to* by the right; 5959 Qualifiers lq; 5960 5961 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 5962 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 5963 lhq.compatiblyIncludesObjCLifetime(rhq)) { 5964 // Ignore lifetime for further calculation. 5965 lhq.removeObjCLifetime(); 5966 rhq.removeObjCLifetime(); 5967 } 5968 5969 if (!lhq.compatiblyIncludes(rhq)) { 5970 // Treat address-space mismatches as fatal. TODO: address subspaces 5971 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 5972 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 5973 5974 // It's okay to add or remove GC or lifetime qualifiers when converting to 5975 // and from void*. 5976 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 5977 .compatiblyIncludes( 5978 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 5979 && (lhptee->isVoidType() || rhptee->isVoidType())) 5980 ; // keep old 5981 5982 // Treat lifetime mismatches as fatal. 5983 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 5984 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 5985 5986 // For GCC compatibility, other qualifier mismatches are treated 5987 // as still compatible in C. 5988 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 5989 } 5990 5991 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 5992 // incomplete type and the other is a pointer to a qualified or unqualified 5993 // version of void... 5994 if (lhptee->isVoidType()) { 5995 if (rhptee->isIncompleteOrObjectType()) 5996 return ConvTy; 5997 5998 // As an extension, we allow cast to/from void* to function pointer. 5999 assert(rhptee->isFunctionType()); 6000 return Sema::FunctionVoidPointer; 6001 } 6002 6003 if (rhptee->isVoidType()) { 6004 if (lhptee->isIncompleteOrObjectType()) 6005 return ConvTy; 6006 6007 // As an extension, we allow cast to/from void* to function pointer. 6008 assert(lhptee->isFunctionType()); 6009 return Sema::FunctionVoidPointer; 6010 } 6011 6012 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 6013 // unqualified versions of compatible types, ... 6014 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 6015 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 6016 // Check if the pointee types are compatible ignoring the sign. 6017 // We explicitly check for char so that we catch "char" vs 6018 // "unsigned char" on systems where "char" is unsigned. 6019 if (lhptee->isCharType()) 6020 ltrans = S.Context.UnsignedCharTy; 6021 else if (lhptee->hasSignedIntegerRepresentation()) 6022 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 6023 6024 if (rhptee->isCharType()) 6025 rtrans = S.Context.UnsignedCharTy; 6026 else if (rhptee->hasSignedIntegerRepresentation()) 6027 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 6028 6029 if (ltrans == rtrans) { 6030 // Types are compatible ignoring the sign. Qualifier incompatibility 6031 // takes priority over sign incompatibility because the sign 6032 // warning can be disabled. 6033 if (ConvTy != Sema::Compatible) 6034 return ConvTy; 6035 6036 return Sema::IncompatiblePointerSign; 6037 } 6038 6039 // If we are a multi-level pointer, it's possible that our issue is simply 6040 // one of qualification - e.g. char ** -> const char ** is not allowed. If 6041 // the eventual target type is the same and the pointers have the same 6042 // level of indirection, this must be the issue. 6043 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 6044 do { 6045 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 6046 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 6047 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 6048 6049 if (lhptee == rhptee) 6050 return Sema::IncompatibleNestedPointerQualifiers; 6051 } 6052 6053 // General pointer incompatibility takes priority over qualifiers. 6054 return Sema::IncompatiblePointer; 6055 } 6056 if (!S.getLangOpts().CPlusPlus && 6057 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 6058 return Sema::IncompatiblePointer; 6059 return ConvTy; 6060 } 6061 6062 /// checkBlockPointerTypesForAssignment - This routine determines whether two 6063 /// block pointer types are compatible or whether a block and normal pointer 6064 /// are compatible. It is more restrict than comparing two function pointer 6065 // types. 6066 static Sema::AssignConvertType 6067 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 6068 QualType RHSType) { 6069 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 6070 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 6071 6072 QualType lhptee, rhptee; 6073 6074 // get the "pointed to" type (ignoring qualifiers at the top level) 6075 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 6076 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 6077 6078 // In C++, the types have to match exactly. 6079 if (S.getLangOpts().CPlusPlus) 6080 return Sema::IncompatibleBlockPointer; 6081 6082 Sema::AssignConvertType ConvTy = Sema::Compatible; 6083 6084 // For blocks we enforce that qualifiers are identical. 6085 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 6086 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 6087 6088 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 6089 return Sema::IncompatibleBlockPointer; 6090 6091 return ConvTy; 6092 } 6093 6094 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 6095 /// for assignment compatibility. 6096 static Sema::AssignConvertType 6097 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 6098 QualType RHSType) { 6099 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 6100 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 6101 6102 if (LHSType->isObjCBuiltinType()) { 6103 // Class is not compatible with ObjC object pointers. 6104 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 6105 !RHSType->isObjCQualifiedClassType()) 6106 return Sema::IncompatiblePointer; 6107 return Sema::Compatible; 6108 } 6109 if (RHSType->isObjCBuiltinType()) { 6110 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 6111 !LHSType->isObjCQualifiedClassType()) 6112 return Sema::IncompatiblePointer; 6113 return Sema::Compatible; 6114 } 6115 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 6116 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 6117 6118 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 6119 // make an exception for id<P> 6120 !LHSType->isObjCQualifiedIdType()) 6121 return Sema::CompatiblePointerDiscardsQualifiers; 6122 6123 if (S.Context.typesAreCompatible(LHSType, RHSType)) 6124 return Sema::Compatible; 6125 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 6126 return Sema::IncompatibleObjCQualifiedId; 6127 return Sema::IncompatiblePointer; 6128 } 6129 6130 Sema::AssignConvertType 6131 Sema::CheckAssignmentConstraints(SourceLocation Loc, 6132 QualType LHSType, QualType RHSType) { 6133 // Fake up an opaque expression. We don't actually care about what 6134 // cast operations are required, so if CheckAssignmentConstraints 6135 // adds casts to this they'll be wasted, but fortunately that doesn't 6136 // usually happen on valid code. 6137 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 6138 ExprResult RHSPtr = &RHSExpr; 6139 CastKind K = CK_Invalid; 6140 6141 return CheckAssignmentConstraints(LHSType, RHSPtr, K); 6142 } 6143 6144 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 6145 /// has code to accommodate several GCC extensions when type checking 6146 /// pointers. Here are some objectionable examples that GCC considers warnings: 6147 /// 6148 /// int a, *pint; 6149 /// short *pshort; 6150 /// struct foo *pfoo; 6151 /// 6152 /// pint = pshort; // warning: assignment from incompatible pointer type 6153 /// a = pint; // warning: assignment makes integer from pointer without a cast 6154 /// pint = a; // warning: assignment makes pointer from integer without a cast 6155 /// pint = pfoo; // warning: assignment from incompatible pointer type 6156 /// 6157 /// As a result, the code for dealing with pointers is more complex than the 6158 /// C99 spec dictates. 6159 /// 6160 /// Sets 'Kind' for any result kind except Incompatible. 6161 Sema::AssignConvertType 6162 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 6163 CastKind &Kind) { 6164 QualType RHSType = RHS.get()->getType(); 6165 QualType OrigLHSType = LHSType; 6166 6167 // Get canonical types. We're not formatting these types, just comparing 6168 // them. 6169 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 6170 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 6171 6172 // Common case: no conversion required. 6173 if (LHSType == RHSType) { 6174 Kind = CK_NoOp; 6175 return Compatible; 6176 } 6177 6178 // If we have an atomic type, try a non-atomic assignment, then just add an 6179 // atomic qualification step. 6180 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 6181 Sema::AssignConvertType result = 6182 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 6183 if (result != Compatible) 6184 return result; 6185 if (Kind != CK_NoOp) 6186 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind); 6187 Kind = CK_NonAtomicToAtomic; 6188 return Compatible; 6189 } 6190 6191 // If the left-hand side is a reference type, then we are in a 6192 // (rare!) case where we've allowed the use of references in C, 6193 // e.g., as a parameter type in a built-in function. In this case, 6194 // just make sure that the type referenced is compatible with the 6195 // right-hand side type. The caller is responsible for adjusting 6196 // LHSType so that the resulting expression does not have reference 6197 // type. 6198 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 6199 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 6200 Kind = CK_LValueBitCast; 6201 return Compatible; 6202 } 6203 return Incompatible; 6204 } 6205 6206 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 6207 // to the same ExtVector type. 6208 if (LHSType->isExtVectorType()) { 6209 if (RHSType->isExtVectorType()) 6210 return Incompatible; 6211 if (RHSType->isArithmeticType()) { 6212 // CK_VectorSplat does T -> vector T, so first cast to the 6213 // element type. 6214 QualType elType = cast<ExtVectorType>(LHSType)->getElementType(); 6215 if (elType != RHSType) { 6216 Kind = PrepareScalarCast(RHS, elType); 6217 RHS = ImpCastExprToType(RHS.take(), elType, Kind); 6218 } 6219 Kind = CK_VectorSplat; 6220 return Compatible; 6221 } 6222 } 6223 6224 // Conversions to or from vector type. 6225 if (LHSType->isVectorType() || RHSType->isVectorType()) { 6226 if (LHSType->isVectorType() && RHSType->isVectorType()) { 6227 // Allow assignments of an AltiVec vector type to an equivalent GCC 6228 // vector type and vice versa 6229 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 6230 Kind = CK_BitCast; 6231 return Compatible; 6232 } 6233 6234 // If we are allowing lax vector conversions, and LHS and RHS are both 6235 // vectors, the total size only needs to be the same. This is a bitcast; 6236 // no bits are changed but the result type is different. 6237 if (getLangOpts().LaxVectorConversions && 6238 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) { 6239 Kind = CK_BitCast; 6240 return IncompatibleVectors; 6241 } 6242 } 6243 return Incompatible; 6244 } 6245 6246 // Arithmetic conversions. 6247 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 6248 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 6249 Kind = PrepareScalarCast(RHS, LHSType); 6250 return Compatible; 6251 } 6252 6253 // Conversions to normal pointers. 6254 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 6255 // U* -> T* 6256 if (isa<PointerType>(RHSType)) { 6257 Kind = CK_BitCast; 6258 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 6259 } 6260 6261 // int -> T* 6262 if (RHSType->isIntegerType()) { 6263 Kind = CK_IntegralToPointer; // FIXME: null? 6264 return IntToPointer; 6265 } 6266 6267 // C pointers are not compatible with ObjC object pointers, 6268 // with two exceptions: 6269 if (isa<ObjCObjectPointerType>(RHSType)) { 6270 // - conversions to void* 6271 if (LHSPointer->getPointeeType()->isVoidType()) { 6272 Kind = CK_BitCast; 6273 return Compatible; 6274 } 6275 6276 // - conversions from 'Class' to the redefinition type 6277 if (RHSType->isObjCClassType() && 6278 Context.hasSameType(LHSType, 6279 Context.getObjCClassRedefinitionType())) { 6280 Kind = CK_BitCast; 6281 return Compatible; 6282 } 6283 6284 Kind = CK_BitCast; 6285 return IncompatiblePointer; 6286 } 6287 6288 // U^ -> void* 6289 if (RHSType->getAs<BlockPointerType>()) { 6290 if (LHSPointer->getPointeeType()->isVoidType()) { 6291 Kind = CK_BitCast; 6292 return Compatible; 6293 } 6294 } 6295 6296 return Incompatible; 6297 } 6298 6299 // Conversions to block pointers. 6300 if (isa<BlockPointerType>(LHSType)) { 6301 // U^ -> T^ 6302 if (RHSType->isBlockPointerType()) { 6303 Kind = CK_BitCast; 6304 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 6305 } 6306 6307 // int or null -> T^ 6308 if (RHSType->isIntegerType()) { 6309 Kind = CK_IntegralToPointer; // FIXME: null 6310 return IntToBlockPointer; 6311 } 6312 6313 // id -> T^ 6314 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 6315 Kind = CK_AnyPointerToBlockPointerCast; 6316 return Compatible; 6317 } 6318 6319 // void* -> T^ 6320 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 6321 if (RHSPT->getPointeeType()->isVoidType()) { 6322 Kind = CK_AnyPointerToBlockPointerCast; 6323 return Compatible; 6324 } 6325 6326 return Incompatible; 6327 } 6328 6329 // Conversions to Objective-C pointers. 6330 if (isa<ObjCObjectPointerType>(LHSType)) { 6331 // A* -> B* 6332 if (RHSType->isObjCObjectPointerType()) { 6333 Kind = CK_BitCast; 6334 Sema::AssignConvertType result = 6335 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 6336 if (getLangOpts().ObjCAutoRefCount && 6337 result == Compatible && 6338 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 6339 result = IncompatibleObjCWeakRef; 6340 return result; 6341 } 6342 6343 // int or null -> A* 6344 if (RHSType->isIntegerType()) { 6345 Kind = CK_IntegralToPointer; // FIXME: null 6346 return IntToPointer; 6347 } 6348 6349 // In general, C pointers are not compatible with ObjC object pointers, 6350 // with two exceptions: 6351 if (isa<PointerType>(RHSType)) { 6352 Kind = CK_CPointerToObjCPointerCast; 6353 6354 // - conversions from 'void*' 6355 if (RHSType->isVoidPointerType()) { 6356 return Compatible; 6357 } 6358 6359 // - conversions to 'Class' from its redefinition type 6360 if (LHSType->isObjCClassType() && 6361 Context.hasSameType(RHSType, 6362 Context.getObjCClassRedefinitionType())) { 6363 return Compatible; 6364 } 6365 6366 return IncompatiblePointer; 6367 } 6368 6369 // T^ -> A* 6370 if (RHSType->isBlockPointerType()) { 6371 maybeExtendBlockObject(*this, RHS); 6372 Kind = CK_BlockPointerToObjCPointerCast; 6373 return Compatible; 6374 } 6375 6376 return Incompatible; 6377 } 6378 6379 // Conversions from pointers that are not covered by the above. 6380 if (isa<PointerType>(RHSType)) { 6381 // T* -> _Bool 6382 if (LHSType == Context.BoolTy) { 6383 Kind = CK_PointerToBoolean; 6384 return Compatible; 6385 } 6386 6387 // T* -> int 6388 if (LHSType->isIntegerType()) { 6389 Kind = CK_PointerToIntegral; 6390 return PointerToInt; 6391 } 6392 6393 return Incompatible; 6394 } 6395 6396 // Conversions from Objective-C pointers that are not covered by the above. 6397 if (isa<ObjCObjectPointerType>(RHSType)) { 6398 // T* -> _Bool 6399 if (LHSType == Context.BoolTy) { 6400 Kind = CK_PointerToBoolean; 6401 return Compatible; 6402 } 6403 6404 // T* -> int 6405 if (LHSType->isIntegerType()) { 6406 Kind = CK_PointerToIntegral; 6407 return PointerToInt; 6408 } 6409 6410 return Incompatible; 6411 } 6412 6413 // struct A -> struct B 6414 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 6415 if (Context.typesAreCompatible(LHSType, RHSType)) { 6416 Kind = CK_NoOp; 6417 return Compatible; 6418 } 6419 } 6420 6421 return Incompatible; 6422 } 6423 6424 /// \brief Constructs a transparent union from an expression that is 6425 /// used to initialize the transparent union. 6426 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 6427 ExprResult &EResult, QualType UnionType, 6428 FieldDecl *Field) { 6429 // Build an initializer list that designates the appropriate member 6430 // of the transparent union. 6431 Expr *E = EResult.take(); 6432 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 6433 E, SourceLocation()); 6434 Initializer->setType(UnionType); 6435 Initializer->setInitializedFieldInUnion(Field); 6436 6437 // Build a compound literal constructing a value of the transparent 6438 // union type from this initializer list. 6439 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 6440 EResult = S.Owned( 6441 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 6442 VK_RValue, Initializer, false)); 6443 } 6444 6445 Sema::AssignConvertType 6446 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 6447 ExprResult &RHS) { 6448 QualType RHSType = RHS.get()->getType(); 6449 6450 // If the ArgType is a Union type, we want to handle a potential 6451 // transparent_union GCC extension. 6452 const RecordType *UT = ArgType->getAsUnionType(); 6453 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 6454 return Incompatible; 6455 6456 // The field to initialize within the transparent union. 6457 RecordDecl *UD = UT->getDecl(); 6458 FieldDecl *InitField = 0; 6459 // It's compatible if the expression matches any of the fields. 6460 for (RecordDecl::field_iterator it = UD->field_begin(), 6461 itend = UD->field_end(); 6462 it != itend; ++it) { 6463 if (it->getType()->isPointerType()) { 6464 // If the transparent union contains a pointer type, we allow: 6465 // 1) void pointer 6466 // 2) null pointer constant 6467 if (RHSType->isPointerType()) 6468 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 6469 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast); 6470 InitField = *it; 6471 break; 6472 } 6473 6474 if (RHS.get()->isNullPointerConstant(Context, 6475 Expr::NPC_ValueDependentIsNull)) { 6476 RHS = ImpCastExprToType(RHS.take(), it->getType(), 6477 CK_NullToPointer); 6478 InitField = *it; 6479 break; 6480 } 6481 } 6482 6483 CastKind Kind = CK_Invalid; 6484 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 6485 == Compatible) { 6486 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind); 6487 InitField = *it; 6488 break; 6489 } 6490 } 6491 6492 if (!InitField) 6493 return Incompatible; 6494 6495 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 6496 return Compatible; 6497 } 6498 6499 Sema::AssignConvertType 6500 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, 6501 bool Diagnose, 6502 bool DiagnoseCFAudited) { 6503 if (getLangOpts().CPlusPlus) { 6504 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 6505 // C++ 5.17p3: If the left operand is not of class type, the 6506 // expression is implicitly converted (C++ 4) to the 6507 // cv-unqualified type of the left operand. 6508 ExprResult Res; 6509 if (Diagnose) { 6510 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6511 AA_Assigning); 6512 } else { 6513 ImplicitConversionSequence ICS = 6514 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6515 /*SuppressUserConversions=*/false, 6516 /*AllowExplicit=*/false, 6517 /*InOverloadResolution=*/false, 6518 /*CStyle=*/false, 6519 /*AllowObjCWritebackConversion=*/false); 6520 if (ICS.isFailure()) 6521 return Incompatible; 6522 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6523 ICS, AA_Assigning); 6524 } 6525 if (Res.isInvalid()) 6526 return Incompatible; 6527 Sema::AssignConvertType result = Compatible; 6528 if (getLangOpts().ObjCAutoRefCount && 6529 !CheckObjCARCUnavailableWeakConversion(LHSType, 6530 RHS.get()->getType())) 6531 result = IncompatibleObjCWeakRef; 6532 RHS = Res; 6533 return result; 6534 } 6535 6536 // FIXME: Currently, we fall through and treat C++ classes like C 6537 // structures. 6538 // FIXME: We also fall through for atomics; not sure what should 6539 // happen there, though. 6540 } 6541 6542 // C99 6.5.16.1p1: the left operand is a pointer and the right is 6543 // a null pointer constant. 6544 if ((LHSType->isPointerType() || 6545 LHSType->isObjCObjectPointerType() || 6546 LHSType->isBlockPointerType()) 6547 && RHS.get()->isNullPointerConstant(Context, 6548 Expr::NPC_ValueDependentIsNull)) { 6549 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer); 6550 return Compatible; 6551 } 6552 6553 // This check seems unnatural, however it is necessary to ensure the proper 6554 // conversion of functions/arrays. If the conversion were done for all 6555 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 6556 // expressions that suppress this implicit conversion (&, sizeof). 6557 // 6558 // Suppress this for references: C++ 8.5.3p5. 6559 if (!LHSType->isReferenceType()) { 6560 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 6561 if (RHS.isInvalid()) 6562 return Incompatible; 6563 } 6564 6565 CastKind Kind = CK_Invalid; 6566 Sema::AssignConvertType result = 6567 CheckAssignmentConstraints(LHSType, RHS, Kind); 6568 6569 // C99 6.5.16.1p2: The value of the right operand is converted to the 6570 // type of the assignment expression. 6571 // CheckAssignmentConstraints allows the left-hand side to be a reference, 6572 // so that we can use references in built-in functions even in C. 6573 // The getNonReferenceType() call makes sure that the resulting expression 6574 // does not have reference type. 6575 if (result != Incompatible && RHS.get()->getType() != LHSType) { 6576 QualType Ty = LHSType.getNonLValueExprType(Context); 6577 Expr *E = RHS.take(); 6578 if (getLangOpts().ObjCAutoRefCount) 6579 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 6580 DiagnoseCFAudited); 6581 RHS = ImpCastExprToType(E, Ty, Kind); 6582 } 6583 return result; 6584 } 6585 6586 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 6587 ExprResult &RHS) { 6588 Diag(Loc, diag::err_typecheck_invalid_operands) 6589 << LHS.get()->getType() << RHS.get()->getType() 6590 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6591 return QualType(); 6592 } 6593 6594 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 6595 SourceLocation Loc, bool IsCompAssign) { 6596 if (!IsCompAssign) { 6597 LHS = DefaultFunctionArrayLvalueConversion(LHS.take()); 6598 if (LHS.isInvalid()) 6599 return QualType(); 6600 } 6601 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 6602 if (RHS.isInvalid()) 6603 return QualType(); 6604 6605 // For conversion purposes, we ignore any qualifiers. 6606 // For example, "const float" and "float" are equivalent. 6607 QualType LHSType = 6608 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6609 QualType RHSType = 6610 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6611 6612 // If the vector types are identical, return. 6613 if (LHSType == RHSType) 6614 return LHSType; 6615 6616 // Handle the case of equivalent AltiVec and GCC vector types 6617 if (LHSType->isVectorType() && RHSType->isVectorType() && 6618 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 6619 if (LHSType->isExtVectorType()) { 6620 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6621 return LHSType; 6622 } 6623 6624 if (!IsCompAssign) 6625 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 6626 return RHSType; 6627 } 6628 6629 if (getLangOpts().LaxVectorConversions && 6630 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) { 6631 // If we are allowing lax vector conversions, and LHS and RHS are both 6632 // vectors, the total size only needs to be the same. This is a 6633 // bitcast; no bits are changed but the result type is different. 6634 // FIXME: Should we really be allowing this? 6635 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6636 return LHSType; 6637 } 6638 6639 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can 6640 // swap back (so that we don't reverse the inputs to a subtract, for instance. 6641 bool swapped = false; 6642 if (RHSType->isExtVectorType() && !IsCompAssign) { 6643 swapped = true; 6644 std::swap(RHS, LHS); 6645 std::swap(RHSType, LHSType); 6646 } 6647 6648 // Handle the case of an ext vector and scalar. 6649 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) { 6650 QualType EltTy = LV->getElementType(); 6651 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) { 6652 int order = Context.getIntegerTypeOrder(EltTy, RHSType); 6653 if (order > 0) 6654 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast); 6655 if (order >= 0) { 6656 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat); 6657 if (swapped) std::swap(RHS, LHS); 6658 return LHSType; 6659 } 6660 } 6661 if (EltTy->isRealFloatingType() && RHSType->isScalarType()) { 6662 if (RHSType->isRealFloatingType()) { 6663 int order = Context.getFloatingTypeOrder(EltTy, RHSType); 6664 if (order > 0) 6665 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast); 6666 if (order >= 0) { 6667 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat); 6668 if (swapped) std::swap(RHS, LHS); 6669 return LHSType; 6670 } 6671 } 6672 if (RHSType->isIntegralType(Context)) { 6673 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralToFloating); 6674 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat); 6675 if (swapped) std::swap(RHS, LHS); 6676 return LHSType; 6677 } 6678 } 6679 } 6680 6681 // Vectors of different size or scalar and non-ext-vector are errors. 6682 if (swapped) std::swap(RHS, LHS); 6683 Diag(Loc, diag::err_typecheck_vector_not_convertable) 6684 << LHS.get()->getType() << RHS.get()->getType() 6685 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6686 return QualType(); 6687 } 6688 6689 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 6690 // expression. These are mainly cases where the null pointer is used as an 6691 // integer instead of a pointer. 6692 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 6693 SourceLocation Loc, bool IsCompare) { 6694 // The canonical way to check for a GNU null is with isNullPointerConstant, 6695 // but we use a bit of a hack here for speed; this is a relatively 6696 // hot path, and isNullPointerConstant is slow. 6697 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 6698 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 6699 6700 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 6701 6702 // Avoid analyzing cases where the result will either be invalid (and 6703 // diagnosed as such) or entirely valid and not something to warn about. 6704 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 6705 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 6706 return; 6707 6708 // Comparison operations would not make sense with a null pointer no matter 6709 // what the other expression is. 6710 if (!IsCompare) { 6711 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 6712 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 6713 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 6714 return; 6715 } 6716 6717 // The rest of the operations only make sense with a null pointer 6718 // if the other expression is a pointer. 6719 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 6720 NonNullType->canDecayToPointerType()) 6721 return; 6722 6723 S.Diag(Loc, diag::warn_null_in_comparison_operation) 6724 << LHSNull /* LHS is NULL */ << NonNullType 6725 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6726 } 6727 6728 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 6729 SourceLocation Loc, 6730 bool IsCompAssign, bool IsDiv) { 6731 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6732 6733 if (LHS.get()->getType()->isVectorType() || 6734 RHS.get()->getType()->isVectorType()) 6735 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6736 6737 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 6738 if (LHS.isInvalid() || RHS.isInvalid()) 6739 return QualType(); 6740 6741 6742 if (compType.isNull() || !compType->isArithmeticType()) 6743 return InvalidOperands(Loc, LHS, RHS); 6744 6745 // Check for division by zero. 6746 llvm::APSInt RHSValue; 6747 if (IsDiv && !RHS.get()->isValueDependent() && 6748 RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0) 6749 DiagRuntimeBehavior(Loc, RHS.get(), 6750 PDiag(diag::warn_division_by_zero) 6751 << RHS.get()->getSourceRange()); 6752 6753 return compType; 6754 } 6755 6756 QualType Sema::CheckRemainderOperands( 6757 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 6758 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6759 6760 if (LHS.get()->getType()->isVectorType() || 6761 RHS.get()->getType()->isVectorType()) { 6762 if (LHS.get()->getType()->hasIntegerRepresentation() && 6763 RHS.get()->getType()->hasIntegerRepresentation()) 6764 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6765 return InvalidOperands(Loc, LHS, RHS); 6766 } 6767 6768 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 6769 if (LHS.isInvalid() || RHS.isInvalid()) 6770 return QualType(); 6771 6772 if (compType.isNull() || !compType->isIntegerType()) 6773 return InvalidOperands(Loc, LHS, RHS); 6774 6775 // Check for remainder by zero. 6776 llvm::APSInt RHSValue; 6777 if (!RHS.get()->isValueDependent() && 6778 RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0) 6779 DiagRuntimeBehavior(Loc, RHS.get(), 6780 PDiag(diag::warn_remainder_by_zero) 6781 << RHS.get()->getSourceRange()); 6782 6783 return compType; 6784 } 6785 6786 /// \brief Diagnose invalid arithmetic on two void pointers. 6787 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 6788 Expr *LHSExpr, Expr *RHSExpr) { 6789 S.Diag(Loc, S.getLangOpts().CPlusPlus 6790 ? diag::err_typecheck_pointer_arith_void_type 6791 : diag::ext_gnu_void_ptr) 6792 << 1 /* two pointers */ << LHSExpr->getSourceRange() 6793 << RHSExpr->getSourceRange(); 6794 } 6795 6796 /// \brief Diagnose invalid arithmetic on a void pointer. 6797 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 6798 Expr *Pointer) { 6799 S.Diag(Loc, S.getLangOpts().CPlusPlus 6800 ? diag::err_typecheck_pointer_arith_void_type 6801 : diag::ext_gnu_void_ptr) 6802 << 0 /* one pointer */ << Pointer->getSourceRange(); 6803 } 6804 6805 /// \brief Diagnose invalid arithmetic on two function pointers. 6806 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 6807 Expr *LHS, Expr *RHS) { 6808 assert(LHS->getType()->isAnyPointerType()); 6809 assert(RHS->getType()->isAnyPointerType()); 6810 S.Diag(Loc, S.getLangOpts().CPlusPlus 6811 ? diag::err_typecheck_pointer_arith_function_type 6812 : diag::ext_gnu_ptr_func_arith) 6813 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 6814 // We only show the second type if it differs from the first. 6815 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 6816 RHS->getType()) 6817 << RHS->getType()->getPointeeType() 6818 << LHS->getSourceRange() << RHS->getSourceRange(); 6819 } 6820 6821 /// \brief Diagnose invalid arithmetic on a function pointer. 6822 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 6823 Expr *Pointer) { 6824 assert(Pointer->getType()->isAnyPointerType()); 6825 S.Diag(Loc, S.getLangOpts().CPlusPlus 6826 ? diag::err_typecheck_pointer_arith_function_type 6827 : diag::ext_gnu_ptr_func_arith) 6828 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 6829 << 0 /* one pointer, so only one type */ 6830 << Pointer->getSourceRange(); 6831 } 6832 6833 /// \brief Emit error if Operand is incomplete pointer type 6834 /// 6835 /// \returns True if pointer has incomplete type 6836 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 6837 Expr *Operand) { 6838 assert(Operand->getType()->isAnyPointerType() && 6839 !Operand->getType()->isDependentType()); 6840 QualType PointeeTy = Operand->getType()->getPointeeType(); 6841 return S.RequireCompleteType(Loc, PointeeTy, 6842 diag::err_typecheck_arithmetic_incomplete_type, 6843 PointeeTy, Operand->getSourceRange()); 6844 } 6845 6846 /// \brief Check the validity of an arithmetic pointer operand. 6847 /// 6848 /// If the operand has pointer type, this code will check for pointer types 6849 /// which are invalid in arithmetic operations. These will be diagnosed 6850 /// appropriately, including whether or not the use is supported as an 6851 /// extension. 6852 /// 6853 /// \returns True when the operand is valid to use (even if as an extension). 6854 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 6855 Expr *Operand) { 6856 if (!Operand->getType()->isAnyPointerType()) return true; 6857 6858 QualType PointeeTy = Operand->getType()->getPointeeType(); 6859 if (PointeeTy->isVoidType()) { 6860 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 6861 return !S.getLangOpts().CPlusPlus; 6862 } 6863 if (PointeeTy->isFunctionType()) { 6864 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 6865 return !S.getLangOpts().CPlusPlus; 6866 } 6867 6868 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 6869 6870 return true; 6871 } 6872 6873 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 6874 /// operands. 6875 /// 6876 /// This routine will diagnose any invalid arithmetic on pointer operands much 6877 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 6878 /// for emitting a single diagnostic even for operations where both LHS and RHS 6879 /// are (potentially problematic) pointers. 6880 /// 6881 /// \returns True when the operand is valid to use (even if as an extension). 6882 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 6883 Expr *LHSExpr, Expr *RHSExpr) { 6884 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 6885 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 6886 if (!isLHSPointer && !isRHSPointer) return true; 6887 6888 QualType LHSPointeeTy, RHSPointeeTy; 6889 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 6890 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 6891 6892 // Check for arithmetic on pointers to incomplete types. 6893 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 6894 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 6895 if (isLHSVoidPtr || isRHSVoidPtr) { 6896 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 6897 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 6898 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 6899 6900 return !S.getLangOpts().CPlusPlus; 6901 } 6902 6903 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 6904 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 6905 if (isLHSFuncPtr || isRHSFuncPtr) { 6906 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 6907 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 6908 RHSExpr); 6909 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 6910 6911 return !S.getLangOpts().CPlusPlus; 6912 } 6913 6914 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 6915 return false; 6916 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 6917 return false; 6918 6919 return true; 6920 } 6921 6922 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 6923 /// literal. 6924 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 6925 Expr *LHSExpr, Expr *RHSExpr) { 6926 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 6927 Expr* IndexExpr = RHSExpr; 6928 if (!StrExpr) { 6929 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 6930 IndexExpr = LHSExpr; 6931 } 6932 6933 bool IsStringPlusInt = StrExpr && 6934 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 6935 if (!IsStringPlusInt) 6936 return; 6937 6938 llvm::APSInt index; 6939 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 6940 unsigned StrLenWithNull = StrExpr->getLength() + 1; 6941 if (index.isNonNegative() && 6942 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 6943 index.isUnsigned())) 6944 return; 6945 } 6946 6947 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 6948 Self.Diag(OpLoc, diag::warn_string_plus_int) 6949 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 6950 6951 // Only print a fixit for "str" + int, not for int + "str". 6952 if (IndexExpr == RHSExpr) { 6953 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 6954 Self.Diag(OpLoc, diag::note_string_plus_int_silence) 6955 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 6956 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 6957 << FixItHint::CreateInsertion(EndLoc, "]"); 6958 } else 6959 Self.Diag(OpLoc, diag::note_string_plus_int_silence); 6960 } 6961 6962 /// \brief Emit error when two pointers are incompatible. 6963 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 6964 Expr *LHSExpr, Expr *RHSExpr) { 6965 assert(LHSExpr->getType()->isAnyPointerType()); 6966 assert(RHSExpr->getType()->isAnyPointerType()); 6967 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 6968 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 6969 << RHSExpr->getSourceRange(); 6970 } 6971 6972 QualType Sema::CheckAdditionOperands( // C99 6.5.6 6973 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 6974 QualType* CompLHSTy) { 6975 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6976 6977 if (LHS.get()->getType()->isVectorType() || 6978 RHS.get()->getType()->isVectorType()) { 6979 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 6980 if (CompLHSTy) *CompLHSTy = compType; 6981 return compType; 6982 } 6983 6984 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 6985 if (LHS.isInvalid() || RHS.isInvalid()) 6986 return QualType(); 6987 6988 // Diagnose "string literal" '+' int. 6989 if (Opc == BO_Add) 6990 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 6991 6992 // handle the common case first (both operands are arithmetic). 6993 if (!compType.isNull() && compType->isArithmeticType()) { 6994 if (CompLHSTy) *CompLHSTy = compType; 6995 return compType; 6996 } 6997 6998 // Type-checking. Ultimately the pointer's going to be in PExp; 6999 // note that we bias towards the LHS being the pointer. 7000 Expr *PExp = LHS.get(), *IExp = RHS.get(); 7001 7002 bool isObjCPointer; 7003 if (PExp->getType()->isPointerType()) { 7004 isObjCPointer = false; 7005 } else if (PExp->getType()->isObjCObjectPointerType()) { 7006 isObjCPointer = true; 7007 } else { 7008 std::swap(PExp, IExp); 7009 if (PExp->getType()->isPointerType()) { 7010 isObjCPointer = false; 7011 } else if (PExp->getType()->isObjCObjectPointerType()) { 7012 isObjCPointer = true; 7013 } else { 7014 return InvalidOperands(Loc, LHS, RHS); 7015 } 7016 } 7017 assert(PExp->getType()->isAnyPointerType()); 7018 7019 if (!IExp->getType()->isIntegerType()) 7020 return InvalidOperands(Loc, LHS, RHS); 7021 7022 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 7023 return QualType(); 7024 7025 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 7026 return QualType(); 7027 7028 // Check array bounds for pointer arithemtic 7029 CheckArrayAccess(PExp, IExp); 7030 7031 if (CompLHSTy) { 7032 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 7033 if (LHSTy.isNull()) { 7034 LHSTy = LHS.get()->getType(); 7035 if (LHSTy->isPromotableIntegerType()) 7036 LHSTy = Context.getPromotedIntegerType(LHSTy); 7037 } 7038 *CompLHSTy = LHSTy; 7039 } 7040 7041 return PExp->getType(); 7042 } 7043 7044 // C99 6.5.6 7045 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 7046 SourceLocation Loc, 7047 QualType* CompLHSTy) { 7048 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7049 7050 if (LHS.get()->getType()->isVectorType() || 7051 RHS.get()->getType()->isVectorType()) { 7052 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 7053 if (CompLHSTy) *CompLHSTy = compType; 7054 return compType; 7055 } 7056 7057 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 7058 if (LHS.isInvalid() || RHS.isInvalid()) 7059 return QualType(); 7060 7061 // Enforce type constraints: C99 6.5.6p3. 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 // Either ptr - int or ptr - ptr. 7070 if (LHS.get()->getType()->isAnyPointerType()) { 7071 QualType lpointee = LHS.get()->getType()->getPointeeType(); 7072 7073 // Diagnose bad cases where we step over interface counts. 7074 if (LHS.get()->getType()->isObjCObjectPointerType() && 7075 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 7076 return QualType(); 7077 7078 // The result type of a pointer-int computation is the pointer type. 7079 if (RHS.get()->getType()->isIntegerType()) { 7080 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 7081 return QualType(); 7082 7083 // Check array bounds for pointer arithemtic 7084 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0, 7085 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 7086 7087 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 7088 return LHS.get()->getType(); 7089 } 7090 7091 // Handle pointer-pointer subtractions. 7092 if (const PointerType *RHSPTy 7093 = RHS.get()->getType()->getAs<PointerType>()) { 7094 QualType rpointee = RHSPTy->getPointeeType(); 7095 7096 if (getLangOpts().CPlusPlus) { 7097 // Pointee types must be the same: C++ [expr.add] 7098 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 7099 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 7100 } 7101 } else { 7102 // Pointee types must be compatible C99 6.5.6p3 7103 if (!Context.typesAreCompatible( 7104 Context.getCanonicalType(lpointee).getUnqualifiedType(), 7105 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 7106 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 7107 return QualType(); 7108 } 7109 } 7110 7111 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 7112 LHS.get(), RHS.get())) 7113 return QualType(); 7114 7115 // The pointee type may have zero size. As an extension, a structure or 7116 // union may have zero size or an array may have zero length. In this 7117 // case subtraction does not make sense. 7118 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 7119 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 7120 if (ElementSize.isZero()) { 7121 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 7122 << rpointee.getUnqualifiedType() 7123 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7124 } 7125 } 7126 7127 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 7128 return Context.getPointerDiffType(); 7129 } 7130 } 7131 7132 return InvalidOperands(Loc, LHS, RHS); 7133 } 7134 7135 static bool isScopedEnumerationType(QualType T) { 7136 if (const EnumType *ET = dyn_cast<EnumType>(T)) 7137 return ET->getDecl()->isScoped(); 7138 return false; 7139 } 7140 7141 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 7142 SourceLocation Loc, unsigned Opc, 7143 QualType LHSType) { 7144 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 7145 // so skip remaining warnings as we don't want to modify values within Sema. 7146 if (S.getLangOpts().OpenCL) 7147 return; 7148 7149 llvm::APSInt Right; 7150 // Check right/shifter operand 7151 if (RHS.get()->isValueDependent() || 7152 !RHS.get()->isIntegerConstantExpr(Right, S.Context)) 7153 return; 7154 7155 if (Right.isNegative()) { 7156 S.DiagRuntimeBehavior(Loc, RHS.get(), 7157 S.PDiag(diag::warn_shift_negative) 7158 << RHS.get()->getSourceRange()); 7159 return; 7160 } 7161 llvm::APInt LeftBits(Right.getBitWidth(), 7162 S.Context.getTypeSize(LHS.get()->getType())); 7163 if (Right.uge(LeftBits)) { 7164 S.DiagRuntimeBehavior(Loc, RHS.get(), 7165 S.PDiag(diag::warn_shift_gt_typewidth) 7166 << RHS.get()->getSourceRange()); 7167 return; 7168 } 7169 if (Opc != BO_Shl) 7170 return; 7171 7172 // When left shifting an ICE which is signed, we can check for overflow which 7173 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 7174 // integers have defined behavior modulo one more than the maximum value 7175 // representable in the result type, so never warn for those. 7176 llvm::APSInt Left; 7177 if (LHS.get()->isValueDependent() || 7178 !LHS.get()->isIntegerConstantExpr(Left, S.Context) || 7179 LHSType->hasUnsignedIntegerRepresentation()) 7180 return; 7181 llvm::APInt ResultBits = 7182 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 7183 if (LeftBits.uge(ResultBits)) 7184 return; 7185 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 7186 Result = Result.shl(Right); 7187 7188 // Print the bit representation of the signed integer as an unsigned 7189 // hexadecimal number. 7190 SmallString<40> HexResult; 7191 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 7192 7193 // If we are only missing a sign bit, this is less likely to result in actual 7194 // bugs -- if the result is cast back to an unsigned type, it will have the 7195 // expected value. Thus we place this behind a different warning that can be 7196 // turned off separately if needed. 7197 if (LeftBits == ResultBits - 1) { 7198 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 7199 << HexResult.str() << LHSType 7200 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7201 return; 7202 } 7203 7204 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 7205 << HexResult.str() << Result.getMinSignedBits() << LHSType 7206 << Left.getBitWidth() << LHS.get()->getSourceRange() 7207 << RHS.get()->getSourceRange(); 7208 } 7209 7210 // C99 6.5.7 7211 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 7212 SourceLocation Loc, unsigned Opc, 7213 bool IsCompAssign) { 7214 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7215 7216 // Vector shifts promote their scalar inputs to vector type. 7217 if (LHS.get()->getType()->isVectorType() || 7218 RHS.get()->getType()->isVectorType()) 7219 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 7220 7221 // Shifts don't perform usual arithmetic conversions, they just do integer 7222 // promotions on each operand. C99 6.5.7p3 7223 7224 // For the LHS, do usual unary conversions, but then reset them away 7225 // if this is a compound assignment. 7226 ExprResult OldLHS = LHS; 7227 LHS = UsualUnaryConversions(LHS.take()); 7228 if (LHS.isInvalid()) 7229 return QualType(); 7230 QualType LHSType = LHS.get()->getType(); 7231 if (IsCompAssign) LHS = OldLHS; 7232 7233 // The RHS is simpler. 7234 RHS = UsualUnaryConversions(RHS.take()); 7235 if (RHS.isInvalid()) 7236 return QualType(); 7237 QualType RHSType = RHS.get()->getType(); 7238 7239 // C99 6.5.7p2: Each of the operands shall have integer type. 7240 if (!LHSType->hasIntegerRepresentation() || 7241 !RHSType->hasIntegerRepresentation()) 7242 return InvalidOperands(Loc, LHS, RHS); 7243 7244 // C++0x: Don't allow scoped enums. FIXME: Use something better than 7245 // hasIntegerRepresentation() above instead of this. 7246 if (isScopedEnumerationType(LHSType) || 7247 isScopedEnumerationType(RHSType)) { 7248 return InvalidOperands(Loc, LHS, RHS); 7249 } 7250 // Sanity-check shift operands 7251 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 7252 7253 // "The type of the result is that of the promoted left operand." 7254 return LHSType; 7255 } 7256 7257 static bool IsWithinTemplateSpecialization(Decl *D) { 7258 if (DeclContext *DC = D->getDeclContext()) { 7259 if (isa<ClassTemplateSpecializationDecl>(DC)) 7260 return true; 7261 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 7262 return FD->isFunctionTemplateSpecialization(); 7263 } 7264 return false; 7265 } 7266 7267 /// If two different enums are compared, raise a warning. 7268 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 7269 Expr *RHS) { 7270 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 7271 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 7272 7273 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 7274 if (!LHSEnumType) 7275 return; 7276 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 7277 if (!RHSEnumType) 7278 return; 7279 7280 // Ignore anonymous enums. 7281 if (!LHSEnumType->getDecl()->getIdentifier()) 7282 return; 7283 if (!RHSEnumType->getDecl()->getIdentifier()) 7284 return; 7285 7286 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 7287 return; 7288 7289 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 7290 << LHSStrippedType << RHSStrippedType 7291 << LHS->getSourceRange() << RHS->getSourceRange(); 7292 } 7293 7294 /// \brief Diagnose bad pointer comparisons. 7295 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 7296 ExprResult &LHS, ExprResult &RHS, 7297 bool IsError) { 7298 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 7299 : diag::ext_typecheck_comparison_of_distinct_pointers) 7300 << LHS.get()->getType() << RHS.get()->getType() 7301 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7302 } 7303 7304 /// \brief Returns false if the pointers are converted to a composite type, 7305 /// true otherwise. 7306 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 7307 ExprResult &LHS, ExprResult &RHS) { 7308 // C++ [expr.rel]p2: 7309 // [...] Pointer conversions (4.10) and qualification 7310 // conversions (4.4) are performed on pointer operands (or on 7311 // a pointer operand and a null pointer constant) to bring 7312 // them to their composite pointer type. [...] 7313 // 7314 // C++ [expr.eq]p1 uses the same notion for (in)equality 7315 // comparisons of pointers. 7316 7317 // C++ [expr.eq]p2: 7318 // In addition, pointers to members can be compared, or a pointer to 7319 // member and a null pointer constant. Pointer to member conversions 7320 // (4.11) and qualification conversions (4.4) are performed to bring 7321 // them to a common type. If one operand is a null pointer constant, 7322 // the common type is the type of the other operand. Otherwise, the 7323 // common type is a pointer to member type similar (4.4) to the type 7324 // of one of the operands, with a cv-qualification signature (4.4) 7325 // that is the union of the cv-qualification signatures of the operand 7326 // types. 7327 7328 QualType LHSType = LHS.get()->getType(); 7329 QualType RHSType = RHS.get()->getType(); 7330 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 7331 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 7332 7333 bool NonStandardCompositeType = false; 7334 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType; 7335 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 7336 if (T.isNull()) { 7337 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 7338 return true; 7339 } 7340 7341 if (NonStandardCompositeType) 7342 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 7343 << LHSType << RHSType << T << LHS.get()->getSourceRange() 7344 << RHS.get()->getSourceRange(); 7345 7346 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast); 7347 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast); 7348 return false; 7349 } 7350 7351 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 7352 ExprResult &LHS, 7353 ExprResult &RHS, 7354 bool IsError) { 7355 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 7356 : diag::ext_typecheck_comparison_of_fptr_to_void) 7357 << LHS.get()->getType() << RHS.get()->getType() 7358 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7359 } 7360 7361 static bool isObjCObjectLiteral(ExprResult &E) { 7362 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 7363 case Stmt::ObjCArrayLiteralClass: 7364 case Stmt::ObjCDictionaryLiteralClass: 7365 case Stmt::ObjCStringLiteralClass: 7366 case Stmt::ObjCBoxedExprClass: 7367 return true; 7368 default: 7369 // Note that ObjCBoolLiteral is NOT an object literal! 7370 return false; 7371 } 7372 } 7373 7374 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 7375 const ObjCObjectPointerType *Type = 7376 LHS->getType()->getAs<ObjCObjectPointerType>(); 7377 7378 // If this is not actually an Objective-C object, bail out. 7379 if (!Type) 7380 return false; 7381 7382 // Get the LHS object's interface type. 7383 QualType InterfaceType = Type->getPointeeType(); 7384 if (const ObjCObjectType *iQFaceTy = 7385 InterfaceType->getAsObjCQualifiedInterfaceType()) 7386 InterfaceType = iQFaceTy->getBaseType(); 7387 7388 // If the RHS isn't an Objective-C object, bail out. 7389 if (!RHS->getType()->isObjCObjectPointerType()) 7390 return false; 7391 7392 // Try to find the -isEqual: method. 7393 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 7394 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 7395 InterfaceType, 7396 /*instance=*/true); 7397 if (!Method) { 7398 if (Type->isObjCIdType()) { 7399 // For 'id', just check the global pool. 7400 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 7401 /*receiverId=*/true, 7402 /*warn=*/false); 7403 } else { 7404 // Check protocols. 7405 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 7406 /*instance=*/true); 7407 } 7408 } 7409 7410 if (!Method) 7411 return false; 7412 7413 QualType T = Method->param_begin()[0]->getType(); 7414 if (!T->isObjCObjectPointerType()) 7415 return false; 7416 7417 QualType R = Method->getResultType(); 7418 if (!R->isScalarType()) 7419 return false; 7420 7421 return true; 7422 } 7423 7424 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 7425 FromE = FromE->IgnoreParenImpCasts(); 7426 switch (FromE->getStmtClass()) { 7427 default: 7428 break; 7429 case Stmt::ObjCStringLiteralClass: 7430 // "string literal" 7431 return LK_String; 7432 case Stmt::ObjCArrayLiteralClass: 7433 // "array literal" 7434 return LK_Array; 7435 case Stmt::ObjCDictionaryLiteralClass: 7436 // "dictionary literal" 7437 return LK_Dictionary; 7438 case Stmt::BlockExprClass: 7439 return LK_Block; 7440 case Stmt::ObjCBoxedExprClass: { 7441 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 7442 switch (Inner->getStmtClass()) { 7443 case Stmt::IntegerLiteralClass: 7444 case Stmt::FloatingLiteralClass: 7445 case Stmt::CharacterLiteralClass: 7446 case Stmt::ObjCBoolLiteralExprClass: 7447 case Stmt::CXXBoolLiteralExprClass: 7448 // "numeric literal" 7449 return LK_Numeric; 7450 case Stmt::ImplicitCastExprClass: { 7451 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 7452 // Boolean literals can be represented by implicit casts. 7453 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 7454 return LK_Numeric; 7455 break; 7456 } 7457 default: 7458 break; 7459 } 7460 return LK_Boxed; 7461 } 7462 } 7463 return LK_None; 7464 } 7465 7466 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 7467 ExprResult &LHS, ExprResult &RHS, 7468 BinaryOperator::Opcode Opc){ 7469 Expr *Literal; 7470 Expr *Other; 7471 if (isObjCObjectLiteral(LHS)) { 7472 Literal = LHS.get(); 7473 Other = RHS.get(); 7474 } else { 7475 Literal = RHS.get(); 7476 Other = LHS.get(); 7477 } 7478 7479 // Don't warn on comparisons against nil. 7480 Other = Other->IgnoreParenCasts(); 7481 if (Other->isNullPointerConstant(S.getASTContext(), 7482 Expr::NPC_ValueDependentIsNotNull)) 7483 return; 7484 7485 // This should be kept in sync with warn_objc_literal_comparison. 7486 // LK_String should always be after the other literals, since it has its own 7487 // warning flag. 7488 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 7489 assert(LiteralKind != Sema::LK_Block); 7490 if (LiteralKind == Sema::LK_None) { 7491 llvm_unreachable("Unknown Objective-C object literal kind"); 7492 } 7493 7494 if (LiteralKind == Sema::LK_String) 7495 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 7496 << Literal->getSourceRange(); 7497 else 7498 S.Diag(Loc, diag::warn_objc_literal_comparison) 7499 << LiteralKind << Literal->getSourceRange(); 7500 7501 if (BinaryOperator::isEqualityOp(Opc) && 7502 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 7503 SourceLocation Start = LHS.get()->getLocStart(); 7504 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 7505 CharSourceRange OpRange = 7506 CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc)); 7507 7508 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 7509 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 7510 << FixItHint::CreateReplacement(OpRange, " isEqual:") 7511 << FixItHint::CreateInsertion(End, "]"); 7512 } 7513 } 7514 7515 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS, 7516 ExprResult &RHS, 7517 SourceLocation Loc, 7518 unsigned OpaqueOpc) { 7519 // This checking requires bools. 7520 if (!S.getLangOpts().Bool) return; 7521 7522 // Check that left hand side is !something. 7523 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 7524 if (!UO || UO->getOpcode() != UO_LNot) return; 7525 7526 // Only check if the right hand side is non-bool arithmetic type. 7527 if (RHS.get()->getType()->isBooleanType()) return; 7528 7529 // Make sure that the something in !something is not bool. 7530 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 7531 if (SubExpr->getType()->isBooleanType()) return; 7532 7533 // Emit warning. 7534 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison) 7535 << Loc; 7536 7537 // First note suggest !(x < y) 7538 SourceLocation FirstOpen = SubExpr->getLocStart(); 7539 SourceLocation FirstClose = RHS.get()->getLocEnd(); 7540 FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose); 7541 if (FirstClose.isInvalid()) 7542 FirstOpen = SourceLocation(); 7543 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 7544 << FixItHint::CreateInsertion(FirstOpen, "(") 7545 << FixItHint::CreateInsertion(FirstClose, ")"); 7546 7547 // Second note suggests (!x) < y 7548 SourceLocation SecondOpen = LHS.get()->getLocStart(); 7549 SourceLocation SecondClose = LHS.get()->getLocEnd(); 7550 SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose); 7551 if (SecondClose.isInvalid()) 7552 SecondOpen = SourceLocation(); 7553 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 7554 << FixItHint::CreateInsertion(SecondOpen, "(") 7555 << FixItHint::CreateInsertion(SecondClose, ")"); 7556 } 7557 7558 // Get the decl for a simple expression: a reference to a variable, 7559 // an implicit C++ field reference, or an implicit ObjC ivar reference. 7560 static ValueDecl *getCompareDecl(Expr *E) { 7561 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 7562 return DR->getDecl(); 7563 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 7564 if (Ivar->isFreeIvar()) 7565 return Ivar->getDecl(); 7566 } 7567 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 7568 if (Mem->isImplicitAccess()) 7569 return Mem->getMemberDecl(); 7570 } 7571 return 0; 7572 } 7573 7574 // C99 6.5.8, C++ [expr.rel] 7575 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 7576 SourceLocation Loc, unsigned OpaqueOpc, 7577 bool IsRelational) { 7578 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 7579 7580 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc; 7581 7582 // Handle vector comparisons separately. 7583 if (LHS.get()->getType()->isVectorType() || 7584 RHS.get()->getType()->isVectorType()) 7585 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 7586 7587 QualType LHSType = LHS.get()->getType(); 7588 QualType RHSType = RHS.get()->getType(); 7589 7590 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 7591 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 7592 7593 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 7594 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc); 7595 7596 if (!LHSType->hasFloatingRepresentation() && 7597 !(LHSType->isBlockPointerType() && IsRelational) && 7598 !LHS.get()->getLocStart().isMacroID() && 7599 !RHS.get()->getLocStart().isMacroID()) { 7600 // For non-floating point types, check for self-comparisons of the form 7601 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 7602 // often indicate logic errors in the program. 7603 // 7604 // NOTE: Don't warn about comparison expressions resulting from macro 7605 // expansion. Also don't warn about comparisons which are only self 7606 // comparisons within a template specialization. The warnings should catch 7607 // obvious cases in the definition of the template anyways. The idea is to 7608 // warn when the typed comparison operator will always evaluate to the same 7609 // result. 7610 ValueDecl *DL = getCompareDecl(LHSStripped); 7611 ValueDecl *DR = getCompareDecl(RHSStripped); 7612 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 7613 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 7614 << 0 // self- 7615 << (Opc == BO_EQ 7616 || Opc == BO_LE 7617 || Opc == BO_GE)); 7618 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 7619 !DL->getType()->isReferenceType() && 7620 !DR->getType()->isReferenceType()) { 7621 // what is it always going to eval to? 7622 char always_evals_to; 7623 switch(Opc) { 7624 case BO_EQ: // e.g. array1 == array2 7625 always_evals_to = 0; // false 7626 break; 7627 case BO_NE: // e.g. array1 != array2 7628 always_evals_to = 1; // true 7629 break; 7630 default: 7631 // best we can say is 'a constant' 7632 always_evals_to = 2; // e.g. array1 <= array2 7633 break; 7634 } 7635 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 7636 << 1 // array 7637 << always_evals_to); 7638 } 7639 7640 if (isa<CastExpr>(LHSStripped)) 7641 LHSStripped = LHSStripped->IgnoreParenCasts(); 7642 if (isa<CastExpr>(RHSStripped)) 7643 RHSStripped = RHSStripped->IgnoreParenCasts(); 7644 7645 // Warn about comparisons against a string constant (unless the other 7646 // operand is null), the user probably wants strcmp. 7647 Expr *literalString = 0; 7648 Expr *literalStringStripped = 0; 7649 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 7650 !RHSStripped->isNullPointerConstant(Context, 7651 Expr::NPC_ValueDependentIsNull)) { 7652 literalString = LHS.get(); 7653 literalStringStripped = LHSStripped; 7654 } else if ((isa<StringLiteral>(RHSStripped) || 7655 isa<ObjCEncodeExpr>(RHSStripped)) && 7656 !LHSStripped->isNullPointerConstant(Context, 7657 Expr::NPC_ValueDependentIsNull)) { 7658 literalString = RHS.get(); 7659 literalStringStripped = RHSStripped; 7660 } 7661 7662 if (literalString) { 7663 DiagRuntimeBehavior(Loc, 0, 7664 PDiag(diag::warn_stringcompare) 7665 << isa<ObjCEncodeExpr>(literalStringStripped) 7666 << literalString->getSourceRange()); 7667 } 7668 } 7669 7670 // C99 6.5.8p3 / C99 6.5.9p4 7671 UsualArithmeticConversions(LHS, RHS); 7672 if (LHS.isInvalid() || RHS.isInvalid()) 7673 return QualType(); 7674 7675 LHSType = LHS.get()->getType(); 7676 RHSType = RHS.get()->getType(); 7677 7678 // The result of comparisons is 'bool' in C++, 'int' in C. 7679 QualType ResultTy = Context.getLogicalOperationType(); 7680 7681 if (IsRelational) { 7682 if (LHSType->isRealType() && RHSType->isRealType()) 7683 return ResultTy; 7684 } else { 7685 // Check for comparisons of floating point operands using != and ==. 7686 if (LHSType->hasFloatingRepresentation()) 7687 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 7688 7689 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 7690 return ResultTy; 7691 } 7692 7693 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context, 7694 Expr::NPC_ValueDependentIsNull); 7695 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context, 7696 Expr::NPC_ValueDependentIsNull); 7697 7698 // All of the following pointer-related warnings are GCC extensions, except 7699 // when handling null pointer constants. 7700 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 7701 QualType LCanPointeeTy = 7702 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 7703 QualType RCanPointeeTy = 7704 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 7705 7706 if (getLangOpts().CPlusPlus) { 7707 if (LCanPointeeTy == RCanPointeeTy) 7708 return ResultTy; 7709 if (!IsRelational && 7710 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 7711 // Valid unless comparison between non-null pointer and function pointer 7712 // This is a gcc extension compatibility comparison. 7713 // In a SFINAE context, we treat this as a hard error to maintain 7714 // conformance with the C++ standard. 7715 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 7716 && !LHSIsNull && !RHSIsNull) { 7717 diagnoseFunctionPointerToVoidComparison( 7718 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 7719 7720 if (isSFINAEContext()) 7721 return QualType(); 7722 7723 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7724 return ResultTy; 7725 } 7726 } 7727 7728 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 7729 return QualType(); 7730 else 7731 return ResultTy; 7732 } 7733 // C99 6.5.9p2 and C99 6.5.8p2 7734 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 7735 RCanPointeeTy.getUnqualifiedType())) { 7736 // Valid unless a relational comparison of function pointers 7737 if (IsRelational && LCanPointeeTy->isFunctionType()) { 7738 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 7739 << LHSType << RHSType << LHS.get()->getSourceRange() 7740 << RHS.get()->getSourceRange(); 7741 } 7742 } else if (!IsRelational && 7743 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 7744 // Valid unless comparison between non-null pointer and function pointer 7745 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 7746 && !LHSIsNull && !RHSIsNull) 7747 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 7748 /*isError*/false); 7749 } else { 7750 // Invalid 7751 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 7752 } 7753 if (LCanPointeeTy != RCanPointeeTy) { 7754 if (LHSIsNull && !RHSIsNull) 7755 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 7756 else 7757 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7758 } 7759 return ResultTy; 7760 } 7761 7762 if (getLangOpts().CPlusPlus) { 7763 // Comparison of nullptr_t with itself. 7764 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 7765 return ResultTy; 7766 7767 // Comparison of pointers with null pointer constants and equality 7768 // comparisons of member pointers to null pointer constants. 7769 if (RHSIsNull && 7770 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 7771 (!IsRelational && 7772 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 7773 RHS = ImpCastExprToType(RHS.take(), LHSType, 7774 LHSType->isMemberPointerType() 7775 ? CK_NullToMemberPointer 7776 : CK_NullToPointer); 7777 return ResultTy; 7778 } 7779 if (LHSIsNull && 7780 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 7781 (!IsRelational && 7782 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 7783 LHS = ImpCastExprToType(LHS.take(), RHSType, 7784 RHSType->isMemberPointerType() 7785 ? CK_NullToMemberPointer 7786 : CK_NullToPointer); 7787 return ResultTy; 7788 } 7789 7790 // Comparison of member pointers. 7791 if (!IsRelational && 7792 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 7793 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 7794 return QualType(); 7795 else 7796 return ResultTy; 7797 } 7798 7799 // Handle scoped enumeration types specifically, since they don't promote 7800 // to integers. 7801 if (LHS.get()->getType()->isEnumeralType() && 7802 Context.hasSameUnqualifiedType(LHS.get()->getType(), 7803 RHS.get()->getType())) 7804 return ResultTy; 7805 } 7806 7807 // Handle block pointer types. 7808 if (!IsRelational && LHSType->isBlockPointerType() && 7809 RHSType->isBlockPointerType()) { 7810 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 7811 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 7812 7813 if (!LHSIsNull && !RHSIsNull && 7814 !Context.typesAreCompatible(lpointee, rpointee)) { 7815 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 7816 << LHSType << RHSType << LHS.get()->getSourceRange() 7817 << RHS.get()->getSourceRange(); 7818 } 7819 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7820 return ResultTy; 7821 } 7822 7823 // Allow block pointers to be compared with null pointer constants. 7824 if (!IsRelational 7825 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 7826 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 7827 if (!LHSIsNull && !RHSIsNull) { 7828 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 7829 ->getPointeeType()->isVoidType()) 7830 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 7831 ->getPointeeType()->isVoidType()))) 7832 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 7833 << LHSType << RHSType << LHS.get()->getSourceRange() 7834 << RHS.get()->getSourceRange(); 7835 } 7836 if (LHSIsNull && !RHSIsNull) 7837 LHS = ImpCastExprToType(LHS.take(), RHSType, 7838 RHSType->isPointerType() ? CK_BitCast 7839 : CK_AnyPointerToBlockPointerCast); 7840 else 7841 RHS = ImpCastExprToType(RHS.take(), LHSType, 7842 LHSType->isPointerType() ? CK_BitCast 7843 : CK_AnyPointerToBlockPointerCast); 7844 return ResultTy; 7845 } 7846 7847 if (LHSType->isObjCObjectPointerType() || 7848 RHSType->isObjCObjectPointerType()) { 7849 const PointerType *LPT = LHSType->getAs<PointerType>(); 7850 const PointerType *RPT = RHSType->getAs<PointerType>(); 7851 if (LPT || RPT) { 7852 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 7853 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 7854 7855 if (!LPtrToVoid && !RPtrToVoid && 7856 !Context.typesAreCompatible(LHSType, RHSType)) { 7857 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 7858 /*isError*/false); 7859 } 7860 if (LHSIsNull && !RHSIsNull) { 7861 Expr *E = LHS.take(); 7862 if (getLangOpts().ObjCAutoRefCount) 7863 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion); 7864 LHS = ImpCastExprToType(E, RHSType, 7865 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 7866 } 7867 else { 7868 Expr *E = RHS.take(); 7869 if (getLangOpts().ObjCAutoRefCount) 7870 CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion); 7871 RHS = ImpCastExprToType(E, LHSType, 7872 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 7873 } 7874 return ResultTy; 7875 } 7876 if (LHSType->isObjCObjectPointerType() && 7877 RHSType->isObjCObjectPointerType()) { 7878 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 7879 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 7880 /*isError*/false); 7881 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 7882 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 7883 7884 if (LHSIsNull && !RHSIsNull) 7885 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 7886 else 7887 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7888 return ResultTy; 7889 } 7890 } 7891 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 7892 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 7893 unsigned DiagID = 0; 7894 bool isError = false; 7895 if (LangOpts.DebuggerSupport) { 7896 // Under a debugger, allow the comparison of pointers to integers, 7897 // since users tend to want to compare addresses. 7898 } else if ((LHSIsNull && LHSType->isIntegerType()) || 7899 (RHSIsNull && RHSType->isIntegerType())) { 7900 if (IsRelational && !getLangOpts().CPlusPlus) 7901 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 7902 } else if (IsRelational && !getLangOpts().CPlusPlus) 7903 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 7904 else if (getLangOpts().CPlusPlus) { 7905 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 7906 isError = true; 7907 } else 7908 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 7909 7910 if (DiagID) { 7911 Diag(Loc, DiagID) 7912 << LHSType << RHSType << LHS.get()->getSourceRange() 7913 << RHS.get()->getSourceRange(); 7914 if (isError) 7915 return QualType(); 7916 } 7917 7918 if (LHSType->isIntegerType()) 7919 LHS = ImpCastExprToType(LHS.take(), RHSType, 7920 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 7921 else 7922 RHS = ImpCastExprToType(RHS.take(), LHSType, 7923 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 7924 return ResultTy; 7925 } 7926 7927 // Handle block pointers. 7928 if (!IsRelational && RHSIsNull 7929 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 7930 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer); 7931 return ResultTy; 7932 } 7933 if (!IsRelational && LHSIsNull 7934 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 7935 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer); 7936 return ResultTy; 7937 } 7938 7939 return InvalidOperands(Loc, LHS, RHS); 7940 } 7941 7942 7943 // Return a signed type that is of identical size and number of elements. 7944 // For floating point vectors, return an integer type of identical size 7945 // and number of elements. 7946 QualType Sema::GetSignedVectorType(QualType V) { 7947 const VectorType *VTy = V->getAs<VectorType>(); 7948 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 7949 if (TypeSize == Context.getTypeSize(Context.CharTy)) 7950 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 7951 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 7952 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 7953 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 7954 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 7955 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 7956 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 7957 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 7958 "Unhandled vector element size in vector compare"); 7959 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 7960 } 7961 7962 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 7963 /// operates on extended vector types. Instead of producing an IntTy result, 7964 /// like a scalar comparison, a vector comparison produces a vector of integer 7965 /// types. 7966 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 7967 SourceLocation Loc, 7968 bool IsRelational) { 7969 // Check to make sure we're operating on vectors of the same type and width, 7970 // Allowing one side to be a scalar of element type. 7971 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false); 7972 if (vType.isNull()) 7973 return vType; 7974 7975 QualType LHSType = LHS.get()->getType(); 7976 7977 // If AltiVec, the comparison results in a numeric type, i.e. 7978 // bool for C++, int for C 7979 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 7980 return Context.getLogicalOperationType(); 7981 7982 // For non-floating point types, check for self-comparisons of the form 7983 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 7984 // often indicate logic errors in the program. 7985 if (!LHSType->hasFloatingRepresentation()) { 7986 if (DeclRefExpr* DRL 7987 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 7988 if (DeclRefExpr* DRR 7989 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 7990 if (DRL->getDecl() == DRR->getDecl()) 7991 DiagRuntimeBehavior(Loc, 0, 7992 PDiag(diag::warn_comparison_always) 7993 << 0 // self- 7994 << 2 // "a constant" 7995 ); 7996 } 7997 7998 // Check for comparisons of floating point operands using != and ==. 7999 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 8000 assert (RHS.get()->getType()->hasFloatingRepresentation()); 8001 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 8002 } 8003 8004 // Return a signed type for the vector. 8005 return GetSignedVectorType(LHSType); 8006 } 8007 8008 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 8009 SourceLocation Loc) { 8010 // Ensure that either both operands are of the same vector type, or 8011 // one operand is of a vector type and the other is of its element type. 8012 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false); 8013 if (vType.isNull()) 8014 return InvalidOperands(Loc, LHS, RHS); 8015 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 8016 vType->hasFloatingRepresentation()) 8017 return InvalidOperands(Loc, LHS, RHS); 8018 8019 return GetSignedVectorType(LHS.get()->getType()); 8020 } 8021 8022 inline QualType Sema::CheckBitwiseOperands( 8023 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8024 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8025 8026 if (LHS.get()->getType()->isVectorType() || 8027 RHS.get()->getType()->isVectorType()) { 8028 if (LHS.get()->getType()->hasIntegerRepresentation() && 8029 RHS.get()->getType()->hasIntegerRepresentation()) 8030 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 8031 8032 return InvalidOperands(Loc, LHS, RHS); 8033 } 8034 8035 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS); 8036 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 8037 IsCompAssign); 8038 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 8039 return QualType(); 8040 LHS = LHSResult.take(); 8041 RHS = RHSResult.take(); 8042 8043 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 8044 return compType; 8045 return InvalidOperands(Loc, LHS, RHS); 8046 } 8047 8048 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 8049 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) { 8050 8051 // Check vector operands differently. 8052 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 8053 return CheckVectorLogicalOperands(LHS, RHS, Loc); 8054 8055 // Diagnose cases where the user write a logical and/or but probably meant a 8056 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 8057 // is a constant. 8058 if (LHS.get()->getType()->isIntegerType() && 8059 !LHS.get()->getType()->isBooleanType() && 8060 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 8061 // Don't warn in macros or template instantiations. 8062 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 8063 // If the RHS can be constant folded, and if it constant folds to something 8064 // that isn't 0 or 1 (which indicate a potential logical operation that 8065 // happened to fold to true/false) then warn. 8066 // Parens on the RHS are ignored. 8067 llvm::APSInt Result; 8068 if (RHS.get()->EvaluateAsInt(Result, Context)) 8069 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) || 8070 (Result != 0 && Result != 1)) { 8071 Diag(Loc, diag::warn_logical_instead_of_bitwise) 8072 << RHS.get()->getSourceRange() 8073 << (Opc == BO_LAnd ? "&&" : "||"); 8074 // Suggest replacing the logical operator with the bitwise version 8075 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 8076 << (Opc == BO_LAnd ? "&" : "|") 8077 << FixItHint::CreateReplacement(SourceRange( 8078 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(), 8079 getLangOpts())), 8080 Opc == BO_LAnd ? "&" : "|"); 8081 if (Opc == BO_LAnd) 8082 // Suggest replacing "Foo() && kNonZero" with "Foo()" 8083 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 8084 << FixItHint::CreateRemoval( 8085 SourceRange( 8086 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(), 8087 0, getSourceManager(), 8088 getLangOpts()), 8089 RHS.get()->getLocEnd())); 8090 } 8091 } 8092 8093 if (!Context.getLangOpts().CPlusPlus) { 8094 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 8095 // not operate on the built-in scalar and vector float types. 8096 if (Context.getLangOpts().OpenCL && 8097 Context.getLangOpts().OpenCLVersion < 120) { 8098 if (LHS.get()->getType()->isFloatingType() || 8099 RHS.get()->getType()->isFloatingType()) 8100 return InvalidOperands(Loc, LHS, RHS); 8101 } 8102 8103 LHS = UsualUnaryConversions(LHS.take()); 8104 if (LHS.isInvalid()) 8105 return QualType(); 8106 8107 RHS = UsualUnaryConversions(RHS.take()); 8108 if (RHS.isInvalid()) 8109 return QualType(); 8110 8111 if (!LHS.get()->getType()->isScalarType() || 8112 !RHS.get()->getType()->isScalarType()) 8113 return InvalidOperands(Loc, LHS, RHS); 8114 8115 return Context.IntTy; 8116 } 8117 8118 // The following is safe because we only use this method for 8119 // non-overloadable operands. 8120 8121 // C++ [expr.log.and]p1 8122 // C++ [expr.log.or]p1 8123 // The operands are both contextually converted to type bool. 8124 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 8125 if (LHSRes.isInvalid()) 8126 return InvalidOperands(Loc, LHS, RHS); 8127 LHS = LHSRes; 8128 8129 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 8130 if (RHSRes.isInvalid()) 8131 return InvalidOperands(Loc, LHS, RHS); 8132 RHS = RHSRes; 8133 8134 // C++ [expr.log.and]p2 8135 // C++ [expr.log.or]p2 8136 // The result is a bool. 8137 return Context.BoolTy; 8138 } 8139 8140 static bool IsReadonlyMessage(Expr *E, Sema &S) { 8141 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 8142 if (!ME) return false; 8143 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 8144 ObjCMessageExpr *Base = 8145 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 8146 if (!Base) return false; 8147 return Base->getMethodDecl() != 0; 8148 } 8149 8150 /// Is the given expression (which must be 'const') a reference to a 8151 /// variable which was originally non-const, but which has become 8152 /// 'const' due to being captured within a block? 8153 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 8154 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 8155 assert(E->isLValue() && E->getType().isConstQualified()); 8156 E = E->IgnoreParens(); 8157 8158 // Must be a reference to a declaration from an enclosing scope. 8159 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 8160 if (!DRE) return NCCK_None; 8161 if (!DRE->refersToEnclosingLocal()) return NCCK_None; 8162 8163 // The declaration must be a variable which is not declared 'const'. 8164 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 8165 if (!var) return NCCK_None; 8166 if (var->getType().isConstQualified()) return NCCK_None; 8167 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 8168 8169 // Decide whether the first capture was for a block or a lambda. 8170 DeclContext *DC = S.CurContext, *Prev = 0; 8171 while (DC != var->getDeclContext()) { 8172 Prev = DC; 8173 DC = DC->getParent(); 8174 } 8175 // Unless we have an init-capture, we've gone one step too far. 8176 if (!var->isInitCapture()) 8177 DC = Prev; 8178 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 8179 } 8180 8181 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 8182 /// emit an error and return true. If so, return false. 8183 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 8184 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 8185 SourceLocation OrigLoc = Loc; 8186 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 8187 &Loc); 8188 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 8189 IsLV = Expr::MLV_InvalidMessageExpression; 8190 if (IsLV == Expr::MLV_Valid) 8191 return false; 8192 8193 unsigned Diag = 0; 8194 bool NeedType = false; 8195 switch (IsLV) { // C99 6.5.16p2 8196 case Expr::MLV_ConstQualified: 8197 Diag = diag::err_typecheck_assign_const; 8198 8199 // Use a specialized diagnostic when we're assigning to an object 8200 // from an enclosing function or block. 8201 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 8202 if (NCCK == NCCK_Block) 8203 Diag = diag::err_block_decl_ref_not_modifiable_lvalue; 8204 else 8205 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue; 8206 break; 8207 } 8208 8209 // In ARC, use some specialized diagnostics for occasions where we 8210 // infer 'const'. These are always pseudo-strong variables. 8211 if (S.getLangOpts().ObjCAutoRefCount) { 8212 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 8213 if (declRef && isa<VarDecl>(declRef->getDecl())) { 8214 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 8215 8216 // Use the normal diagnostic if it's pseudo-__strong but the 8217 // user actually wrote 'const'. 8218 if (var->isARCPseudoStrong() && 8219 (!var->getTypeSourceInfo() || 8220 !var->getTypeSourceInfo()->getType().isConstQualified())) { 8221 // There are two pseudo-strong cases: 8222 // - self 8223 ObjCMethodDecl *method = S.getCurMethodDecl(); 8224 if (method && var == method->getSelfDecl()) 8225 Diag = method->isClassMethod() 8226 ? diag::err_typecheck_arc_assign_self_class_method 8227 : diag::err_typecheck_arc_assign_self; 8228 8229 // - fast enumeration variables 8230 else 8231 Diag = diag::err_typecheck_arr_assign_enumeration; 8232 8233 SourceRange Assign; 8234 if (Loc != OrigLoc) 8235 Assign = SourceRange(OrigLoc, OrigLoc); 8236 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 8237 // We need to preserve the AST regardless, so migration tool 8238 // can do its job. 8239 return false; 8240 } 8241 } 8242 } 8243 8244 break; 8245 case Expr::MLV_ArrayType: 8246 case Expr::MLV_ArrayTemporary: 8247 Diag = diag::err_typecheck_array_not_modifiable_lvalue; 8248 NeedType = true; 8249 break; 8250 case Expr::MLV_NotObjectType: 8251 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue; 8252 NeedType = true; 8253 break; 8254 case Expr::MLV_LValueCast: 8255 Diag = diag::err_typecheck_lvalue_casts_not_supported; 8256 break; 8257 case Expr::MLV_Valid: 8258 llvm_unreachable("did not take early return for MLV_Valid"); 8259 case Expr::MLV_InvalidExpression: 8260 case Expr::MLV_MemberFunction: 8261 case Expr::MLV_ClassTemporary: 8262 Diag = diag::err_typecheck_expression_not_modifiable_lvalue; 8263 break; 8264 case Expr::MLV_IncompleteType: 8265 case Expr::MLV_IncompleteVoidType: 8266 return S.RequireCompleteType(Loc, E->getType(), 8267 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 8268 case Expr::MLV_DuplicateVectorComponents: 8269 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 8270 break; 8271 case Expr::MLV_NoSetterProperty: 8272 llvm_unreachable("readonly properties should be processed differently"); 8273 case Expr::MLV_InvalidMessageExpression: 8274 Diag = diag::error_readonly_message_assignment; 8275 break; 8276 case Expr::MLV_SubObjCPropertySetting: 8277 Diag = diag::error_no_subobject_property_setting; 8278 break; 8279 } 8280 8281 SourceRange Assign; 8282 if (Loc != OrigLoc) 8283 Assign = SourceRange(OrigLoc, OrigLoc); 8284 if (NeedType) 8285 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign; 8286 else 8287 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 8288 return true; 8289 } 8290 8291 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 8292 SourceLocation Loc, 8293 Sema &Sema) { 8294 // C / C++ fields 8295 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 8296 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 8297 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 8298 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 8299 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 8300 } 8301 8302 // Objective-C instance variables 8303 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 8304 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 8305 if (OL && OR && OL->getDecl() == OR->getDecl()) { 8306 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 8307 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 8308 if (RL && RR && RL->getDecl() == RR->getDecl()) 8309 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 8310 } 8311 } 8312 8313 // C99 6.5.16.1 8314 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 8315 SourceLocation Loc, 8316 QualType CompoundType) { 8317 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 8318 8319 // Verify that LHS is a modifiable lvalue, and emit error if not. 8320 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 8321 return QualType(); 8322 8323 QualType LHSType = LHSExpr->getType(); 8324 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 8325 CompoundType; 8326 AssignConvertType ConvTy; 8327 if (CompoundType.isNull()) { 8328 Expr *RHSCheck = RHS.get(); 8329 8330 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 8331 8332 QualType LHSTy(LHSType); 8333 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 8334 if (RHS.isInvalid()) 8335 return QualType(); 8336 // Special case of NSObject attributes on c-style pointer types. 8337 if (ConvTy == IncompatiblePointer && 8338 ((Context.isObjCNSObjectType(LHSType) && 8339 RHSType->isObjCObjectPointerType()) || 8340 (Context.isObjCNSObjectType(RHSType) && 8341 LHSType->isObjCObjectPointerType()))) 8342 ConvTy = Compatible; 8343 8344 if (ConvTy == Compatible && 8345 LHSType->isObjCObjectType()) 8346 Diag(Loc, diag::err_objc_object_assignment) 8347 << LHSType; 8348 8349 // If the RHS is a unary plus or minus, check to see if they = and + are 8350 // right next to each other. If so, the user may have typo'd "x =+ 4" 8351 // instead of "x += 4". 8352 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 8353 RHSCheck = ICE->getSubExpr(); 8354 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 8355 if ((UO->getOpcode() == UO_Plus || 8356 UO->getOpcode() == UO_Minus) && 8357 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 8358 // Only if the two operators are exactly adjacent. 8359 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 8360 // And there is a space or other character before the subexpr of the 8361 // unary +/-. We don't want to warn on "x=-1". 8362 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 8363 UO->getSubExpr()->getLocStart().isFileID()) { 8364 Diag(Loc, diag::warn_not_compound_assign) 8365 << (UO->getOpcode() == UO_Plus ? "+" : "-") 8366 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 8367 } 8368 } 8369 8370 if (ConvTy == Compatible) { 8371 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 8372 // Warn about retain cycles where a block captures the LHS, but 8373 // not if the LHS is a simple variable into which the block is 8374 // being stored...unless that variable can be captured by reference! 8375 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 8376 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 8377 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 8378 checkRetainCycles(LHSExpr, RHS.get()); 8379 8380 // It is safe to assign a weak reference into a strong variable. 8381 // Although this code can still have problems: 8382 // id x = self.weakProp; 8383 // id y = self.weakProp; 8384 // we do not warn to warn spuriously when 'x' and 'y' are on separate 8385 // paths through the function. This should be revisited if 8386 // -Wrepeated-use-of-weak is made flow-sensitive. 8387 DiagnosticsEngine::Level Level = 8388 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 8389 RHS.get()->getLocStart()); 8390 if (Level != DiagnosticsEngine::Ignored) 8391 getCurFunction()->markSafeWeakUse(RHS.get()); 8392 8393 } else if (getLangOpts().ObjCAutoRefCount) { 8394 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 8395 } 8396 } 8397 } else { 8398 // Compound assignment "x += y" 8399 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 8400 } 8401 8402 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 8403 RHS.get(), AA_Assigning)) 8404 return QualType(); 8405 8406 CheckForNullPointerDereference(*this, LHSExpr); 8407 8408 // C99 6.5.16p3: The type of an assignment expression is the type of the 8409 // left operand unless the left operand has qualified type, in which case 8410 // it is the unqualified version of the type of the left operand. 8411 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 8412 // is converted to the type of the assignment expression (above). 8413 // C++ 5.17p1: the type of the assignment expression is that of its left 8414 // operand. 8415 return (getLangOpts().CPlusPlus 8416 ? LHSType : LHSType.getUnqualifiedType()); 8417 } 8418 8419 // C99 6.5.17 8420 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 8421 SourceLocation Loc) { 8422 LHS = S.CheckPlaceholderExpr(LHS.take()); 8423 RHS = S.CheckPlaceholderExpr(RHS.take()); 8424 if (LHS.isInvalid() || RHS.isInvalid()) 8425 return QualType(); 8426 8427 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 8428 // operands, but not unary promotions. 8429 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 8430 8431 // So we treat the LHS as a ignored value, and in C++ we allow the 8432 // containing site to determine what should be done with the RHS. 8433 LHS = S.IgnoredValueConversions(LHS.take()); 8434 if (LHS.isInvalid()) 8435 return QualType(); 8436 8437 S.DiagnoseUnusedExprResult(LHS.get()); 8438 8439 if (!S.getLangOpts().CPlusPlus) { 8440 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take()); 8441 if (RHS.isInvalid()) 8442 return QualType(); 8443 if (!RHS.get()->getType()->isVoidType()) 8444 S.RequireCompleteType(Loc, RHS.get()->getType(), 8445 diag::err_incomplete_type); 8446 } 8447 8448 return RHS.get()->getType(); 8449 } 8450 8451 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 8452 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 8453 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 8454 ExprValueKind &VK, 8455 SourceLocation OpLoc, 8456 bool IsInc, bool IsPrefix) { 8457 if (Op->isTypeDependent()) 8458 return S.Context.DependentTy; 8459 8460 QualType ResType = Op->getType(); 8461 // Atomic types can be used for increment / decrement where the non-atomic 8462 // versions can, so ignore the _Atomic() specifier for the purpose of 8463 // checking. 8464 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8465 ResType = ResAtomicType->getValueType(); 8466 8467 assert(!ResType.isNull() && "no type for increment/decrement expression"); 8468 8469 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 8470 // Decrement of bool is not allowed. 8471 if (!IsInc) { 8472 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 8473 return QualType(); 8474 } 8475 // Increment of bool sets it to true, but is deprecated. 8476 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); 8477 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 8478 // Error on enum increments and decrements in C++ mode 8479 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 8480 return QualType(); 8481 } else if (ResType->isRealType()) { 8482 // OK! 8483 } else if (ResType->isPointerType()) { 8484 // C99 6.5.2.4p2, 6.5.6p2 8485 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 8486 return QualType(); 8487 } else if (ResType->isObjCObjectPointerType()) { 8488 // On modern runtimes, ObjC pointer arithmetic is forbidden. 8489 // Otherwise, we just need a complete type. 8490 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 8491 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 8492 return QualType(); 8493 } else if (ResType->isAnyComplexType()) { 8494 // C99 does not support ++/-- on complex types, we allow as an extension. 8495 S.Diag(OpLoc, diag::ext_integer_increment_complex) 8496 << ResType << Op->getSourceRange(); 8497 } else if (ResType->isPlaceholderType()) { 8498 ExprResult PR = S.CheckPlaceholderExpr(Op); 8499 if (PR.isInvalid()) return QualType(); 8500 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc, 8501 IsInc, IsPrefix); 8502 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 8503 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 8504 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 8505 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 8506 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 8507 } else { 8508 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 8509 << ResType << int(IsInc) << Op->getSourceRange(); 8510 return QualType(); 8511 } 8512 // At this point, we know we have a real, complex or pointer type. 8513 // Now make sure the operand is a modifiable lvalue. 8514 if (CheckForModifiableLvalue(Op, OpLoc, S)) 8515 return QualType(); 8516 // In C++, a prefix increment is the same type as the operand. Otherwise 8517 // (in C or with postfix), the increment is the unqualified type of the 8518 // operand. 8519 if (IsPrefix && S.getLangOpts().CPlusPlus) { 8520 VK = VK_LValue; 8521 return ResType; 8522 } else { 8523 VK = VK_RValue; 8524 return ResType.getUnqualifiedType(); 8525 } 8526 } 8527 8528 8529 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 8530 /// This routine allows us to typecheck complex/recursive expressions 8531 /// where the declaration is needed for type checking. We only need to 8532 /// handle cases when the expression references a function designator 8533 /// or is an lvalue. Here are some examples: 8534 /// - &(x) => x 8535 /// - &*****f => f for f a function designator. 8536 /// - &s.xx => s 8537 /// - &s.zz[1].yy -> s, if zz is an array 8538 /// - *(x + 1) -> x, if x is an array 8539 /// - &"123"[2] -> 0 8540 /// - & __real__ x -> x 8541 static ValueDecl *getPrimaryDecl(Expr *E) { 8542 switch (E->getStmtClass()) { 8543 case Stmt::DeclRefExprClass: 8544 return cast<DeclRefExpr>(E)->getDecl(); 8545 case Stmt::MemberExprClass: 8546 // If this is an arrow operator, the address is an offset from 8547 // the base's value, so the object the base refers to is 8548 // irrelevant. 8549 if (cast<MemberExpr>(E)->isArrow()) 8550 return 0; 8551 // Otherwise, the expression refers to a part of the base 8552 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 8553 case Stmt::ArraySubscriptExprClass: { 8554 // FIXME: This code shouldn't be necessary! We should catch the implicit 8555 // promotion of register arrays earlier. 8556 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 8557 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 8558 if (ICE->getSubExpr()->getType()->isArrayType()) 8559 return getPrimaryDecl(ICE->getSubExpr()); 8560 } 8561 return 0; 8562 } 8563 case Stmt::UnaryOperatorClass: { 8564 UnaryOperator *UO = cast<UnaryOperator>(E); 8565 8566 switch(UO->getOpcode()) { 8567 case UO_Real: 8568 case UO_Imag: 8569 case UO_Extension: 8570 return getPrimaryDecl(UO->getSubExpr()); 8571 default: 8572 return 0; 8573 } 8574 } 8575 case Stmt::ParenExprClass: 8576 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 8577 case Stmt::ImplicitCastExprClass: 8578 // If the result of an implicit cast is an l-value, we care about 8579 // the sub-expression; otherwise, the result here doesn't matter. 8580 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 8581 default: 8582 return 0; 8583 } 8584 } 8585 8586 namespace { 8587 enum { 8588 AO_Bit_Field = 0, 8589 AO_Vector_Element = 1, 8590 AO_Property_Expansion = 2, 8591 AO_Register_Variable = 3, 8592 AO_No_Error = 4 8593 }; 8594 } 8595 /// \brief Diagnose invalid operand for address of operations. 8596 /// 8597 /// \param Type The type of operand which cannot have its address taken. 8598 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 8599 Expr *E, unsigned Type) { 8600 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 8601 } 8602 8603 /// CheckAddressOfOperand - The operand of & must be either a function 8604 /// designator or an lvalue designating an object. If it is an lvalue, the 8605 /// object cannot be declared with storage class register or be a bit field. 8606 /// Note: The usual conversions are *not* applied to the operand of the & 8607 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 8608 /// In C++, the operand might be an overloaded function name, in which case 8609 /// we allow the '&' but retain the overloaded-function type. 8610 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 8611 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 8612 if (PTy->getKind() == BuiltinType::Overload) { 8613 Expr *E = OrigOp.get()->IgnoreParens(); 8614 if (!isa<OverloadExpr>(E)) { 8615 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 8616 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 8617 << OrigOp.get()->getSourceRange(); 8618 return QualType(); 8619 } 8620 8621 OverloadExpr *Ovl = cast<OverloadExpr>(E); 8622 if (isa<UnresolvedMemberExpr>(Ovl)) 8623 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 8624 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8625 << OrigOp.get()->getSourceRange(); 8626 return QualType(); 8627 } 8628 8629 return Context.OverloadTy; 8630 } 8631 8632 if (PTy->getKind() == BuiltinType::UnknownAny) 8633 return Context.UnknownAnyTy; 8634 8635 if (PTy->getKind() == BuiltinType::BoundMember) { 8636 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8637 << OrigOp.get()->getSourceRange(); 8638 return QualType(); 8639 } 8640 8641 OrigOp = CheckPlaceholderExpr(OrigOp.take()); 8642 if (OrigOp.isInvalid()) return QualType(); 8643 } 8644 8645 if (OrigOp.get()->isTypeDependent()) 8646 return Context.DependentTy; 8647 8648 assert(!OrigOp.get()->getType()->isPlaceholderType()); 8649 8650 // Make sure to ignore parentheses in subsequent checks 8651 Expr *op = OrigOp.get()->IgnoreParens(); 8652 8653 if (getLangOpts().C99) { 8654 // Implement C99-only parts of addressof rules. 8655 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 8656 if (uOp->getOpcode() == UO_Deref) 8657 // Per C99 6.5.3.2, the address of a deref always returns a valid result 8658 // (assuming the deref expression is valid). 8659 return uOp->getSubExpr()->getType(); 8660 } 8661 // Technically, there should be a check for array subscript 8662 // expressions here, but the result of one is always an lvalue anyway. 8663 } 8664 ValueDecl *dcl = getPrimaryDecl(op); 8665 Expr::LValueClassification lval = op->ClassifyLValue(Context); 8666 unsigned AddressOfError = AO_No_Error; 8667 8668 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 8669 bool sfinae = (bool)isSFINAEContext(); 8670 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 8671 : diag::ext_typecheck_addrof_temporary) 8672 << op->getType() << op->getSourceRange(); 8673 if (sfinae) 8674 return QualType(); 8675 // Materialize the temporary as an lvalue so that we can take its address. 8676 OrigOp = op = new (Context) 8677 MaterializeTemporaryExpr(op->getType(), OrigOp.take(), true, 0); 8678 } else if (isa<ObjCSelectorExpr>(op)) { 8679 return Context.getPointerType(op->getType()); 8680 } else if (lval == Expr::LV_MemberFunction) { 8681 // If it's an instance method, make a member pointer. 8682 // The expression must have exactly the form &A::foo. 8683 8684 // If the underlying expression isn't a decl ref, give up. 8685 if (!isa<DeclRefExpr>(op)) { 8686 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8687 << OrigOp.get()->getSourceRange(); 8688 return QualType(); 8689 } 8690 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 8691 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 8692 8693 // The id-expression was parenthesized. 8694 if (OrigOp.get() != DRE) { 8695 Diag(OpLoc, diag::err_parens_pointer_member_function) 8696 << OrigOp.get()->getSourceRange(); 8697 8698 // The method was named without a qualifier. 8699 } else if (!DRE->getQualifier()) { 8700 if (MD->getParent()->getName().empty()) 8701 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 8702 << op->getSourceRange(); 8703 else { 8704 SmallString<32> Str; 8705 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 8706 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 8707 << op->getSourceRange() 8708 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 8709 } 8710 } 8711 8712 return Context.getMemberPointerType(op->getType(), 8713 Context.getTypeDeclType(MD->getParent()).getTypePtr()); 8714 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 8715 // C99 6.5.3.2p1 8716 // The operand must be either an l-value or a function designator 8717 if (!op->getType()->isFunctionType()) { 8718 // Use a special diagnostic for loads from property references. 8719 if (isa<PseudoObjectExpr>(op)) { 8720 AddressOfError = AO_Property_Expansion; 8721 } else { 8722 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 8723 << op->getType() << op->getSourceRange(); 8724 return QualType(); 8725 } 8726 } 8727 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 8728 // The operand cannot be a bit-field 8729 AddressOfError = AO_Bit_Field; 8730 } else if (op->getObjectKind() == OK_VectorComponent) { 8731 // The operand cannot be an element of a vector 8732 AddressOfError = AO_Vector_Element; 8733 } else if (dcl) { // C99 6.5.3.2p1 8734 // We have an lvalue with a decl. Make sure the decl is not declared 8735 // with the register storage-class specifier. 8736 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 8737 // in C++ it is not error to take address of a register 8738 // variable (c++03 7.1.1P3) 8739 if (vd->getStorageClass() == SC_Register && 8740 !getLangOpts().CPlusPlus) { 8741 AddressOfError = AO_Register_Variable; 8742 } 8743 } else if (isa<FunctionTemplateDecl>(dcl)) { 8744 return Context.OverloadTy; 8745 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 8746 // Okay: we can take the address of a field. 8747 // Could be a pointer to member, though, if there is an explicit 8748 // scope qualifier for the class. 8749 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 8750 DeclContext *Ctx = dcl->getDeclContext(); 8751 if (Ctx && Ctx->isRecord()) { 8752 if (dcl->getType()->isReferenceType()) { 8753 Diag(OpLoc, 8754 diag::err_cannot_form_pointer_to_member_of_reference_type) 8755 << dcl->getDeclName() << dcl->getType(); 8756 return QualType(); 8757 } 8758 8759 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 8760 Ctx = Ctx->getParent(); 8761 return Context.getMemberPointerType(op->getType(), 8762 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 8763 } 8764 } 8765 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl)) 8766 llvm_unreachable("Unknown/unexpected decl type"); 8767 } 8768 8769 if (AddressOfError != AO_No_Error) { 8770 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 8771 return QualType(); 8772 } 8773 8774 if (lval == Expr::LV_IncompleteVoidType) { 8775 // Taking the address of a void variable is technically illegal, but we 8776 // allow it in cases which are otherwise valid. 8777 // Example: "extern void x; void* y = &x;". 8778 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 8779 } 8780 8781 // If the operand has type "type", the result has type "pointer to type". 8782 if (op->getType()->isObjCObjectType()) 8783 return Context.getObjCObjectPointerType(op->getType()); 8784 return Context.getPointerType(op->getType()); 8785 } 8786 8787 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 8788 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 8789 SourceLocation OpLoc) { 8790 if (Op->isTypeDependent()) 8791 return S.Context.DependentTy; 8792 8793 ExprResult ConvResult = S.UsualUnaryConversions(Op); 8794 if (ConvResult.isInvalid()) 8795 return QualType(); 8796 Op = ConvResult.take(); 8797 QualType OpTy = Op->getType(); 8798 QualType Result; 8799 8800 if (isa<CXXReinterpretCastExpr>(Op)) { 8801 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 8802 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 8803 Op->getSourceRange()); 8804 } 8805 8806 // Note that per both C89 and C99, indirection is always legal, even if OpTy 8807 // is an incomplete type or void. It would be possible to warn about 8808 // dereferencing a void pointer, but it's completely well-defined, and such a 8809 // warning is unlikely to catch any mistakes. 8810 if (const PointerType *PT = OpTy->getAs<PointerType>()) 8811 Result = PT->getPointeeType(); 8812 else if (const ObjCObjectPointerType *OPT = 8813 OpTy->getAs<ObjCObjectPointerType>()) 8814 Result = OPT->getPointeeType(); 8815 else { 8816 ExprResult PR = S.CheckPlaceholderExpr(Op); 8817 if (PR.isInvalid()) return QualType(); 8818 if (PR.take() != Op) 8819 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc); 8820 } 8821 8822 if (Result.isNull()) { 8823 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 8824 << OpTy << Op->getSourceRange(); 8825 return QualType(); 8826 } 8827 8828 // Dereferences are usually l-values... 8829 VK = VK_LValue; 8830 8831 // ...except that certain expressions are never l-values in C. 8832 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 8833 VK = VK_RValue; 8834 8835 return Result; 8836 } 8837 8838 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode( 8839 tok::TokenKind Kind) { 8840 BinaryOperatorKind Opc; 8841 switch (Kind) { 8842 default: llvm_unreachable("Unknown binop!"); 8843 case tok::periodstar: Opc = BO_PtrMemD; break; 8844 case tok::arrowstar: Opc = BO_PtrMemI; break; 8845 case tok::star: Opc = BO_Mul; break; 8846 case tok::slash: Opc = BO_Div; break; 8847 case tok::percent: Opc = BO_Rem; break; 8848 case tok::plus: Opc = BO_Add; break; 8849 case tok::minus: Opc = BO_Sub; break; 8850 case tok::lessless: Opc = BO_Shl; break; 8851 case tok::greatergreater: Opc = BO_Shr; break; 8852 case tok::lessequal: Opc = BO_LE; break; 8853 case tok::less: Opc = BO_LT; break; 8854 case tok::greaterequal: Opc = BO_GE; break; 8855 case tok::greater: Opc = BO_GT; break; 8856 case tok::exclaimequal: Opc = BO_NE; break; 8857 case tok::equalequal: Opc = BO_EQ; break; 8858 case tok::amp: Opc = BO_And; break; 8859 case tok::caret: Opc = BO_Xor; break; 8860 case tok::pipe: Opc = BO_Or; break; 8861 case tok::ampamp: Opc = BO_LAnd; break; 8862 case tok::pipepipe: Opc = BO_LOr; break; 8863 case tok::equal: Opc = BO_Assign; break; 8864 case tok::starequal: Opc = BO_MulAssign; break; 8865 case tok::slashequal: Opc = BO_DivAssign; break; 8866 case tok::percentequal: Opc = BO_RemAssign; break; 8867 case tok::plusequal: Opc = BO_AddAssign; break; 8868 case tok::minusequal: Opc = BO_SubAssign; break; 8869 case tok::lesslessequal: Opc = BO_ShlAssign; break; 8870 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 8871 case tok::ampequal: Opc = BO_AndAssign; break; 8872 case tok::caretequal: Opc = BO_XorAssign; break; 8873 case tok::pipeequal: Opc = BO_OrAssign; break; 8874 case tok::comma: Opc = BO_Comma; break; 8875 } 8876 return Opc; 8877 } 8878 8879 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 8880 tok::TokenKind Kind) { 8881 UnaryOperatorKind Opc; 8882 switch (Kind) { 8883 default: llvm_unreachable("Unknown unary op!"); 8884 case tok::plusplus: Opc = UO_PreInc; break; 8885 case tok::minusminus: Opc = UO_PreDec; break; 8886 case tok::amp: Opc = UO_AddrOf; break; 8887 case tok::star: Opc = UO_Deref; break; 8888 case tok::plus: Opc = UO_Plus; break; 8889 case tok::minus: Opc = UO_Minus; break; 8890 case tok::tilde: Opc = UO_Not; break; 8891 case tok::exclaim: Opc = UO_LNot; break; 8892 case tok::kw___real: Opc = UO_Real; break; 8893 case tok::kw___imag: Opc = UO_Imag; break; 8894 case tok::kw___extension__: Opc = UO_Extension; break; 8895 } 8896 return Opc; 8897 } 8898 8899 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 8900 /// This warning is only emitted for builtin assignment operations. It is also 8901 /// suppressed in the event of macro expansions. 8902 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 8903 SourceLocation OpLoc) { 8904 if (!S.ActiveTemplateInstantiations.empty()) 8905 return; 8906 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 8907 return; 8908 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 8909 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 8910 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 8911 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 8912 if (!LHSDeclRef || !RHSDeclRef || 8913 LHSDeclRef->getLocation().isMacroID() || 8914 RHSDeclRef->getLocation().isMacroID()) 8915 return; 8916 const ValueDecl *LHSDecl = 8917 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 8918 const ValueDecl *RHSDecl = 8919 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 8920 if (LHSDecl != RHSDecl) 8921 return; 8922 if (LHSDecl->getType().isVolatileQualified()) 8923 return; 8924 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 8925 if (RefTy->getPointeeType().isVolatileQualified()) 8926 return; 8927 8928 S.Diag(OpLoc, diag::warn_self_assignment) 8929 << LHSDeclRef->getType() 8930 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8931 } 8932 8933 /// Check if a bitwise-& is performed on an Objective-C pointer. This 8934 /// is usually indicative of introspection within the Objective-C pointer. 8935 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 8936 SourceLocation OpLoc) { 8937 if (!S.getLangOpts().ObjC1) 8938 return; 8939 8940 const Expr *ObjCPointerExpr = 0, *OtherExpr = 0; 8941 const Expr *LHS = L.get(); 8942 const Expr *RHS = R.get(); 8943 8944 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 8945 ObjCPointerExpr = LHS; 8946 OtherExpr = RHS; 8947 } 8948 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 8949 ObjCPointerExpr = RHS; 8950 OtherExpr = LHS; 8951 } 8952 8953 // This warning is deliberately made very specific to reduce false 8954 // positives with logic that uses '&' for hashing. This logic mainly 8955 // looks for code trying to introspect into tagged pointers, which 8956 // code should generally never do. 8957 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 8958 unsigned Diag = diag::warn_objc_pointer_masking; 8959 // Determine if we are introspecting the result of performSelectorXXX. 8960 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 8961 // Special case messages to -performSelector and friends, which 8962 // can return non-pointer values boxed in a pointer value. 8963 // Some clients may wish to silence warnings in this subcase. 8964 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 8965 Selector S = ME->getSelector(); 8966 StringRef SelArg0 = S.getNameForSlot(0); 8967 if (SelArg0.startswith("performSelector")) 8968 Diag = diag::warn_objc_pointer_masking_performSelector; 8969 } 8970 8971 S.Diag(OpLoc, Diag) 8972 << ObjCPointerExpr->getSourceRange(); 8973 } 8974 } 8975 8976 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 8977 /// operator @p Opc at location @c TokLoc. This routine only supports 8978 /// built-in operations; ActOnBinOp handles overloaded operators. 8979 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 8980 BinaryOperatorKind Opc, 8981 Expr *LHSExpr, Expr *RHSExpr) { 8982 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 8983 // The syntax only allows initializer lists on the RHS of assignment, 8984 // so we don't need to worry about accepting invalid code for 8985 // non-assignment operators. 8986 // C++11 5.17p9: 8987 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 8988 // of x = {} is x = T(). 8989 InitializationKind Kind = 8990 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 8991 InitializedEntity Entity = 8992 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 8993 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 8994 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 8995 if (Init.isInvalid()) 8996 return Init; 8997 RHSExpr = Init.take(); 8998 } 8999 9000 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 9001 QualType ResultTy; // Result type of the binary operator. 9002 // The following two variables are used for compound assignment operators 9003 QualType CompLHSTy; // Type of LHS after promotions for computation 9004 QualType CompResultTy; // Type of computation result 9005 ExprValueKind VK = VK_RValue; 9006 ExprObjectKind OK = OK_Ordinary; 9007 9008 switch (Opc) { 9009 case BO_Assign: 9010 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 9011 if (getLangOpts().CPlusPlus && 9012 LHS.get()->getObjectKind() != OK_ObjCProperty) { 9013 VK = LHS.get()->getValueKind(); 9014 OK = LHS.get()->getObjectKind(); 9015 } 9016 if (!ResultTy.isNull()) 9017 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 9018 break; 9019 case BO_PtrMemD: 9020 case BO_PtrMemI: 9021 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 9022 Opc == BO_PtrMemI); 9023 break; 9024 case BO_Mul: 9025 case BO_Div: 9026 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 9027 Opc == BO_Div); 9028 break; 9029 case BO_Rem: 9030 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 9031 break; 9032 case BO_Add: 9033 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 9034 break; 9035 case BO_Sub: 9036 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 9037 break; 9038 case BO_Shl: 9039 case BO_Shr: 9040 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 9041 break; 9042 case BO_LE: 9043 case BO_LT: 9044 case BO_GE: 9045 case BO_GT: 9046 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 9047 break; 9048 case BO_EQ: 9049 case BO_NE: 9050 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 9051 break; 9052 case BO_And: 9053 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 9054 case BO_Xor: 9055 case BO_Or: 9056 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 9057 break; 9058 case BO_LAnd: 9059 case BO_LOr: 9060 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 9061 break; 9062 case BO_MulAssign: 9063 case BO_DivAssign: 9064 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 9065 Opc == BO_DivAssign); 9066 CompLHSTy = CompResultTy; 9067 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9068 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9069 break; 9070 case BO_RemAssign: 9071 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 9072 CompLHSTy = CompResultTy; 9073 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9074 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9075 break; 9076 case BO_AddAssign: 9077 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 9078 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9079 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9080 break; 9081 case BO_SubAssign: 9082 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 9083 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9084 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9085 break; 9086 case BO_ShlAssign: 9087 case BO_ShrAssign: 9088 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 9089 CompLHSTy = CompResultTy; 9090 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9091 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9092 break; 9093 case BO_AndAssign: 9094 case BO_XorAssign: 9095 case BO_OrAssign: 9096 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 9097 CompLHSTy = CompResultTy; 9098 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9099 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9100 break; 9101 case BO_Comma: 9102 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 9103 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 9104 VK = RHS.get()->getValueKind(); 9105 OK = RHS.get()->getObjectKind(); 9106 } 9107 break; 9108 } 9109 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 9110 return ExprError(); 9111 9112 // Check for array bounds violations for both sides of the BinaryOperator 9113 CheckArrayAccess(LHS.get()); 9114 CheckArrayAccess(RHS.get()); 9115 9116 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 9117 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 9118 &Context.Idents.get("object_setClass"), 9119 SourceLocation(), LookupOrdinaryName); 9120 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 9121 SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 9122 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 9123 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 9124 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 9125 FixItHint::CreateInsertion(RHSLocEnd, ")"); 9126 } 9127 else 9128 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 9129 } 9130 else if (const ObjCIvarRefExpr *OIRE = 9131 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 9132 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 9133 9134 if (CompResultTy.isNull()) 9135 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc, 9136 ResultTy, VK, OK, OpLoc, 9137 FPFeatures.fp_contract)); 9138 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 9139 OK_ObjCProperty) { 9140 VK = VK_LValue; 9141 OK = LHS.get()->getObjectKind(); 9142 } 9143 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc, 9144 ResultTy, VK, OK, CompLHSTy, 9145 CompResultTy, OpLoc, 9146 FPFeatures.fp_contract)); 9147 } 9148 9149 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 9150 /// operators are mixed in a way that suggests that the programmer forgot that 9151 /// comparison operators have higher precedence. The most typical example of 9152 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 9153 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 9154 SourceLocation OpLoc, Expr *LHSExpr, 9155 Expr *RHSExpr) { 9156 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 9157 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 9158 9159 // Check that one of the sides is a comparison operator. 9160 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 9161 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 9162 if (!isLeftComp && !isRightComp) 9163 return; 9164 9165 // Bitwise operations are sometimes used as eager logical ops. 9166 // Don't diagnose this. 9167 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 9168 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 9169 if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise)) 9170 return; 9171 9172 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 9173 OpLoc) 9174 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 9175 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 9176 SourceRange ParensRange = isLeftComp ? 9177 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 9178 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart()); 9179 9180 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 9181 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 9182 SuggestParentheses(Self, OpLoc, 9183 Self.PDiag(diag::note_precedence_silence) << OpStr, 9184 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 9185 SuggestParentheses(Self, OpLoc, 9186 Self.PDiag(diag::note_precedence_bitwise_first) 9187 << BinaryOperator::getOpcodeStr(Opc), 9188 ParensRange); 9189 } 9190 9191 /// \brief It accepts a '&' expr that is inside a '|' one. 9192 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression 9193 /// in parentheses. 9194 static void 9195 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc, 9196 BinaryOperator *Bop) { 9197 assert(Bop->getOpcode() == BO_And); 9198 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or) 9199 << Bop->getSourceRange() << OpLoc; 9200 SuggestParentheses(Self, Bop->getOperatorLoc(), 9201 Self.PDiag(diag::note_precedence_silence) 9202 << Bop->getOpcodeStr(), 9203 Bop->getSourceRange()); 9204 } 9205 9206 /// \brief It accepts a '&&' expr that is inside a '||' one. 9207 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 9208 /// in parentheses. 9209 static void 9210 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 9211 BinaryOperator *Bop) { 9212 assert(Bop->getOpcode() == BO_LAnd); 9213 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 9214 << Bop->getSourceRange() << OpLoc; 9215 SuggestParentheses(Self, Bop->getOperatorLoc(), 9216 Self.PDiag(diag::note_precedence_silence) 9217 << Bop->getOpcodeStr(), 9218 Bop->getSourceRange()); 9219 } 9220 9221 /// \brief Returns true if the given expression can be evaluated as a constant 9222 /// 'true'. 9223 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 9224 bool Res; 9225 return !E->isValueDependent() && 9226 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 9227 } 9228 9229 /// \brief Returns true if the given expression can be evaluated as a constant 9230 /// 'false'. 9231 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 9232 bool Res; 9233 return !E->isValueDependent() && 9234 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 9235 } 9236 9237 /// \brief Look for '&&' in the left hand of a '||' expr. 9238 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 9239 Expr *LHSExpr, Expr *RHSExpr) { 9240 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 9241 if (Bop->getOpcode() == BO_LAnd) { 9242 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 9243 if (EvaluatesAsFalse(S, RHSExpr)) 9244 return; 9245 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 9246 if (!EvaluatesAsTrue(S, Bop->getLHS())) 9247 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 9248 } else if (Bop->getOpcode() == BO_LOr) { 9249 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 9250 // If it's "a || b && 1 || c" we didn't warn earlier for 9251 // "a || b && 1", but warn now. 9252 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 9253 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 9254 } 9255 } 9256 } 9257 } 9258 9259 /// \brief Look for '&&' in the right hand of a '||' expr. 9260 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 9261 Expr *LHSExpr, Expr *RHSExpr) { 9262 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 9263 if (Bop->getOpcode() == BO_LAnd) { 9264 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 9265 if (EvaluatesAsFalse(S, LHSExpr)) 9266 return; 9267 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 9268 if (!EvaluatesAsTrue(S, Bop->getRHS())) 9269 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 9270 } 9271 } 9272 } 9273 9274 /// \brief Look for '&' in the left or right hand of a '|' expr. 9275 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc, 9276 Expr *OrArg) { 9277 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) { 9278 if (Bop->getOpcode() == BO_And) 9279 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop); 9280 } 9281 } 9282 9283 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 9284 Expr *SubExpr, StringRef Shift) { 9285 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 9286 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 9287 StringRef Op = Bop->getOpcodeStr(); 9288 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 9289 << Bop->getSourceRange() << OpLoc << Shift << Op; 9290 SuggestParentheses(S, Bop->getOperatorLoc(), 9291 S.PDiag(diag::note_precedence_silence) << Op, 9292 Bop->getSourceRange()); 9293 } 9294 } 9295 } 9296 9297 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 9298 Expr *LHSExpr, Expr *RHSExpr) { 9299 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 9300 if (!OCE) 9301 return; 9302 9303 FunctionDecl *FD = OCE->getDirectCallee(); 9304 if (!FD || !FD->isOverloadedOperator()) 9305 return; 9306 9307 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 9308 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 9309 return; 9310 9311 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 9312 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 9313 << (Kind == OO_LessLess); 9314 SuggestParentheses(S, OCE->getOperatorLoc(), 9315 S.PDiag(diag::note_precedence_silence) 9316 << (Kind == OO_LessLess ? "<<" : ">>"), 9317 OCE->getSourceRange()); 9318 SuggestParentheses(S, OpLoc, 9319 S.PDiag(diag::note_evaluate_comparison_first), 9320 SourceRange(OCE->getArg(1)->getLocStart(), 9321 RHSExpr->getLocEnd())); 9322 } 9323 9324 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 9325 /// precedence. 9326 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 9327 SourceLocation OpLoc, Expr *LHSExpr, 9328 Expr *RHSExpr){ 9329 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 9330 if (BinaryOperator::isBitwiseOp(Opc)) 9331 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 9332 9333 // Diagnose "arg1 & arg2 | arg3" 9334 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) { 9335 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr); 9336 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr); 9337 } 9338 9339 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 9340 // We don't warn for 'assert(a || b && "bad")' since this is safe. 9341 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 9342 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 9343 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 9344 } 9345 9346 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 9347 || Opc == BO_Shr) { 9348 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 9349 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 9350 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 9351 } 9352 9353 // Warn on overloaded shift operators and comparisons, such as: 9354 // cout << 5 == 4; 9355 if (BinaryOperator::isComparisonOp(Opc)) 9356 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 9357 } 9358 9359 // Binary Operators. 'Tok' is the token for the operator. 9360 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 9361 tok::TokenKind Kind, 9362 Expr *LHSExpr, Expr *RHSExpr) { 9363 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 9364 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression"); 9365 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression"); 9366 9367 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 9368 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 9369 9370 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 9371 } 9372 9373 /// Build an overloaded binary operator expression in the given scope. 9374 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 9375 BinaryOperatorKind Opc, 9376 Expr *LHS, Expr *RHS) { 9377 // Find all of the overloaded operators visible from this 9378 // point. We perform both an operator-name lookup from the local 9379 // scope and an argument-dependent lookup based on the types of 9380 // the arguments. 9381 UnresolvedSet<16> Functions; 9382 OverloadedOperatorKind OverOp 9383 = BinaryOperator::getOverloadedOperator(Opc); 9384 if (Sc && OverOp != OO_None) 9385 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 9386 RHS->getType(), Functions); 9387 9388 // Build the (potentially-overloaded, potentially-dependent) 9389 // binary operation. 9390 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 9391 } 9392 9393 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 9394 BinaryOperatorKind Opc, 9395 Expr *LHSExpr, Expr *RHSExpr) { 9396 // We want to end up calling one of checkPseudoObjectAssignment 9397 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 9398 // both expressions are overloadable or either is type-dependent), 9399 // or CreateBuiltinBinOp (in any other case). We also want to get 9400 // any placeholder types out of the way. 9401 9402 // Handle pseudo-objects in the LHS. 9403 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 9404 // Assignments with a pseudo-object l-value need special analysis. 9405 if (pty->getKind() == BuiltinType::PseudoObject && 9406 BinaryOperator::isAssignmentOp(Opc)) 9407 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 9408 9409 // Don't resolve overloads if the other type is overloadable. 9410 if (pty->getKind() == BuiltinType::Overload) { 9411 // We can't actually test that if we still have a placeholder, 9412 // though. Fortunately, none of the exceptions we see in that 9413 // code below are valid when the LHS is an overload set. Note 9414 // that an overload set can be dependently-typed, but it never 9415 // instantiates to having an overloadable type. 9416 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 9417 if (resolvedRHS.isInvalid()) return ExprError(); 9418 RHSExpr = resolvedRHS.take(); 9419 9420 if (RHSExpr->isTypeDependent() || 9421 RHSExpr->getType()->isOverloadableType()) 9422 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9423 } 9424 9425 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 9426 if (LHS.isInvalid()) return ExprError(); 9427 LHSExpr = LHS.take(); 9428 } 9429 9430 // Handle pseudo-objects in the RHS. 9431 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 9432 // An overload in the RHS can potentially be resolved by the type 9433 // being assigned to. 9434 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 9435 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 9436 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9437 9438 if (LHSExpr->getType()->isOverloadableType()) 9439 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9440 9441 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 9442 } 9443 9444 // Don't resolve overloads if the other type is overloadable. 9445 if (pty->getKind() == BuiltinType::Overload && 9446 LHSExpr->getType()->isOverloadableType()) 9447 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9448 9449 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 9450 if (!resolvedRHS.isUsable()) return ExprError(); 9451 RHSExpr = resolvedRHS.take(); 9452 } 9453 9454 if (getLangOpts().CPlusPlus) { 9455 // If either expression is type-dependent, always build an 9456 // overloaded op. 9457 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 9458 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9459 9460 // Otherwise, build an overloaded op if either expression has an 9461 // overloadable type. 9462 if (LHSExpr->getType()->isOverloadableType() || 9463 RHSExpr->getType()->isOverloadableType()) 9464 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9465 } 9466 9467 // Build a built-in binary operation. 9468 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 9469 } 9470 9471 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 9472 UnaryOperatorKind Opc, 9473 Expr *InputExpr) { 9474 ExprResult Input = Owned(InputExpr); 9475 ExprValueKind VK = VK_RValue; 9476 ExprObjectKind OK = OK_Ordinary; 9477 QualType resultType; 9478 switch (Opc) { 9479 case UO_PreInc: 9480 case UO_PreDec: 9481 case UO_PostInc: 9482 case UO_PostDec: 9483 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc, 9484 Opc == UO_PreInc || 9485 Opc == UO_PostInc, 9486 Opc == UO_PreInc || 9487 Opc == UO_PreDec); 9488 break; 9489 case UO_AddrOf: 9490 resultType = CheckAddressOfOperand(Input, OpLoc); 9491 break; 9492 case UO_Deref: { 9493 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 9494 if (Input.isInvalid()) return ExprError(); 9495 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 9496 break; 9497 } 9498 case UO_Plus: 9499 case UO_Minus: 9500 Input = UsualUnaryConversions(Input.take()); 9501 if (Input.isInvalid()) return ExprError(); 9502 resultType = Input.get()->getType(); 9503 if (resultType->isDependentType()) 9504 break; 9505 if (resultType->isArithmeticType() || // C99 6.5.3.3p1 9506 resultType->isVectorType()) 9507 break; 9508 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 9509 Opc == UO_Plus && 9510 resultType->isPointerType()) 9511 break; 9512 9513 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9514 << resultType << Input.get()->getSourceRange()); 9515 9516 case UO_Not: // bitwise complement 9517 Input = UsualUnaryConversions(Input.take()); 9518 if (Input.isInvalid()) 9519 return ExprError(); 9520 resultType = Input.get()->getType(); 9521 if (resultType->isDependentType()) 9522 break; 9523 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 9524 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 9525 // C99 does not support '~' for complex conjugation. 9526 Diag(OpLoc, diag::ext_integer_complement_complex) 9527 << resultType << Input.get()->getSourceRange(); 9528 else if (resultType->hasIntegerRepresentation()) 9529 break; 9530 else if (resultType->isExtVectorType()) { 9531 if (Context.getLangOpts().OpenCL) { 9532 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 9533 // on vector float types. 9534 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 9535 if (!T->isIntegerType()) 9536 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9537 << resultType << Input.get()->getSourceRange()); 9538 } 9539 break; 9540 } else { 9541 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9542 << resultType << Input.get()->getSourceRange()); 9543 } 9544 break; 9545 9546 case UO_LNot: // logical negation 9547 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 9548 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 9549 if (Input.isInvalid()) return ExprError(); 9550 resultType = Input.get()->getType(); 9551 9552 // Though we still have to promote half FP to float... 9553 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 9554 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take(); 9555 resultType = Context.FloatTy; 9556 } 9557 9558 if (resultType->isDependentType()) 9559 break; 9560 if (resultType->isScalarType()) { 9561 // C99 6.5.3.3p1: ok, fallthrough; 9562 if (Context.getLangOpts().CPlusPlus) { 9563 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 9564 // operand contextually converted to bool. 9565 Input = ImpCastExprToType(Input.take(), Context.BoolTy, 9566 ScalarTypeToBooleanCastKind(resultType)); 9567 } else if (Context.getLangOpts().OpenCL && 9568 Context.getLangOpts().OpenCLVersion < 120) { 9569 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 9570 // operate on scalar float types. 9571 if (!resultType->isIntegerType()) 9572 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9573 << resultType << Input.get()->getSourceRange()); 9574 } 9575 } else if (resultType->isExtVectorType()) { 9576 if (Context.getLangOpts().OpenCL && 9577 Context.getLangOpts().OpenCLVersion < 120) { 9578 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 9579 // operate on vector float types. 9580 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 9581 if (!T->isIntegerType()) 9582 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9583 << resultType << Input.get()->getSourceRange()); 9584 } 9585 // Vector logical not returns the signed variant of the operand type. 9586 resultType = GetSignedVectorType(resultType); 9587 break; 9588 } else { 9589 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9590 << resultType << Input.get()->getSourceRange()); 9591 } 9592 9593 // LNot always has type int. C99 6.5.3.3p5. 9594 // In C++, it's bool. C++ 5.3.1p8 9595 resultType = Context.getLogicalOperationType(); 9596 break; 9597 case UO_Real: 9598 case UO_Imag: 9599 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 9600 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 9601 // complex l-values to ordinary l-values and all other values to r-values. 9602 if (Input.isInvalid()) return ExprError(); 9603 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 9604 if (Input.get()->getValueKind() != VK_RValue && 9605 Input.get()->getObjectKind() == OK_Ordinary) 9606 VK = Input.get()->getValueKind(); 9607 } else if (!getLangOpts().CPlusPlus) { 9608 // In C, a volatile scalar is read by __imag. In C++, it is not. 9609 Input = DefaultLvalueConversion(Input.take()); 9610 } 9611 break; 9612 case UO_Extension: 9613 resultType = Input.get()->getType(); 9614 VK = Input.get()->getValueKind(); 9615 OK = Input.get()->getObjectKind(); 9616 break; 9617 } 9618 if (resultType.isNull() || Input.isInvalid()) 9619 return ExprError(); 9620 9621 // Check for array bounds violations in the operand of the UnaryOperator, 9622 // except for the '*' and '&' operators that have to be handled specially 9623 // by CheckArrayAccess (as there are special cases like &array[arraysize] 9624 // that are explicitly defined as valid by the standard). 9625 if (Opc != UO_AddrOf && Opc != UO_Deref) 9626 CheckArrayAccess(Input.get()); 9627 9628 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType, 9629 VK, OK, OpLoc)); 9630 } 9631 9632 /// \brief Determine whether the given expression is a qualified member 9633 /// access expression, of a form that could be turned into a pointer to member 9634 /// with the address-of operator. 9635 static bool isQualifiedMemberAccess(Expr *E) { 9636 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9637 if (!DRE->getQualifier()) 9638 return false; 9639 9640 ValueDecl *VD = DRE->getDecl(); 9641 if (!VD->isCXXClassMember()) 9642 return false; 9643 9644 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 9645 return true; 9646 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 9647 return Method->isInstance(); 9648 9649 return false; 9650 } 9651 9652 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 9653 if (!ULE->getQualifier()) 9654 return false; 9655 9656 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(), 9657 DEnd = ULE->decls_end(); 9658 D != DEnd; ++D) { 9659 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) { 9660 if (Method->isInstance()) 9661 return true; 9662 } else { 9663 // Overload set does not contain methods. 9664 break; 9665 } 9666 } 9667 9668 return false; 9669 } 9670 9671 return false; 9672 } 9673 9674 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 9675 UnaryOperatorKind Opc, Expr *Input) { 9676 // First things first: handle placeholders so that the 9677 // overloaded-operator check considers the right type. 9678 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 9679 // Increment and decrement of pseudo-object references. 9680 if (pty->getKind() == BuiltinType::PseudoObject && 9681 UnaryOperator::isIncrementDecrementOp(Opc)) 9682 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 9683 9684 // extension is always a builtin operator. 9685 if (Opc == UO_Extension) 9686 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9687 9688 // & gets special logic for several kinds of placeholder. 9689 // The builtin code knows what to do. 9690 if (Opc == UO_AddrOf && 9691 (pty->getKind() == BuiltinType::Overload || 9692 pty->getKind() == BuiltinType::UnknownAny || 9693 pty->getKind() == BuiltinType::BoundMember)) 9694 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9695 9696 // Anything else needs to be handled now. 9697 ExprResult Result = CheckPlaceholderExpr(Input); 9698 if (Result.isInvalid()) return ExprError(); 9699 Input = Result.take(); 9700 } 9701 9702 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 9703 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 9704 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 9705 // Find all of the overloaded operators visible from this 9706 // point. We perform both an operator-name lookup from the local 9707 // scope and an argument-dependent lookup based on the types of 9708 // the arguments. 9709 UnresolvedSet<16> Functions; 9710 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 9711 if (S && OverOp != OO_None) 9712 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 9713 Functions); 9714 9715 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 9716 } 9717 9718 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9719 } 9720 9721 // Unary Operators. 'Tok' is the token for the operator. 9722 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 9723 tok::TokenKind Op, Expr *Input) { 9724 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 9725 } 9726 9727 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 9728 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 9729 LabelDecl *TheDecl) { 9730 TheDecl->markUsed(Context); 9731 // Create the AST node. The address of a label always has type 'void*'. 9732 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 9733 Context.getPointerType(Context.VoidTy))); 9734 } 9735 9736 /// Given the last statement in a statement-expression, check whether 9737 /// the result is a producing expression (like a call to an 9738 /// ns_returns_retained function) and, if so, rebuild it to hoist the 9739 /// release out of the full-expression. Otherwise, return null. 9740 /// Cannot fail. 9741 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 9742 // Should always be wrapped with one of these. 9743 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 9744 if (!cleanups) return 0; 9745 9746 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 9747 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 9748 return 0; 9749 9750 // Splice out the cast. This shouldn't modify any interesting 9751 // features of the statement. 9752 Expr *producer = cast->getSubExpr(); 9753 assert(producer->getType() == cast->getType()); 9754 assert(producer->getValueKind() == cast->getValueKind()); 9755 cleanups->setSubExpr(producer); 9756 return cleanups; 9757 } 9758 9759 void Sema::ActOnStartStmtExpr() { 9760 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 9761 } 9762 9763 void Sema::ActOnStmtExprError() { 9764 // Note that function is also called by TreeTransform when leaving a 9765 // StmtExpr scope without rebuilding anything. 9766 9767 DiscardCleanupsInEvaluationContext(); 9768 PopExpressionEvaluationContext(); 9769 } 9770 9771 ExprResult 9772 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 9773 SourceLocation RPLoc) { // "({..})" 9774 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 9775 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 9776 9777 if (hasAnyUnrecoverableErrorsInThisFunction()) 9778 DiscardCleanupsInEvaluationContext(); 9779 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!"); 9780 PopExpressionEvaluationContext(); 9781 9782 bool isFileScope 9783 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0); 9784 if (isFileScope) 9785 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope)); 9786 9787 // FIXME: there are a variety of strange constraints to enforce here, for 9788 // example, it is not possible to goto into a stmt expression apparently. 9789 // More semantic analysis is needed. 9790 9791 // If there are sub stmts in the compound stmt, take the type of the last one 9792 // as the type of the stmtexpr. 9793 QualType Ty = Context.VoidTy; 9794 bool StmtExprMayBindToTemp = false; 9795 if (!Compound->body_empty()) { 9796 Stmt *LastStmt = Compound->body_back(); 9797 LabelStmt *LastLabelStmt = 0; 9798 // If LastStmt is a label, skip down through into the body. 9799 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 9800 LastLabelStmt = Label; 9801 LastStmt = Label->getSubStmt(); 9802 } 9803 9804 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 9805 // Do function/array conversion on the last expression, but not 9806 // lvalue-to-rvalue. However, initialize an unqualified type. 9807 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 9808 if (LastExpr.isInvalid()) 9809 return ExprError(); 9810 Ty = LastExpr.get()->getType().getUnqualifiedType(); 9811 9812 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 9813 // In ARC, if the final expression ends in a consume, splice 9814 // the consume out and bind it later. In the alternate case 9815 // (when dealing with a retainable type), the result 9816 // initialization will create a produce. In both cases the 9817 // result will be +1, and we'll need to balance that out with 9818 // a bind. 9819 if (Expr *rebuiltLastStmt 9820 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 9821 LastExpr = rebuiltLastStmt; 9822 } else { 9823 LastExpr = PerformCopyInitialization( 9824 InitializedEntity::InitializeResult(LPLoc, 9825 Ty, 9826 false), 9827 SourceLocation(), 9828 LastExpr); 9829 } 9830 9831 if (LastExpr.isInvalid()) 9832 return ExprError(); 9833 if (LastExpr.get() != 0) { 9834 if (!LastLabelStmt) 9835 Compound->setLastStmt(LastExpr.take()); 9836 else 9837 LastLabelStmt->setSubStmt(LastExpr.take()); 9838 StmtExprMayBindToTemp = true; 9839 } 9840 } 9841 } 9842 } 9843 9844 // FIXME: Check that expression type is complete/non-abstract; statement 9845 // expressions are not lvalues. 9846 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 9847 if (StmtExprMayBindToTemp) 9848 return MaybeBindToTemporary(ResStmtExpr); 9849 return Owned(ResStmtExpr); 9850 } 9851 9852 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 9853 TypeSourceInfo *TInfo, 9854 OffsetOfComponent *CompPtr, 9855 unsigned NumComponents, 9856 SourceLocation RParenLoc) { 9857 QualType ArgTy = TInfo->getType(); 9858 bool Dependent = ArgTy->isDependentType(); 9859 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 9860 9861 // We must have at least one component that refers to the type, and the first 9862 // one is known to be a field designator. Verify that the ArgTy represents 9863 // a struct/union/class. 9864 if (!Dependent && !ArgTy->isRecordType()) 9865 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 9866 << ArgTy << TypeRange); 9867 9868 // Type must be complete per C99 7.17p3 because a declaring a variable 9869 // with an incomplete type would be ill-formed. 9870 if (!Dependent 9871 && RequireCompleteType(BuiltinLoc, ArgTy, 9872 diag::err_offsetof_incomplete_type, TypeRange)) 9873 return ExprError(); 9874 9875 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 9876 // GCC extension, diagnose them. 9877 // FIXME: This diagnostic isn't actually visible because the location is in 9878 // a system header! 9879 if (NumComponents != 1) 9880 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 9881 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); 9882 9883 bool DidWarnAboutNonPOD = false; 9884 QualType CurrentType = ArgTy; 9885 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; 9886 SmallVector<OffsetOfNode, 4> Comps; 9887 SmallVector<Expr*, 4> Exprs; 9888 for (unsigned i = 0; i != NumComponents; ++i) { 9889 const OffsetOfComponent &OC = CompPtr[i]; 9890 if (OC.isBrackets) { 9891 // Offset of an array sub-field. TODO: Should we allow vector elements? 9892 if (!CurrentType->isDependentType()) { 9893 const ArrayType *AT = Context.getAsArrayType(CurrentType); 9894 if(!AT) 9895 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 9896 << CurrentType); 9897 CurrentType = AT->getElementType(); 9898 } else 9899 CurrentType = Context.DependentTy; 9900 9901 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 9902 if (IdxRval.isInvalid()) 9903 return ExprError(); 9904 Expr *Idx = IdxRval.take(); 9905 9906 // The expression must be an integral expression. 9907 // FIXME: An integral constant expression? 9908 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 9909 !Idx->getType()->isIntegerType()) 9910 return ExprError(Diag(Idx->getLocStart(), 9911 diag::err_typecheck_subscript_not_integer) 9912 << Idx->getSourceRange()); 9913 9914 // Record this array index. 9915 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 9916 Exprs.push_back(Idx); 9917 continue; 9918 } 9919 9920 // Offset of a field. 9921 if (CurrentType->isDependentType()) { 9922 // We have the offset of a field, but we can't look into the dependent 9923 // type. Just record the identifier of the field. 9924 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 9925 CurrentType = Context.DependentTy; 9926 continue; 9927 } 9928 9929 // We need to have a complete type to look into. 9930 if (RequireCompleteType(OC.LocStart, CurrentType, 9931 diag::err_offsetof_incomplete_type)) 9932 return ExprError(); 9933 9934 // Look for the designated field. 9935 const RecordType *RC = CurrentType->getAs<RecordType>(); 9936 if (!RC) 9937 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 9938 << CurrentType); 9939 RecordDecl *RD = RC->getDecl(); 9940 9941 // C++ [lib.support.types]p5: 9942 // The macro offsetof accepts a restricted set of type arguments in this 9943 // International Standard. type shall be a POD structure or a POD union 9944 // (clause 9). 9945 // C++11 [support.types]p4: 9946 // If type is not a standard-layout class (Clause 9), the results are 9947 // undefined. 9948 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 9949 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 9950 unsigned DiagID = 9951 LangOpts.CPlusPlus11? diag::warn_offsetof_non_standardlayout_type 9952 : diag::warn_offsetof_non_pod_type; 9953 9954 if (!IsSafe && !DidWarnAboutNonPOD && 9955 DiagRuntimeBehavior(BuiltinLoc, 0, 9956 PDiag(DiagID) 9957 << SourceRange(CompPtr[0].LocStart, OC.LocEnd) 9958 << CurrentType)) 9959 DidWarnAboutNonPOD = true; 9960 } 9961 9962 // Look for the field. 9963 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 9964 LookupQualifiedName(R, RD); 9965 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 9966 IndirectFieldDecl *IndirectMemberDecl = 0; 9967 if (!MemberDecl) { 9968 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 9969 MemberDecl = IndirectMemberDecl->getAnonField(); 9970 } 9971 9972 if (!MemberDecl) 9973 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 9974 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 9975 OC.LocEnd)); 9976 9977 // C99 7.17p3: 9978 // (If the specified member is a bit-field, the behavior is undefined.) 9979 // 9980 // We diagnose this as an error. 9981 if (MemberDecl->isBitField()) { 9982 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 9983 << MemberDecl->getDeclName() 9984 << SourceRange(BuiltinLoc, RParenLoc); 9985 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 9986 return ExprError(); 9987 } 9988 9989 RecordDecl *Parent = MemberDecl->getParent(); 9990 if (IndirectMemberDecl) 9991 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 9992 9993 // If the member was found in a base class, introduce OffsetOfNodes for 9994 // the base class indirections. 9995 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 9996 /*DetectVirtual=*/false); 9997 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) { 9998 CXXBasePath &Path = Paths.front(); 9999 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end(); 10000 B != BEnd; ++B) 10001 Comps.push_back(OffsetOfNode(B->Base)); 10002 } 10003 10004 if (IndirectMemberDecl) { 10005 for (IndirectFieldDecl::chain_iterator FI = 10006 IndirectMemberDecl->chain_begin(), 10007 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) { 10008 assert(isa<FieldDecl>(*FI)); 10009 Comps.push_back(OffsetOfNode(OC.LocStart, 10010 cast<FieldDecl>(*FI), OC.LocEnd)); 10011 } 10012 } else 10013 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 10014 10015 CurrentType = MemberDecl->getType().getNonReferenceType(); 10016 } 10017 10018 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, 10019 TInfo, Comps, Exprs, RParenLoc)); 10020 } 10021 10022 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 10023 SourceLocation BuiltinLoc, 10024 SourceLocation TypeLoc, 10025 ParsedType ParsedArgTy, 10026 OffsetOfComponent *CompPtr, 10027 unsigned NumComponents, 10028 SourceLocation RParenLoc) { 10029 10030 TypeSourceInfo *ArgTInfo; 10031 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 10032 if (ArgTy.isNull()) 10033 return ExprError(); 10034 10035 if (!ArgTInfo) 10036 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 10037 10038 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents, 10039 RParenLoc); 10040 } 10041 10042 10043 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 10044 Expr *CondExpr, 10045 Expr *LHSExpr, Expr *RHSExpr, 10046 SourceLocation RPLoc) { 10047 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 10048 10049 ExprValueKind VK = VK_RValue; 10050 ExprObjectKind OK = OK_Ordinary; 10051 QualType resType; 10052 bool ValueDependent = false; 10053 bool CondIsTrue = false; 10054 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 10055 resType = Context.DependentTy; 10056 ValueDependent = true; 10057 } else { 10058 // The conditional expression is required to be a constant expression. 10059 llvm::APSInt condEval(32); 10060 ExprResult CondICE 10061 = VerifyIntegerConstantExpression(CondExpr, &condEval, 10062 diag::err_typecheck_choose_expr_requires_constant, false); 10063 if (CondICE.isInvalid()) 10064 return ExprError(); 10065 CondExpr = CondICE.take(); 10066 CondIsTrue = condEval.getZExtValue(); 10067 10068 // If the condition is > zero, then the AST type is the same as the LSHExpr. 10069 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 10070 10071 resType = ActiveExpr->getType(); 10072 ValueDependent = ActiveExpr->isValueDependent(); 10073 VK = ActiveExpr->getValueKind(); 10074 OK = ActiveExpr->getObjectKind(); 10075 } 10076 10077 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 10078 resType, VK, OK, RPLoc, CondIsTrue, 10079 resType->isDependentType(), 10080 ValueDependent)); 10081 } 10082 10083 //===----------------------------------------------------------------------===// 10084 // Clang Extensions. 10085 //===----------------------------------------------------------------------===// 10086 10087 /// ActOnBlockStart - This callback is invoked when a block literal is started. 10088 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 10089 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 10090 10091 if (LangOpts.CPlusPlus) { 10092 Decl *ManglingContextDecl; 10093 if (MangleNumberingContext *MCtx = 10094 getCurrentMangleNumberContext(Block->getDeclContext(), 10095 ManglingContextDecl)) { 10096 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 10097 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 10098 } 10099 } 10100 10101 PushBlockScope(CurScope, Block); 10102 CurContext->addDecl(Block); 10103 if (CurScope) 10104 PushDeclContext(CurScope, Block); 10105 else 10106 CurContext = Block; 10107 10108 getCurBlock()->HasImplicitReturnType = true; 10109 10110 // Enter a new evaluation context to insulate the block from any 10111 // cleanups from the enclosing full-expression. 10112 PushExpressionEvaluationContext(PotentiallyEvaluated); 10113 } 10114 10115 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 10116 Scope *CurScope) { 10117 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!"); 10118 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 10119 BlockScopeInfo *CurBlock = getCurBlock(); 10120 10121 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 10122 QualType T = Sig->getType(); 10123 10124 // FIXME: We should allow unexpanded parameter packs here, but that would, 10125 // in turn, make the block expression contain unexpanded parameter packs. 10126 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 10127 // Drop the parameters. 10128 FunctionProtoType::ExtProtoInfo EPI; 10129 EPI.HasTrailingReturn = false; 10130 EPI.TypeQuals |= DeclSpec::TQ_const; 10131 T = Context.getFunctionType(Context.DependentTy, None, EPI); 10132 Sig = Context.getTrivialTypeSourceInfo(T); 10133 } 10134 10135 // GetTypeForDeclarator always produces a function type for a block 10136 // literal signature. Furthermore, it is always a FunctionProtoType 10137 // unless the function was written with a typedef. 10138 assert(T->isFunctionType() && 10139 "GetTypeForDeclarator made a non-function block signature"); 10140 10141 // Look for an explicit signature in that function type. 10142 FunctionProtoTypeLoc ExplicitSignature; 10143 10144 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 10145 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 10146 10147 // Check whether that explicit signature was synthesized by 10148 // GetTypeForDeclarator. If so, don't save that as part of the 10149 // written signature. 10150 if (ExplicitSignature.getLocalRangeBegin() == 10151 ExplicitSignature.getLocalRangeEnd()) { 10152 // This would be much cheaper if we stored TypeLocs instead of 10153 // TypeSourceInfos. 10154 TypeLoc Result = ExplicitSignature.getResultLoc(); 10155 unsigned Size = Result.getFullDataSize(); 10156 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 10157 Sig->getTypeLoc().initializeFullCopy(Result, Size); 10158 10159 ExplicitSignature = FunctionProtoTypeLoc(); 10160 } 10161 } 10162 10163 CurBlock->TheDecl->setSignatureAsWritten(Sig); 10164 CurBlock->FunctionType = T; 10165 10166 const FunctionType *Fn = T->getAs<FunctionType>(); 10167 QualType RetTy = Fn->getResultType(); 10168 bool isVariadic = 10169 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 10170 10171 CurBlock->TheDecl->setIsVariadic(isVariadic); 10172 10173 // Context.DependentTy is used as a placeholder for a missing block 10174 // return type. TODO: what should we do with declarators like: 10175 // ^ * { ... } 10176 // If the answer is "apply template argument deduction".... 10177 if (RetTy != Context.DependentTy) { 10178 CurBlock->ReturnType = RetTy; 10179 CurBlock->TheDecl->setBlockMissingReturnType(false); 10180 CurBlock->HasImplicitReturnType = false; 10181 } 10182 10183 // Push block parameters from the declarator if we had them. 10184 SmallVector<ParmVarDecl*, 8> Params; 10185 if (ExplicitSignature) { 10186 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) { 10187 ParmVarDecl *Param = ExplicitSignature.getArg(I); 10188 if (Param->getIdentifier() == 0 && 10189 !Param->isImplicit() && 10190 !Param->isInvalidDecl() && 10191 !getLangOpts().CPlusPlus) 10192 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 10193 Params.push_back(Param); 10194 } 10195 10196 // Fake up parameter variables if we have a typedef, like 10197 // ^ fntype { ... } 10198 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 10199 for (FunctionProtoType::arg_type_iterator 10200 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) { 10201 ParmVarDecl *Param = 10202 BuildParmVarDeclForTypedef(CurBlock->TheDecl, 10203 ParamInfo.getLocStart(), 10204 *I); 10205 Params.push_back(Param); 10206 } 10207 } 10208 10209 // Set the parameters on the block decl. 10210 if (!Params.empty()) { 10211 CurBlock->TheDecl->setParams(Params); 10212 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(), 10213 CurBlock->TheDecl->param_end(), 10214 /*CheckParameterNames=*/false); 10215 } 10216 10217 // Finally we can process decl attributes. 10218 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 10219 10220 // Put the parameter variables in scope. 10221 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(), 10222 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) { 10223 (*AI)->setOwningFunction(CurBlock->TheDecl); 10224 10225 // If this has an identifier, add it to the scope stack. 10226 if ((*AI)->getIdentifier()) { 10227 CheckShadow(CurBlock->TheScope, *AI); 10228 10229 PushOnScopeChains(*AI, CurBlock->TheScope); 10230 } 10231 } 10232 } 10233 10234 /// ActOnBlockError - If there is an error parsing a block, this callback 10235 /// is invoked to pop the information about the block from the action impl. 10236 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 10237 // Leave the expression-evaluation context. 10238 DiscardCleanupsInEvaluationContext(); 10239 PopExpressionEvaluationContext(); 10240 10241 // Pop off CurBlock, handle nested blocks. 10242 PopDeclContext(); 10243 PopFunctionScopeInfo(); 10244 } 10245 10246 /// ActOnBlockStmtExpr - This is called when the body of a block statement 10247 /// literal was successfully completed. ^(int x){...} 10248 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 10249 Stmt *Body, Scope *CurScope) { 10250 // If blocks are disabled, emit an error. 10251 if (!LangOpts.Blocks) 10252 Diag(CaretLoc, diag::err_blocks_disable); 10253 10254 // Leave the expression-evaluation context. 10255 if (hasAnyUnrecoverableErrorsInThisFunction()) 10256 DiscardCleanupsInEvaluationContext(); 10257 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!"); 10258 PopExpressionEvaluationContext(); 10259 10260 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 10261 10262 if (BSI->HasImplicitReturnType) 10263 deduceClosureReturnType(*BSI); 10264 10265 PopDeclContext(); 10266 10267 QualType RetTy = Context.VoidTy; 10268 if (!BSI->ReturnType.isNull()) 10269 RetTy = BSI->ReturnType; 10270 10271 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>(); 10272 QualType BlockTy; 10273 10274 // Set the captured variables on the block. 10275 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 10276 SmallVector<BlockDecl::Capture, 4> Captures; 10277 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) { 10278 CapturingScopeInfo::Capture &Cap = BSI->Captures[i]; 10279 if (Cap.isThisCapture()) 10280 continue; 10281 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 10282 Cap.isNested(), Cap.getInitExpr()); 10283 Captures.push_back(NewCap); 10284 } 10285 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(), 10286 BSI->CXXThisCaptureIndex != 0); 10287 10288 // If the user wrote a function type in some form, try to use that. 10289 if (!BSI->FunctionType.isNull()) { 10290 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 10291 10292 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 10293 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 10294 10295 // Turn protoless block types into nullary block types. 10296 if (isa<FunctionNoProtoType>(FTy)) { 10297 FunctionProtoType::ExtProtoInfo EPI; 10298 EPI.ExtInfo = Ext; 10299 BlockTy = Context.getFunctionType(RetTy, None, EPI); 10300 10301 // Otherwise, if we don't need to change anything about the function type, 10302 // preserve its sugar structure. 10303 } else if (FTy->getResultType() == RetTy && 10304 (!NoReturn || FTy->getNoReturnAttr())) { 10305 BlockTy = BSI->FunctionType; 10306 10307 // Otherwise, make the minimal modifications to the function type. 10308 } else { 10309 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 10310 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10311 EPI.TypeQuals = 0; // FIXME: silently? 10312 EPI.ExtInfo = Ext; 10313 BlockTy = Context.getFunctionType(RetTy, FPT->getArgTypes(), EPI); 10314 } 10315 10316 // If we don't have a function type, just build one from nothing. 10317 } else { 10318 FunctionProtoType::ExtProtoInfo EPI; 10319 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 10320 BlockTy = Context.getFunctionType(RetTy, None, EPI); 10321 } 10322 10323 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(), 10324 BSI->TheDecl->param_end()); 10325 BlockTy = Context.getBlockPointerType(BlockTy); 10326 10327 // If needed, diagnose invalid gotos and switches in the block. 10328 if (getCurFunction()->NeedsScopeChecking() && 10329 !hasAnyUnrecoverableErrorsInThisFunction() && 10330 !PP.isCodeCompletionEnabled()) 10331 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 10332 10333 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 10334 10335 // Try to apply the named return value optimization. We have to check again 10336 // if we can do this, though, because blocks keep return statements around 10337 // to deduce an implicit return type. 10338 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 10339 !BSI->TheDecl->isDependentContext()) 10340 computeNRVO(Body, getCurBlock()); 10341 10342 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 10343 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 10344 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 10345 10346 // If the block isn't obviously global, i.e. it captures anything at 10347 // all, then we need to do a few things in the surrounding context: 10348 if (Result->getBlockDecl()->hasCaptures()) { 10349 // First, this expression has a new cleanup object. 10350 ExprCleanupObjects.push_back(Result->getBlockDecl()); 10351 ExprNeedsCleanups = true; 10352 10353 // It also gets a branch-protected scope if any of the captured 10354 // variables needs destruction. 10355 for (BlockDecl::capture_const_iterator 10356 ci = Result->getBlockDecl()->capture_begin(), 10357 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) { 10358 const VarDecl *var = ci->getVariable(); 10359 if (var->getType().isDestructedType() != QualType::DK_none) { 10360 getCurFunction()->setHasBranchProtectedScope(); 10361 break; 10362 } 10363 } 10364 } 10365 10366 return Owned(Result); 10367 } 10368 10369 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 10370 Expr *E, ParsedType Ty, 10371 SourceLocation RPLoc) { 10372 TypeSourceInfo *TInfo; 10373 GetTypeFromParser(Ty, &TInfo); 10374 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 10375 } 10376 10377 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 10378 Expr *E, TypeSourceInfo *TInfo, 10379 SourceLocation RPLoc) { 10380 Expr *OrigExpr = E; 10381 10382 // Get the va_list type 10383 QualType VaListType = Context.getBuiltinVaListType(); 10384 if (VaListType->isArrayType()) { 10385 // Deal with implicit array decay; for example, on x86-64, 10386 // va_list is an array, but it's supposed to decay to 10387 // a pointer for va_arg. 10388 VaListType = Context.getArrayDecayedType(VaListType); 10389 // Make sure the input expression also decays appropriately. 10390 ExprResult Result = UsualUnaryConversions(E); 10391 if (Result.isInvalid()) 10392 return ExprError(); 10393 E = Result.take(); 10394 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 10395 // If va_list is a record type and we are compiling in C++ mode, 10396 // check the argument using reference binding. 10397 InitializedEntity Entity 10398 = InitializedEntity::InitializeParameter(Context, 10399 Context.getLValueReferenceType(VaListType), false); 10400 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 10401 if (Init.isInvalid()) 10402 return ExprError(); 10403 E = Init.takeAs<Expr>(); 10404 } else { 10405 // Otherwise, the va_list argument must be an l-value because 10406 // it is modified by va_arg. 10407 if (!E->isTypeDependent() && 10408 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 10409 return ExprError(); 10410 } 10411 10412 if (!E->isTypeDependent() && 10413 !Context.hasSameType(VaListType, E->getType())) { 10414 return ExprError(Diag(E->getLocStart(), 10415 diag::err_first_argument_to_va_arg_not_of_type_va_list) 10416 << OrigExpr->getType() << E->getSourceRange()); 10417 } 10418 10419 if (!TInfo->getType()->isDependentType()) { 10420 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 10421 diag::err_second_parameter_to_va_arg_incomplete, 10422 TInfo->getTypeLoc())) 10423 return ExprError(); 10424 10425 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 10426 TInfo->getType(), 10427 diag::err_second_parameter_to_va_arg_abstract, 10428 TInfo->getTypeLoc())) 10429 return ExprError(); 10430 10431 if (!TInfo->getType().isPODType(Context)) { 10432 Diag(TInfo->getTypeLoc().getBeginLoc(), 10433 TInfo->getType()->isObjCLifetimeType() 10434 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 10435 : diag::warn_second_parameter_to_va_arg_not_pod) 10436 << TInfo->getType() 10437 << TInfo->getTypeLoc().getSourceRange(); 10438 } 10439 10440 // Check for va_arg where arguments of the given type will be promoted 10441 // (i.e. this va_arg is guaranteed to have undefined behavior). 10442 QualType PromoteType; 10443 if (TInfo->getType()->isPromotableIntegerType()) { 10444 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 10445 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 10446 PromoteType = QualType(); 10447 } 10448 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 10449 PromoteType = Context.DoubleTy; 10450 if (!PromoteType.isNull()) 10451 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 10452 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 10453 << TInfo->getType() 10454 << PromoteType 10455 << TInfo->getTypeLoc().getSourceRange()); 10456 } 10457 10458 QualType T = TInfo->getType().getNonLValueExprType(Context); 10459 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T)); 10460 } 10461 10462 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 10463 // The type of __null will be int or long, depending on the size of 10464 // pointers on the target. 10465 QualType Ty; 10466 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 10467 if (pw == Context.getTargetInfo().getIntWidth()) 10468 Ty = Context.IntTy; 10469 else if (pw == Context.getTargetInfo().getLongWidth()) 10470 Ty = Context.LongTy; 10471 else if (pw == Context.getTargetInfo().getLongLongWidth()) 10472 Ty = Context.LongLongTy; 10473 else { 10474 llvm_unreachable("I don't know size of pointer!"); 10475 } 10476 10477 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc)); 10478 } 10479 10480 static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType, 10481 Expr *SrcExpr, FixItHint &Hint, 10482 bool &IsNSString) { 10483 if (!SemaRef.getLangOpts().ObjC1) 10484 return; 10485 10486 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 10487 if (!PT) 10488 return; 10489 10490 // Check if the destination is of type 'id'. 10491 if (!PT->isObjCIdType()) { 10492 // Check if the destination is the 'NSString' interface. 10493 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 10494 if (!ID || !ID->getIdentifier()->isStr("NSString")) 10495 return; 10496 IsNSString = true; 10497 } 10498 10499 // Ignore any parens, implicit casts (should only be 10500 // array-to-pointer decays), and not-so-opaque values. The last is 10501 // important for making this trigger for property assignments. 10502 SrcExpr = SrcExpr->IgnoreParenImpCasts(); 10503 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 10504 if (OV->getSourceExpr()) 10505 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 10506 10507 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 10508 if (!SL || !SL->isAscii()) 10509 return; 10510 10511 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@"); 10512 } 10513 10514 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 10515 SourceLocation Loc, 10516 QualType DstType, QualType SrcType, 10517 Expr *SrcExpr, AssignmentAction Action, 10518 bool *Complained) { 10519 if (Complained) 10520 *Complained = false; 10521 10522 // Decode the result (notice that AST's are still created for extensions). 10523 bool CheckInferredResultType = false; 10524 bool isInvalid = false; 10525 unsigned DiagKind = 0; 10526 FixItHint Hint; 10527 ConversionFixItGenerator ConvHints; 10528 bool MayHaveConvFixit = false; 10529 bool MayHaveFunctionDiff = false; 10530 bool IsNSString = false; 10531 10532 switch (ConvTy) { 10533 case Compatible: 10534 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 10535 return false; 10536 10537 case PointerToInt: 10538 DiagKind = diag::ext_typecheck_convert_pointer_int; 10539 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10540 MayHaveConvFixit = true; 10541 break; 10542 case IntToPointer: 10543 DiagKind = diag::ext_typecheck_convert_int_pointer; 10544 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10545 MayHaveConvFixit = true; 10546 break; 10547 case IncompatiblePointer: 10548 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint, IsNSString); 10549 DiagKind = 10550 (Action == AA_Passing_CFAudited ? 10551 diag::err_arc_typecheck_convert_incompatible_pointer : 10552 diag::ext_typecheck_convert_incompatible_pointer); 10553 CheckInferredResultType = DstType->isObjCObjectPointerType() && 10554 SrcType->isObjCObjectPointerType(); 10555 if (Hint.isNull() && !CheckInferredResultType) { 10556 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10557 } 10558 else if (CheckInferredResultType) { 10559 SrcType = SrcType.getUnqualifiedType(); 10560 DstType = DstType.getUnqualifiedType(); 10561 } 10562 else if (IsNSString && !Hint.isNull()) 10563 DiagKind = diag::warn_missing_atsign_prefix; 10564 MayHaveConvFixit = true; 10565 break; 10566 case IncompatiblePointerSign: 10567 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 10568 break; 10569 case FunctionVoidPointer: 10570 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 10571 break; 10572 case IncompatiblePointerDiscardsQualifiers: { 10573 // Perform array-to-pointer decay if necessary. 10574 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 10575 10576 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 10577 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 10578 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 10579 DiagKind = diag::err_typecheck_incompatible_address_space; 10580 break; 10581 10582 10583 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 10584 DiagKind = diag::err_typecheck_incompatible_ownership; 10585 break; 10586 } 10587 10588 llvm_unreachable("unknown error case for discarding qualifiers!"); 10589 // fallthrough 10590 } 10591 case CompatiblePointerDiscardsQualifiers: 10592 // If the qualifiers lost were because we were applying the 10593 // (deprecated) C++ conversion from a string literal to a char* 10594 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 10595 // Ideally, this check would be performed in 10596 // checkPointerTypesForAssignment. However, that would require a 10597 // bit of refactoring (so that the second argument is an 10598 // expression, rather than a type), which should be done as part 10599 // of a larger effort to fix checkPointerTypesForAssignment for 10600 // C++ semantics. 10601 if (getLangOpts().CPlusPlus && 10602 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 10603 return false; 10604 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 10605 break; 10606 case IncompatibleNestedPointerQualifiers: 10607 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 10608 break; 10609 case IntToBlockPointer: 10610 DiagKind = diag::err_int_to_block_pointer; 10611 break; 10612 case IncompatibleBlockPointer: 10613 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 10614 break; 10615 case IncompatibleObjCQualifiedId: 10616 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since 10617 // it can give a more specific diagnostic. 10618 DiagKind = diag::warn_incompatible_qualified_id; 10619 break; 10620 case IncompatibleVectors: 10621 DiagKind = diag::warn_incompatible_vectors; 10622 break; 10623 case IncompatibleObjCWeakRef: 10624 DiagKind = diag::err_arc_weak_unavailable_assign; 10625 break; 10626 case Incompatible: 10627 DiagKind = diag::err_typecheck_convert_incompatible; 10628 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10629 MayHaveConvFixit = true; 10630 isInvalid = true; 10631 MayHaveFunctionDiff = true; 10632 break; 10633 } 10634 10635 QualType FirstType, SecondType; 10636 switch (Action) { 10637 case AA_Assigning: 10638 case AA_Initializing: 10639 // The destination type comes first. 10640 FirstType = DstType; 10641 SecondType = SrcType; 10642 break; 10643 10644 case AA_Returning: 10645 case AA_Passing: 10646 case AA_Passing_CFAudited: 10647 case AA_Converting: 10648 case AA_Sending: 10649 case AA_Casting: 10650 // The source type comes first. 10651 FirstType = SrcType; 10652 SecondType = DstType; 10653 break; 10654 } 10655 10656 PartialDiagnostic FDiag = PDiag(DiagKind); 10657 if (Action == AA_Passing_CFAudited) 10658 FDiag << FirstType << SecondType << SrcExpr->getSourceRange(); 10659 else 10660 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 10661 10662 // If we can fix the conversion, suggest the FixIts. 10663 assert(ConvHints.isNull() || Hint.isNull()); 10664 if (!ConvHints.isNull()) { 10665 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(), 10666 HE = ConvHints.Hints.end(); HI != HE; ++HI) 10667 FDiag << *HI; 10668 } else { 10669 FDiag << Hint; 10670 } 10671 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 10672 10673 if (MayHaveFunctionDiff) 10674 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 10675 10676 Diag(Loc, FDiag); 10677 10678 if (SecondType == Context.OverloadTy) 10679 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 10680 FirstType); 10681 10682 if (CheckInferredResultType) 10683 EmitRelatedResultTypeNote(SrcExpr); 10684 10685 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 10686 EmitRelatedResultTypeNoteForReturn(DstType); 10687 10688 if (Complained) 10689 *Complained = true; 10690 return isInvalid; 10691 } 10692 10693 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 10694 llvm::APSInt *Result) { 10695 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 10696 public: 10697 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 10698 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 10699 } 10700 } Diagnoser; 10701 10702 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 10703 } 10704 10705 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 10706 llvm::APSInt *Result, 10707 unsigned DiagID, 10708 bool AllowFold) { 10709 class IDDiagnoser : public VerifyICEDiagnoser { 10710 unsigned DiagID; 10711 10712 public: 10713 IDDiagnoser(unsigned DiagID) 10714 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 10715 10716 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 10717 S.Diag(Loc, DiagID) << SR; 10718 } 10719 } Diagnoser(DiagID); 10720 10721 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 10722 } 10723 10724 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 10725 SourceRange SR) { 10726 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 10727 } 10728 10729 ExprResult 10730 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 10731 VerifyICEDiagnoser &Diagnoser, 10732 bool AllowFold) { 10733 SourceLocation DiagLoc = E->getLocStart(); 10734 10735 if (getLangOpts().CPlusPlus11) { 10736 // C++11 [expr.const]p5: 10737 // If an expression of literal class type is used in a context where an 10738 // integral constant expression is required, then that class type shall 10739 // have a single non-explicit conversion function to an integral or 10740 // unscoped enumeration type 10741 ExprResult Converted; 10742 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 10743 public: 10744 CXX11ConvertDiagnoser(bool Silent) 10745 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 10746 Silent, true) {} 10747 10748 virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 10749 QualType T) { 10750 return S.Diag(Loc, diag::err_ice_not_integral) << T; 10751 } 10752 10753 virtual SemaDiagnosticBuilder diagnoseIncomplete( 10754 Sema &S, SourceLocation Loc, QualType T) { 10755 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 10756 } 10757 10758 virtual SemaDiagnosticBuilder diagnoseExplicitConv( 10759 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) { 10760 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 10761 } 10762 10763 virtual SemaDiagnosticBuilder noteExplicitConv( 10764 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) { 10765 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 10766 << ConvTy->isEnumeralType() << ConvTy; 10767 } 10768 10769 virtual SemaDiagnosticBuilder diagnoseAmbiguous( 10770 Sema &S, SourceLocation Loc, QualType T) { 10771 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 10772 } 10773 10774 virtual SemaDiagnosticBuilder noteAmbiguous( 10775 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) { 10776 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 10777 << ConvTy->isEnumeralType() << ConvTy; 10778 } 10779 10780 virtual SemaDiagnosticBuilder diagnoseConversion( 10781 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) { 10782 llvm_unreachable("conversion functions are permitted"); 10783 } 10784 } ConvertDiagnoser(Diagnoser.Suppress); 10785 10786 Converted = PerformContextualImplicitConversion(DiagLoc, E, 10787 ConvertDiagnoser); 10788 if (Converted.isInvalid()) 10789 return Converted; 10790 E = Converted.take(); 10791 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 10792 return ExprError(); 10793 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 10794 // An ICE must be of integral or unscoped enumeration type. 10795 if (!Diagnoser.Suppress) 10796 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 10797 return ExprError(); 10798 } 10799 10800 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 10801 // in the non-ICE case. 10802 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 10803 if (Result) 10804 *Result = E->EvaluateKnownConstInt(Context); 10805 return Owned(E); 10806 } 10807 10808 Expr::EvalResult EvalResult; 10809 SmallVector<PartialDiagnosticAt, 8> Notes; 10810 EvalResult.Diag = &Notes; 10811 10812 // Try to evaluate the expression, and produce diagnostics explaining why it's 10813 // not a constant expression as a side-effect. 10814 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 10815 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 10816 10817 // In C++11, we can rely on diagnostics being produced for any expression 10818 // which is not a constant expression. If no diagnostics were produced, then 10819 // this is a constant expression. 10820 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 10821 if (Result) 10822 *Result = EvalResult.Val.getInt(); 10823 return Owned(E); 10824 } 10825 10826 // If our only note is the usual "invalid subexpression" note, just point 10827 // the caret at its location rather than producing an essentially 10828 // redundant note. 10829 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 10830 diag::note_invalid_subexpr_in_const_expr) { 10831 DiagLoc = Notes[0].first; 10832 Notes.clear(); 10833 } 10834 10835 if (!Folded || !AllowFold) { 10836 if (!Diagnoser.Suppress) { 10837 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 10838 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 10839 Diag(Notes[I].first, Notes[I].second); 10840 } 10841 10842 return ExprError(); 10843 } 10844 10845 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 10846 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 10847 Diag(Notes[I].first, Notes[I].second); 10848 10849 if (Result) 10850 *Result = EvalResult.Val.getInt(); 10851 return Owned(E); 10852 } 10853 10854 namespace { 10855 // Handle the case where we conclude a expression which we speculatively 10856 // considered to be unevaluated is actually evaluated. 10857 class TransformToPE : public TreeTransform<TransformToPE> { 10858 typedef TreeTransform<TransformToPE> BaseTransform; 10859 10860 public: 10861 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 10862 10863 // Make sure we redo semantic analysis 10864 bool AlwaysRebuild() { return true; } 10865 10866 // Make sure we handle LabelStmts correctly. 10867 // FIXME: This does the right thing, but maybe we need a more general 10868 // fix to TreeTransform? 10869 StmtResult TransformLabelStmt(LabelStmt *S) { 10870 S->getDecl()->setStmt(0); 10871 return BaseTransform::TransformLabelStmt(S); 10872 } 10873 10874 // We need to special-case DeclRefExprs referring to FieldDecls which 10875 // are not part of a member pointer formation; normal TreeTransforming 10876 // doesn't catch this case because of the way we represent them in the AST. 10877 // FIXME: This is a bit ugly; is it really the best way to handle this 10878 // case? 10879 // 10880 // Error on DeclRefExprs referring to FieldDecls. 10881 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 10882 if (isa<FieldDecl>(E->getDecl()) && 10883 !SemaRef.isUnevaluatedContext()) 10884 return SemaRef.Diag(E->getLocation(), 10885 diag::err_invalid_non_static_member_use) 10886 << E->getDecl() << E->getSourceRange(); 10887 10888 return BaseTransform::TransformDeclRefExpr(E); 10889 } 10890 10891 // Exception: filter out member pointer formation 10892 ExprResult TransformUnaryOperator(UnaryOperator *E) { 10893 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 10894 return E; 10895 10896 return BaseTransform::TransformUnaryOperator(E); 10897 } 10898 10899 ExprResult TransformLambdaExpr(LambdaExpr *E) { 10900 // Lambdas never need to be transformed. 10901 return E; 10902 } 10903 }; 10904 } 10905 10906 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 10907 assert(isUnevaluatedContext() && 10908 "Should only transform unevaluated expressions"); 10909 ExprEvalContexts.back().Context = 10910 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 10911 if (isUnevaluatedContext()) 10912 return E; 10913 return TransformToPE(*this).TransformExpr(E); 10914 } 10915 10916 void 10917 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 10918 Decl *LambdaContextDecl, 10919 bool IsDecltype) { 10920 ExprEvalContexts.push_back( 10921 ExpressionEvaluationContextRecord(NewContext, 10922 ExprCleanupObjects.size(), 10923 ExprNeedsCleanups, 10924 LambdaContextDecl, 10925 IsDecltype)); 10926 ExprNeedsCleanups = false; 10927 if (!MaybeODRUseExprs.empty()) 10928 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 10929 } 10930 10931 void 10932 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 10933 ReuseLambdaContextDecl_t, 10934 bool IsDecltype) { 10935 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 10936 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 10937 } 10938 10939 void Sema::PopExpressionEvaluationContext() { 10940 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 10941 10942 if (!Rec.Lambdas.empty()) { 10943 if (Rec.isUnevaluated()) { 10944 // C++11 [expr.prim.lambda]p2: 10945 // A lambda-expression shall not appear in an unevaluated operand 10946 // (Clause 5). 10947 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) 10948 Diag(Rec.Lambdas[I]->getLocStart(), 10949 diag::err_lambda_unevaluated_operand); 10950 } else { 10951 // Mark the capture expressions odr-used. This was deferred 10952 // during lambda expression creation. 10953 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) { 10954 LambdaExpr *Lambda = Rec.Lambdas[I]; 10955 for (LambdaExpr::capture_init_iterator 10956 C = Lambda->capture_init_begin(), 10957 CEnd = Lambda->capture_init_end(); 10958 C != CEnd; ++C) { 10959 MarkDeclarationsReferencedInExpr(*C); 10960 } 10961 } 10962 } 10963 } 10964 10965 // When are coming out of an unevaluated context, clear out any 10966 // temporaries that we may have created as part of the evaluation of 10967 // the expression in that context: they aren't relevant because they 10968 // will never be constructed. 10969 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 10970 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 10971 ExprCleanupObjects.end()); 10972 ExprNeedsCleanups = Rec.ParentNeedsCleanups; 10973 CleanupVarDeclMarking(); 10974 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 10975 // Otherwise, merge the contexts together. 10976 } else { 10977 ExprNeedsCleanups |= Rec.ParentNeedsCleanups; 10978 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 10979 Rec.SavedMaybeODRUseExprs.end()); 10980 } 10981 10982 // Pop the current expression evaluation context off the stack. 10983 ExprEvalContexts.pop_back(); 10984 } 10985 10986 void Sema::DiscardCleanupsInEvaluationContext() { 10987 ExprCleanupObjects.erase( 10988 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 10989 ExprCleanupObjects.end()); 10990 ExprNeedsCleanups = false; 10991 MaybeODRUseExprs.clear(); 10992 } 10993 10994 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 10995 if (!E->getType()->isVariablyModifiedType()) 10996 return E; 10997 return TransformToPotentiallyEvaluated(E); 10998 } 10999 11000 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 11001 // Do not mark anything as "used" within a dependent context; wait for 11002 // an instantiation. 11003 if (SemaRef.CurContext->isDependentContext()) 11004 return false; 11005 11006 switch (SemaRef.ExprEvalContexts.back().Context) { 11007 case Sema::Unevaluated: 11008 case Sema::UnevaluatedAbstract: 11009 // We are in an expression that is not potentially evaluated; do nothing. 11010 // (Depending on how you read the standard, we actually do need to do 11011 // something here for null pointer constants, but the standard's 11012 // definition of a null pointer constant is completely crazy.) 11013 return false; 11014 11015 case Sema::ConstantEvaluated: 11016 case Sema::PotentiallyEvaluated: 11017 // We are in a potentially evaluated expression (or a constant-expression 11018 // in C++03); we need to do implicit template instantiation, implicitly 11019 // define class members, and mark most declarations as used. 11020 return true; 11021 11022 case Sema::PotentiallyEvaluatedIfUsed: 11023 // Referenced declarations will only be used if the construct in the 11024 // containing expression is used. 11025 return false; 11026 } 11027 llvm_unreachable("Invalid context"); 11028 } 11029 11030 /// \brief Mark a function referenced, and check whether it is odr-used 11031 /// (C++ [basic.def.odr]p2, C99 6.9p3) 11032 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) { 11033 assert(Func && "No function?"); 11034 11035 Func->setReferenced(); 11036 11037 // C++11 [basic.def.odr]p3: 11038 // A function whose name appears as a potentially-evaluated expression is 11039 // odr-used if it is the unique lookup result or the selected member of a 11040 // set of overloaded functions [...]. 11041 // 11042 // We (incorrectly) mark overload resolution as an unevaluated context, so we 11043 // can just check that here. Skip the rest of this function if we've already 11044 // marked the function as used. 11045 if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) { 11046 // C++11 [temp.inst]p3: 11047 // Unless a function template specialization has been explicitly 11048 // instantiated or explicitly specialized, the function template 11049 // specialization is implicitly instantiated when the specialization is 11050 // referenced in a context that requires a function definition to exist. 11051 // 11052 // We consider constexpr function templates to be referenced in a context 11053 // that requires a definition to exist whenever they are referenced. 11054 // 11055 // FIXME: This instantiates constexpr functions too frequently. If this is 11056 // really an unevaluated context (and we're not just in the definition of a 11057 // function template or overload resolution or other cases which we 11058 // incorrectly consider to be unevaluated contexts), and we're not in a 11059 // subexpression which we actually need to evaluate (for instance, a 11060 // template argument, array bound or an expression in a braced-init-list), 11061 // we are not permitted to instantiate this constexpr function definition. 11062 // 11063 // FIXME: This also implicitly defines special members too frequently. They 11064 // are only supposed to be implicitly defined if they are odr-used, but they 11065 // are not odr-used from constant expressions in unevaluated contexts. 11066 // However, they cannot be referenced if they are deleted, and they are 11067 // deleted whenever the implicit definition of the special member would 11068 // fail. 11069 if (!(Func->isConstexpr() && !getLangOpts().DelayedTemplateParsing) || 11070 Func->getBody()) 11071 return; 11072 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 11073 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided())) 11074 return; 11075 } 11076 11077 // Note that this declaration has been used. 11078 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 11079 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 11080 if (Constructor->isDefaultConstructor()) { 11081 if (Constructor->isTrivial()) 11082 return; 11083 if (!Constructor->isUsed(false)) 11084 DefineImplicitDefaultConstructor(Loc, Constructor); 11085 } else if (Constructor->isCopyConstructor()) { 11086 if (!Constructor->isUsed(false)) 11087 DefineImplicitCopyConstructor(Loc, Constructor); 11088 } else if (Constructor->isMoveConstructor()) { 11089 if (!Constructor->isUsed(false)) 11090 DefineImplicitMoveConstructor(Loc, Constructor); 11091 } 11092 } else if (Constructor->getInheritedConstructor()) { 11093 if (!Constructor->isUsed(false)) 11094 DefineInheritingConstructor(Loc, Constructor); 11095 } 11096 11097 MarkVTableUsed(Loc, Constructor->getParent()); 11098 } else if (CXXDestructorDecl *Destructor = 11099 dyn_cast<CXXDestructorDecl>(Func)) { 11100 if (Destructor->isDefaulted() && !Destructor->isDeleted() && 11101 !Destructor->isUsed(false)) 11102 DefineImplicitDestructor(Loc, Destructor); 11103 if (Destructor->isVirtual()) 11104 MarkVTableUsed(Loc, Destructor->getParent()); 11105 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 11106 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() && 11107 MethodDecl->isOverloadedOperator() && 11108 MethodDecl->getOverloadedOperator() == OO_Equal) { 11109 if (!MethodDecl->isUsed(false)) { 11110 if (MethodDecl->isCopyAssignmentOperator()) 11111 DefineImplicitCopyAssignment(Loc, MethodDecl); 11112 else 11113 DefineImplicitMoveAssignment(Loc, MethodDecl); 11114 } 11115 } else if (isa<CXXConversionDecl>(MethodDecl) && 11116 MethodDecl->getParent()->isLambda()) { 11117 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl); 11118 if (Conversion->isLambdaToBlockPointerConversion()) 11119 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 11120 else 11121 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 11122 } else if (MethodDecl->isVirtual()) 11123 MarkVTableUsed(Loc, MethodDecl->getParent()); 11124 } 11125 11126 // Recursive functions should be marked when used from another function. 11127 // FIXME: Is this really right? 11128 if (CurContext == Func) return; 11129 11130 // Resolve the exception specification for any function which is 11131 // used: CodeGen will need it. 11132 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 11133 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 11134 ResolveExceptionSpec(Loc, FPT); 11135 11136 // Implicit instantiation of function templates and member functions of 11137 // class templates. 11138 if (Func->isImplicitlyInstantiable()) { 11139 bool AlreadyInstantiated = false; 11140 SourceLocation PointOfInstantiation = Loc; 11141 if (FunctionTemplateSpecializationInfo *SpecInfo 11142 = Func->getTemplateSpecializationInfo()) { 11143 if (SpecInfo->getPointOfInstantiation().isInvalid()) 11144 SpecInfo->setPointOfInstantiation(Loc); 11145 else if (SpecInfo->getTemplateSpecializationKind() 11146 == TSK_ImplicitInstantiation) { 11147 AlreadyInstantiated = true; 11148 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 11149 } 11150 } else if (MemberSpecializationInfo *MSInfo 11151 = Func->getMemberSpecializationInfo()) { 11152 if (MSInfo->getPointOfInstantiation().isInvalid()) 11153 MSInfo->setPointOfInstantiation(Loc); 11154 else if (MSInfo->getTemplateSpecializationKind() 11155 == TSK_ImplicitInstantiation) { 11156 AlreadyInstantiated = true; 11157 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 11158 } 11159 } 11160 11161 if (!AlreadyInstantiated || 11162 (Func->isConstexpr() && !getLangOpts().DelayedTemplateParsing)) { 11163 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 11164 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 11165 ActiveTemplateInstantiations.size()) 11166 PendingLocalImplicitInstantiations.push_back( 11167 std::make_pair(Func, PointOfInstantiation)); 11168 else if (Func->isConstexpr() && !getLangOpts().DelayedTemplateParsing) 11169 // Do not defer instantiations of constexpr functions, to avoid the 11170 // expression evaluator needing to call back into Sema if it sees a 11171 // call to such a function. 11172 InstantiateFunctionDefinition(PointOfInstantiation, Func); 11173 else { 11174 PendingInstantiations.push_back(std::make_pair(Func, 11175 PointOfInstantiation)); 11176 // Notify the consumer that a function was implicitly instantiated. 11177 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 11178 } 11179 } 11180 } else { 11181 // Walk redefinitions, as some of them may be instantiable. 11182 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()), 11183 e(Func->redecls_end()); i != e; ++i) { 11184 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 11185 MarkFunctionReferenced(Loc, *i); 11186 } 11187 } 11188 11189 // Keep track of used but undefined functions. 11190 if (!Func->isDefined()) { 11191 if (mightHaveNonExternalLinkage(Func)) 11192 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 11193 else if (Func->getMostRecentDecl()->isInlined() && 11194 (LangOpts.CPlusPlus || !LangOpts.GNUInline) && 11195 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 11196 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 11197 } 11198 11199 // Normally the must current decl is marked used while processing the use and 11200 // any subsequent decls are marked used by decl merging. This fails with 11201 // template instantiation since marking can happen at the end of the file 11202 // and, because of the two phase lookup, this function is called with at 11203 // decl in the middle of a decl chain. We loop to maintain the invariant 11204 // that once a decl is used, all decls after it are also used. 11205 for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) { 11206 F->markUsed(Context); 11207 if (F == Func) 11208 break; 11209 } 11210 } 11211 11212 static void 11213 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 11214 VarDecl *var, DeclContext *DC) { 11215 DeclContext *VarDC = var->getDeclContext(); 11216 11217 // If the parameter still belongs to the translation unit, then 11218 // we're actually just using one parameter in the declaration of 11219 // the next. 11220 if (isa<ParmVarDecl>(var) && 11221 isa<TranslationUnitDecl>(VarDC)) 11222 return; 11223 11224 // For C code, don't diagnose about capture if we're not actually in code 11225 // right now; it's impossible to write a non-constant expression outside of 11226 // function context, so we'll get other (more useful) diagnostics later. 11227 // 11228 // For C++, things get a bit more nasty... it would be nice to suppress this 11229 // diagnostic for certain cases like using a local variable in an array bound 11230 // for a member of a local class, but the correct predicate is not obvious. 11231 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 11232 return; 11233 11234 if (isa<CXXMethodDecl>(VarDC) && 11235 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 11236 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda) 11237 << var->getIdentifier(); 11238 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) { 11239 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 11240 << var->getIdentifier() << fn->getDeclName(); 11241 } else if (isa<BlockDecl>(VarDC)) { 11242 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block) 11243 << var->getIdentifier(); 11244 } else { 11245 // FIXME: Is there any other context where a local variable can be 11246 // declared? 11247 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context) 11248 << var->getIdentifier(); 11249 } 11250 11251 S.Diag(var->getLocation(), diag::note_local_variable_declared_here) 11252 << var->getIdentifier(); 11253 11254 // FIXME: Add additional diagnostic info about class etc. which prevents 11255 // capture. 11256 } 11257 11258 11259 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 11260 bool &SubCapturesAreNested, 11261 QualType &CaptureType, 11262 QualType &DeclRefType) { 11263 // Check whether we've already captured it. 11264 if (CSI->CaptureMap.count(Var)) { 11265 // If we found a capture, any subcaptures are nested. 11266 SubCapturesAreNested = true; 11267 11268 // Retrieve the capture type for this variable. 11269 CaptureType = CSI->getCapture(Var).getCaptureType(); 11270 11271 // Compute the type of an expression that refers to this variable. 11272 DeclRefType = CaptureType.getNonReferenceType(); 11273 11274 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 11275 if (Cap.isCopyCapture() && 11276 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable)) 11277 DeclRefType.addConst(); 11278 return true; 11279 } 11280 return false; 11281 } 11282 11283 // Only block literals, captured statements, and lambda expressions can 11284 // capture; other scopes don't work. 11285 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 11286 SourceLocation Loc, 11287 const bool Diagnose, Sema &S) { 11288 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) 11289 return DC->getParent(); 11290 else if (isa<CXXMethodDecl>(DC) && 11291 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call && 11292 cast<CXXRecordDecl>(DC->getParent())->isLambda()) 11293 return DC->getParent()->getParent(); 11294 else { 11295 if (Diagnose) 11296 diagnoseUncapturableValueReference(S, Loc, Var, DC); 11297 } 11298 return 0; 11299 } 11300 11301 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 11302 // certain types of variables (unnamed, variably modified types etc.) 11303 // so check for eligibility. 11304 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 11305 SourceLocation Loc, 11306 const bool Diagnose, Sema &S) { 11307 11308 bool IsBlock = isa<BlockScopeInfo>(CSI); 11309 bool IsLambda = isa<LambdaScopeInfo>(CSI); 11310 11311 // Lambdas are not allowed to capture unnamed variables 11312 // (e.g. anonymous unions). 11313 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 11314 // assuming that's the intent. 11315 if (IsLambda && !Var->getDeclName()) { 11316 if (Diagnose) { 11317 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 11318 S.Diag(Var->getLocation(), diag::note_declared_at); 11319 } 11320 return false; 11321 } 11322 11323 // Prohibit variably-modified types; they're difficult to deal with. 11324 if (Var->getType()->isVariablyModifiedType()) { 11325 if (Diagnose) { 11326 if (IsBlock) 11327 S.Diag(Loc, diag::err_ref_vm_type); 11328 else 11329 S.Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName(); 11330 S.Diag(Var->getLocation(), diag::note_previous_decl) 11331 << Var->getDeclName(); 11332 } 11333 return false; 11334 } 11335 // Prohibit structs with flexible array members too. 11336 // We cannot capture what is in the tail end of the struct. 11337 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 11338 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 11339 if (Diagnose) { 11340 if (IsBlock) 11341 S.Diag(Loc, diag::err_ref_flexarray_type); 11342 else 11343 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 11344 << Var->getDeclName(); 11345 S.Diag(Var->getLocation(), diag::note_previous_decl) 11346 << Var->getDeclName(); 11347 } 11348 return false; 11349 } 11350 } 11351 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 11352 // Lambdas and captured statements are not allowed to capture __block 11353 // variables; they don't support the expected semantics. 11354 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 11355 if (Diagnose) { 11356 S.Diag(Loc, diag::err_capture_block_variable) 11357 << Var->getDeclName() << !IsLambda; 11358 S.Diag(Var->getLocation(), diag::note_previous_decl) 11359 << Var->getDeclName(); 11360 } 11361 return false; 11362 } 11363 11364 return true; 11365 } 11366 11367 // Returns true if the capture by block was successful. 11368 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 11369 SourceLocation Loc, 11370 const bool BuildAndDiagnose, 11371 QualType &CaptureType, 11372 QualType &DeclRefType, 11373 const bool Nested, 11374 Sema &S) { 11375 Expr *CopyExpr = 0; 11376 bool ByRef = false; 11377 11378 // Blocks are not allowed to capture arrays. 11379 if (CaptureType->isArrayType()) { 11380 if (BuildAndDiagnose) { 11381 S.Diag(Loc, diag::err_ref_array_type); 11382 S.Diag(Var->getLocation(), diag::note_previous_decl) 11383 << Var->getDeclName(); 11384 } 11385 return false; 11386 } 11387 11388 // Forbid the block-capture of autoreleasing variables. 11389 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 11390 if (BuildAndDiagnose) { 11391 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 11392 << /*block*/ 0; 11393 S.Diag(Var->getLocation(), diag::note_previous_decl) 11394 << Var->getDeclName(); 11395 } 11396 return false; 11397 } 11398 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 11399 if (HasBlocksAttr || CaptureType->isReferenceType()) { 11400 // Block capture by reference does not change the capture or 11401 // declaration reference types. 11402 ByRef = true; 11403 } else { 11404 // Block capture by copy introduces 'const'. 11405 CaptureType = CaptureType.getNonReferenceType().withConst(); 11406 DeclRefType = CaptureType; 11407 11408 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 11409 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 11410 // The capture logic needs the destructor, so make sure we mark it. 11411 // Usually this is unnecessary because most local variables have 11412 // their destructors marked at declaration time, but parameters are 11413 // an exception because it's technically only the call site that 11414 // actually requires the destructor. 11415 if (isa<ParmVarDecl>(Var)) 11416 S.FinalizeVarWithDestructor(Var, Record); 11417 11418 // Enter a new evaluation context to insulate the copy 11419 // full-expression. 11420 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated); 11421 11422 // According to the blocks spec, the capture of a variable from 11423 // the stack requires a const copy constructor. This is not true 11424 // of the copy/move done to move a __block variable to the heap. 11425 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 11426 DeclRefType.withConst(), 11427 VK_LValue, Loc); 11428 11429 ExprResult Result 11430 = S.PerformCopyInitialization( 11431 InitializedEntity::InitializeBlock(Var->getLocation(), 11432 CaptureType, false), 11433 Loc, S.Owned(DeclRef)); 11434 11435 // Build a full-expression copy expression if initialization 11436 // succeeded and used a non-trivial constructor. Recover from 11437 // errors by pretending that the copy isn't necessary. 11438 if (!Result.isInvalid() && 11439 !cast<CXXConstructExpr>(Result.get())->getConstructor() 11440 ->isTrivial()) { 11441 Result = S.MaybeCreateExprWithCleanups(Result); 11442 CopyExpr = Result.take(); 11443 } 11444 } 11445 } 11446 } 11447 11448 // Actually capture the variable. 11449 if (BuildAndDiagnose) 11450 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 11451 SourceLocation(), CaptureType, CopyExpr); 11452 11453 return true; 11454 11455 } 11456 11457 11458 /// \brief Capture the given variable in the captured region. 11459 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 11460 VarDecl *Var, 11461 SourceLocation Loc, 11462 const bool BuildAndDiagnose, 11463 QualType &CaptureType, 11464 QualType &DeclRefType, 11465 const bool RefersToEnclosingLocal, 11466 Sema &S) { 11467 11468 // By default, capture variables by reference. 11469 bool ByRef = true; 11470 // Using an LValue reference type is consistent with Lambdas (see below). 11471 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 11472 Expr *CopyExpr = 0; 11473 if (BuildAndDiagnose) { 11474 // The current implementation assumes that all variables are captured 11475 // by references. Since there is no capture by copy, no expression evaluation 11476 // will be needed. 11477 // 11478 RecordDecl *RD = RSI->TheRecordDecl; 11479 11480 FieldDecl *Field 11481 = FieldDecl::Create(S.Context, RD, Loc, Loc, 0, CaptureType, 11482 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 11483 0, false, ICIS_NoInit); 11484 Field->setImplicit(true); 11485 Field->setAccess(AS_private); 11486 RD->addDecl(Field); 11487 11488 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 11489 DeclRefType, VK_LValue, Loc); 11490 Var->setReferenced(true); 11491 Var->markUsed(S.Context); 11492 } 11493 11494 // Actually capture the variable. 11495 if (BuildAndDiagnose) 11496 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToEnclosingLocal, Loc, 11497 SourceLocation(), CaptureType, CopyExpr); 11498 11499 11500 return true; 11501 } 11502 11503 /// \brief Create a field within the lambda class for the variable 11504 /// being captured. Handle Array captures. 11505 static ExprResult addAsFieldToClosureType(Sema &S, 11506 LambdaScopeInfo *LSI, 11507 VarDecl *Var, QualType FieldType, 11508 QualType DeclRefType, 11509 SourceLocation Loc, 11510 bool RefersToEnclosingLocal) { 11511 CXXRecordDecl *Lambda = LSI->Lambda; 11512 11513 // Build the non-static data member. 11514 FieldDecl *Field 11515 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType, 11516 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 11517 0, false, ICIS_NoInit); 11518 Field->setImplicit(true); 11519 Field->setAccess(AS_private); 11520 Lambda->addDecl(Field); 11521 11522 // C++11 [expr.prim.lambda]p21: 11523 // When the lambda-expression is evaluated, the entities that 11524 // are captured by copy are used to direct-initialize each 11525 // corresponding non-static data member of the resulting closure 11526 // object. (For array members, the array elements are 11527 // direct-initialized in increasing subscript order.) These 11528 // initializations are performed in the (unspecified) order in 11529 // which the non-static data members are declared. 11530 11531 // Introduce a new evaluation context for the initialization, so 11532 // that temporaries introduced as part of the capture are retained 11533 // to be re-"exported" from the lambda expression itself. 11534 EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated); 11535 11536 // C++ [expr.prim.labda]p12: 11537 // An entity captured by a lambda-expression is odr-used (3.2) in 11538 // the scope containing the lambda-expression. 11539 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 11540 DeclRefType, VK_LValue, Loc); 11541 Var->setReferenced(true); 11542 Var->markUsed(S.Context); 11543 11544 // When the field has array type, create index variables for each 11545 // dimension of the array. We use these index variables to subscript 11546 // the source array, and other clients (e.g., CodeGen) will perform 11547 // the necessary iteration with these index variables. 11548 SmallVector<VarDecl *, 4> IndexVariables; 11549 QualType BaseType = FieldType; 11550 QualType SizeType = S.Context.getSizeType(); 11551 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size()); 11552 while (const ConstantArrayType *Array 11553 = S.Context.getAsConstantArrayType(BaseType)) { 11554 // Create the iteration variable for this array index. 11555 IdentifierInfo *IterationVarName = 0; 11556 { 11557 SmallString<8> Str; 11558 llvm::raw_svector_ostream OS(Str); 11559 OS << "__i" << IndexVariables.size(); 11560 IterationVarName = &S.Context.Idents.get(OS.str()); 11561 } 11562 VarDecl *IterationVar 11563 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 11564 IterationVarName, SizeType, 11565 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 11566 SC_None); 11567 IndexVariables.push_back(IterationVar); 11568 LSI->ArrayIndexVars.push_back(IterationVar); 11569 11570 // Create a reference to the iteration variable. 11571 ExprResult IterationVarRef 11572 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 11573 assert(!IterationVarRef.isInvalid() && 11574 "Reference to invented variable cannot fail!"); 11575 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take()); 11576 assert(!IterationVarRef.isInvalid() && 11577 "Conversion of invented variable cannot fail!"); 11578 11579 // Subscript the array with this iteration variable. 11580 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr( 11581 Ref, Loc, IterationVarRef.take(), Loc); 11582 if (Subscript.isInvalid()) { 11583 S.CleanupVarDeclMarking(); 11584 S.DiscardCleanupsInEvaluationContext(); 11585 return ExprError(); 11586 } 11587 11588 Ref = Subscript.take(); 11589 BaseType = Array->getElementType(); 11590 } 11591 11592 // Construct the entity that we will be initializing. For an array, this 11593 // will be first element in the array, which may require several levels 11594 // of array-subscript entities. 11595 SmallVector<InitializedEntity, 4> Entities; 11596 Entities.reserve(1 + IndexVariables.size()); 11597 Entities.push_back( 11598 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc)); 11599 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 11600 Entities.push_back(InitializedEntity::InitializeElement(S.Context, 11601 0, 11602 Entities.back())); 11603 11604 InitializationKind InitKind 11605 = InitializationKind::CreateDirect(Loc, Loc, Loc); 11606 InitializationSequence Init(S, Entities.back(), InitKind, Ref); 11607 ExprResult Result(true); 11608 if (!Init.Diagnose(S, Entities.back(), InitKind, Ref)) 11609 Result = Init.Perform(S, Entities.back(), InitKind, Ref); 11610 11611 // If this initialization requires any cleanups (e.g., due to a 11612 // default argument to a copy constructor), note that for the 11613 // lambda. 11614 if (S.ExprNeedsCleanups) 11615 LSI->ExprNeedsCleanups = true; 11616 11617 // Exit the expression evaluation context used for the capture. 11618 S.CleanupVarDeclMarking(); 11619 S.DiscardCleanupsInEvaluationContext(); 11620 return Result; 11621 } 11622 11623 11624 11625 /// \brief Capture the given variable in the lambda. 11626 static bool captureInLambda(LambdaScopeInfo *LSI, 11627 VarDecl *Var, 11628 SourceLocation Loc, 11629 const bool BuildAndDiagnose, 11630 QualType &CaptureType, 11631 QualType &DeclRefType, 11632 const bool RefersToEnclosingLocal, 11633 const Sema::TryCaptureKind Kind, 11634 SourceLocation EllipsisLoc, 11635 const bool IsTopScope, 11636 Sema &S) { 11637 11638 // Determine whether we are capturing by reference or by value. 11639 bool ByRef = false; 11640 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 11641 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 11642 } else { 11643 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 11644 } 11645 11646 // Compute the type of the field that will capture this variable. 11647 if (ByRef) { 11648 // C++11 [expr.prim.lambda]p15: 11649 // An entity is captured by reference if it is implicitly or 11650 // explicitly captured but not captured by copy. It is 11651 // unspecified whether additional unnamed non-static data 11652 // members are declared in the closure type for entities 11653 // captured by reference. 11654 // 11655 // FIXME: It is not clear whether we want to build an lvalue reference 11656 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 11657 // to do the former, while EDG does the latter. Core issue 1249 will 11658 // clarify, but for now we follow GCC because it's a more permissive and 11659 // easily defensible position. 11660 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 11661 } else { 11662 // C++11 [expr.prim.lambda]p14: 11663 // For each entity captured by copy, an unnamed non-static 11664 // data member is declared in the closure type. The 11665 // declaration order of these members is unspecified. The type 11666 // of such a data member is the type of the corresponding 11667 // captured entity if the entity is not a reference to an 11668 // object, or the referenced type otherwise. [Note: If the 11669 // captured entity is a reference to a function, the 11670 // corresponding data member is also a reference to a 11671 // function. - end note ] 11672 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 11673 if (!RefType->getPointeeType()->isFunctionType()) 11674 CaptureType = RefType->getPointeeType(); 11675 } 11676 11677 // Forbid the lambda copy-capture of autoreleasing variables. 11678 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 11679 if (BuildAndDiagnose) { 11680 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 11681 S.Diag(Var->getLocation(), diag::note_previous_decl) 11682 << Var->getDeclName(); 11683 } 11684 return false; 11685 } 11686 } 11687 11688 // Capture this variable in the lambda. 11689 Expr *CopyExpr = 0; 11690 if (BuildAndDiagnose) { 11691 ExprResult Result = addAsFieldToClosureType(S, LSI, Var, 11692 CaptureType, DeclRefType, Loc, 11693 RefersToEnclosingLocal); 11694 if (!Result.isInvalid()) 11695 CopyExpr = Result.take(); 11696 } 11697 11698 // Compute the type of a reference to this captured variable. 11699 if (ByRef) 11700 DeclRefType = CaptureType.getNonReferenceType(); 11701 else { 11702 // C++ [expr.prim.lambda]p5: 11703 // The closure type for a lambda-expression has a public inline 11704 // function call operator [...]. This function call operator is 11705 // declared const (9.3.1) if and only if the lambda-expression’s 11706 // parameter-declaration-clause is not followed by mutable. 11707 DeclRefType = CaptureType.getNonReferenceType(); 11708 if (!LSI->Mutable && !CaptureType->isReferenceType()) 11709 DeclRefType.addConst(); 11710 } 11711 11712 // Add the capture. 11713 if (BuildAndDiagnose) 11714 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToEnclosingLocal, 11715 Loc, EllipsisLoc, CaptureType, CopyExpr); 11716 11717 return true; 11718 } 11719 11720 11721 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation ExprLoc, 11722 TryCaptureKind Kind, SourceLocation EllipsisLoc, 11723 bool BuildAndDiagnose, 11724 QualType &CaptureType, 11725 QualType &DeclRefType) { 11726 bool Nested = false; 11727 11728 DeclContext *DC = CurContext; 11729 const unsigned MaxFunctionScopesIndex = FunctionScopes.size() - 1; 11730 11731 // If the variable is declared in the current context (and is not an 11732 // init-capture), there is no need to capture it. 11733 if (!Var->isInitCapture() && Var->getDeclContext() == DC) return true; 11734 if (!Var->hasLocalStorage()) return true; 11735 11736 // Walk up the stack to determine whether we can capture the variable, 11737 // performing the "simple" checks that don't depend on type. We stop when 11738 // we've either hit the declared scope of the variable or find an existing 11739 // capture of that variable. We start from the innermost capturing-entity 11740 // (the DC) and ensure that all intervening capturing-entities 11741 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 11742 // declcontext can either capture the variable or have already captured 11743 // the variable. 11744 CaptureType = Var->getType(); 11745 DeclRefType = CaptureType.getNonReferenceType(); 11746 bool Explicit = (Kind != TryCapture_Implicit); 11747 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 11748 do { 11749 // Only block literals, captured statements, and lambda expressions can 11750 // capture; other scopes don't work. 11751 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 11752 ExprLoc, 11753 BuildAndDiagnose, 11754 *this); 11755 if (!ParentDC) return true; 11756 11757 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 11758 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 11759 11760 11761 // Check whether we've already captured it. 11762 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 11763 DeclRefType)) 11764 break; 11765 11766 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 11767 // certain types of variables (unnamed, variably modified types etc.) 11768 // so check for eligibility. 11769 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 11770 return true; 11771 11772 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 11773 // No capture-default, and this is not an explicit capture 11774 // so cannot capture this variable. 11775 if (BuildAndDiagnose) { 11776 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 11777 Diag(Var->getLocation(), diag::note_previous_decl) 11778 << Var->getDeclName(); 11779 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 11780 diag::note_lambda_decl); 11781 } 11782 return true; 11783 } 11784 11785 FunctionScopesIndex--; 11786 DC = ParentDC; 11787 Explicit = false; 11788 } while (!Var->getDeclContext()->Equals(DC)); 11789 11790 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 11791 // computing the type of the capture at each step, checking type-specific 11792 // requirements, and adding captures if requested. 11793 // If the variable had already been captured previously, we start capturing 11794 // at the lambda nested within that one. 11795 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 11796 ++I) { 11797 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 11798 11799 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 11800 if (!captureInBlock(BSI, Var, ExprLoc, 11801 BuildAndDiagnose, CaptureType, 11802 DeclRefType, Nested, *this)) 11803 return true; 11804 Nested = true; 11805 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 11806 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 11807 BuildAndDiagnose, CaptureType, 11808 DeclRefType, Nested, *this)) 11809 return true; 11810 Nested = true; 11811 } else { 11812 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 11813 if (!captureInLambda(LSI, Var, ExprLoc, 11814 BuildAndDiagnose, CaptureType, 11815 DeclRefType, Nested, Kind, EllipsisLoc, 11816 /*IsTopScope*/I == N - 1, *this)) 11817 return true; 11818 Nested = true; 11819 } 11820 } 11821 return false; 11822 } 11823 11824 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 11825 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 11826 QualType CaptureType; 11827 QualType DeclRefType; 11828 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 11829 /*BuildAndDiagnose=*/true, CaptureType, 11830 DeclRefType); 11831 } 11832 11833 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 11834 QualType CaptureType; 11835 QualType DeclRefType; 11836 11837 // Determine whether we can capture this variable. 11838 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 11839 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType)) 11840 return QualType(); 11841 11842 return DeclRefType; 11843 } 11844 11845 static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var, 11846 SourceLocation Loc) { 11847 // Keep track of used but undefined variables. 11848 // FIXME: We shouldn't suppress this warning for static data members. 11849 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 11850 !Var->isExternallyVisible() && 11851 !(Var->isStaticDataMember() && Var->hasInit())) { 11852 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 11853 if (old.isInvalid()) old = Loc; 11854 } 11855 11856 SemaRef.tryCaptureVariable(Var, Loc); 11857 11858 Var->markUsed(SemaRef.Context); 11859 } 11860 11861 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 11862 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 11863 // an object that satisfies the requirements for appearing in a 11864 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 11865 // is immediately applied." This function handles the lvalue-to-rvalue 11866 // conversion part. 11867 MaybeODRUseExprs.erase(E->IgnoreParens()); 11868 } 11869 11870 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 11871 if (!Res.isUsable()) 11872 return Res; 11873 11874 // If a constant-expression is a reference to a variable where we delay 11875 // deciding whether it is an odr-use, just assume we will apply the 11876 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 11877 // (a non-type template argument), we have special handling anyway. 11878 UpdateMarkingForLValueToRValue(Res.get()); 11879 return Res; 11880 } 11881 11882 void Sema::CleanupVarDeclMarking() { 11883 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(), 11884 e = MaybeODRUseExprs.end(); 11885 i != e; ++i) { 11886 VarDecl *Var; 11887 SourceLocation Loc; 11888 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) { 11889 Var = cast<VarDecl>(DRE->getDecl()); 11890 Loc = DRE->getLocation(); 11891 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) { 11892 Var = cast<VarDecl>(ME->getMemberDecl()); 11893 Loc = ME->getMemberLoc(); 11894 } else { 11895 llvm_unreachable("Unexpcted expression"); 11896 } 11897 11898 MarkVarDeclODRUsed(*this, Var, Loc); 11899 } 11900 11901 MaybeODRUseExprs.clear(); 11902 } 11903 11904 // Mark a VarDecl referenced, and perform the necessary handling to compute 11905 // odr-uses. 11906 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 11907 VarDecl *Var, Expr *E) { 11908 Var->setReferenced(); 11909 11910 if (!IsPotentiallyEvaluatedContext(SemaRef)) 11911 return; 11912 11913 VarTemplateSpecializationDecl *VarSpec = 11914 dyn_cast<VarTemplateSpecializationDecl>(Var); 11915 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 11916 "Can't instantiate a partial template specialization."); 11917 11918 // Implicit instantiation of static data members, static data member 11919 // templates of class templates, and variable template specializations. 11920 // Delay instantiations of variable templates, except for those 11921 // that could be used in a constant expression. 11922 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 11923 if (isTemplateInstantiation(TSK)) { 11924 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 11925 11926 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 11927 if (Var->getPointOfInstantiation().isInvalid()) { 11928 // This is a modification of an existing AST node. Notify listeners. 11929 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 11930 L->StaticDataMemberInstantiated(Var); 11931 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 11932 // Don't bother trying to instantiate it again, unless we might need 11933 // its initializer before we get to the end of the TU. 11934 TryInstantiating = false; 11935 } 11936 11937 if (Var->getPointOfInstantiation().isInvalid()) 11938 Var->setTemplateSpecializationKind(TSK, Loc); 11939 11940 if (TryInstantiating) { 11941 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 11942 bool InstantiationDependent = false; 11943 bool IsNonDependent = 11944 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 11945 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 11946 : true; 11947 11948 // Do not instantiate specializations that are still type-dependent. 11949 if (IsNonDependent) { 11950 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 11951 // Do not defer instantiations of variables which could be used in a 11952 // constant expression. 11953 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 11954 } else { 11955 SemaRef.PendingInstantiations 11956 .push_back(std::make_pair(Var, PointOfInstantiation)); 11957 } 11958 } 11959 } 11960 } 11961 11962 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 11963 // the requirements for appearing in a constant expression (5.19) and, if 11964 // it is an object, the lvalue-to-rvalue conversion (4.1) 11965 // is immediately applied." We check the first part here, and 11966 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 11967 // Note that we use the C++11 definition everywhere because nothing in 11968 // C++03 depends on whether we get the C++03 version correct. The second 11969 // part does not apply to references, since they are not objects. 11970 const VarDecl *DefVD; 11971 if (E && !isa<ParmVarDecl>(Var) && 11972 Var->isUsableInConstantExpressions(SemaRef.Context) && 11973 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE()) { 11974 if (!Var->getType()->isReferenceType()) 11975 SemaRef.MaybeODRUseExprs.insert(E); 11976 } else 11977 MarkVarDeclODRUsed(SemaRef, Var, Loc); 11978 } 11979 11980 /// \brief Mark a variable referenced, and check whether it is odr-used 11981 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 11982 /// used directly for normal expressions referring to VarDecl. 11983 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 11984 DoMarkVarDeclReferenced(*this, Loc, Var, 0); 11985 } 11986 11987 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 11988 Decl *D, Expr *E, bool OdrUse) { 11989 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 11990 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 11991 return; 11992 } 11993 11994 SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse); 11995 11996 // If this is a call to a method via a cast, also mark the method in the 11997 // derived class used in case codegen can devirtualize the call. 11998 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 11999 if (!ME) 12000 return; 12001 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 12002 if (!MD) 12003 return; 12004 const Expr *Base = ME->getBase(); 12005 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 12006 if (!MostDerivedClassDecl) 12007 return; 12008 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 12009 if (!DM || DM->isPure()) 12010 return; 12011 SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse); 12012 } 12013 12014 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 12015 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 12016 // TODO: update this with DR# once a defect report is filed. 12017 // C++11 defect. The address of a pure member should not be an ODR use, even 12018 // if it's a qualified reference. 12019 bool OdrUse = true; 12020 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 12021 if (Method->isVirtual()) 12022 OdrUse = false; 12023 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 12024 } 12025 12026 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 12027 void Sema::MarkMemberReferenced(MemberExpr *E) { 12028 // C++11 [basic.def.odr]p2: 12029 // A non-overloaded function whose name appears as a potentially-evaluated 12030 // expression or a member of a set of candidate functions, if selected by 12031 // overload resolution when referred to from a potentially-evaluated 12032 // expression, is odr-used, unless it is a pure virtual function and its 12033 // name is not explicitly qualified. 12034 bool OdrUse = true; 12035 if (!E->hasQualifier()) { 12036 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 12037 if (Method->isPure()) 12038 OdrUse = false; 12039 } 12040 SourceLocation Loc = E->getMemberLoc().isValid() ? 12041 E->getMemberLoc() : E->getLocStart(); 12042 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse); 12043 } 12044 12045 /// \brief Perform marking for a reference to an arbitrary declaration. It 12046 /// marks the declaration referenced, and performs odr-use checking for functions 12047 /// and variables. This method should not be used when building an normal 12048 /// expression which refers to a variable. 12049 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) { 12050 if (OdrUse) { 12051 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 12052 MarkVariableReferenced(Loc, VD); 12053 return; 12054 } 12055 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 12056 MarkFunctionReferenced(Loc, FD); 12057 return; 12058 } 12059 } 12060 D->setReferenced(); 12061 } 12062 12063 namespace { 12064 // Mark all of the declarations referenced 12065 // FIXME: Not fully implemented yet! We need to have a better understanding 12066 // of when we're entering 12067 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 12068 Sema &S; 12069 SourceLocation Loc; 12070 12071 public: 12072 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 12073 12074 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 12075 12076 bool TraverseTemplateArgument(const TemplateArgument &Arg); 12077 bool TraverseRecordType(RecordType *T); 12078 }; 12079 } 12080 12081 bool MarkReferencedDecls::TraverseTemplateArgument( 12082 const TemplateArgument &Arg) { 12083 if (Arg.getKind() == TemplateArgument::Declaration) { 12084 if (Decl *D = Arg.getAsDecl()) 12085 S.MarkAnyDeclReferenced(Loc, D, true); 12086 } 12087 12088 return Inherited::TraverseTemplateArgument(Arg); 12089 } 12090 12091 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 12092 if (ClassTemplateSpecializationDecl *Spec 12093 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 12094 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 12095 return TraverseTemplateArguments(Args.data(), Args.size()); 12096 } 12097 12098 return true; 12099 } 12100 12101 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 12102 MarkReferencedDecls Marker(*this, Loc); 12103 Marker.TraverseType(Context.getCanonicalType(T)); 12104 } 12105 12106 namespace { 12107 /// \brief Helper class that marks all of the declarations referenced by 12108 /// potentially-evaluated subexpressions as "referenced". 12109 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 12110 Sema &S; 12111 bool SkipLocalVariables; 12112 12113 public: 12114 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 12115 12116 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 12117 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 12118 12119 void VisitDeclRefExpr(DeclRefExpr *E) { 12120 // If we were asked not to visit local variables, don't. 12121 if (SkipLocalVariables) { 12122 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 12123 if (VD->hasLocalStorage()) 12124 return; 12125 } 12126 12127 S.MarkDeclRefReferenced(E); 12128 } 12129 12130 void VisitMemberExpr(MemberExpr *E) { 12131 S.MarkMemberReferenced(E); 12132 Inherited::VisitMemberExpr(E); 12133 } 12134 12135 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 12136 S.MarkFunctionReferenced(E->getLocStart(), 12137 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 12138 Visit(E->getSubExpr()); 12139 } 12140 12141 void VisitCXXNewExpr(CXXNewExpr *E) { 12142 if (E->getOperatorNew()) 12143 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 12144 if (E->getOperatorDelete()) 12145 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 12146 Inherited::VisitCXXNewExpr(E); 12147 } 12148 12149 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 12150 if (E->getOperatorDelete()) 12151 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 12152 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 12153 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 12154 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 12155 S.MarkFunctionReferenced(E->getLocStart(), 12156 S.LookupDestructor(Record)); 12157 } 12158 12159 Inherited::VisitCXXDeleteExpr(E); 12160 } 12161 12162 void VisitCXXConstructExpr(CXXConstructExpr *E) { 12163 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 12164 Inherited::VisitCXXConstructExpr(E); 12165 } 12166 12167 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 12168 Visit(E->getExpr()); 12169 } 12170 12171 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 12172 Inherited::VisitImplicitCastExpr(E); 12173 12174 if (E->getCastKind() == CK_LValueToRValue) 12175 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 12176 } 12177 }; 12178 } 12179 12180 /// \brief Mark any declarations that appear within this expression or any 12181 /// potentially-evaluated subexpressions as "referenced". 12182 /// 12183 /// \param SkipLocalVariables If true, don't mark local variables as 12184 /// 'referenced'. 12185 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 12186 bool SkipLocalVariables) { 12187 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 12188 } 12189 12190 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 12191 /// of the program being compiled. 12192 /// 12193 /// This routine emits the given diagnostic when the code currently being 12194 /// type-checked is "potentially evaluated", meaning that there is a 12195 /// possibility that the code will actually be executable. Code in sizeof() 12196 /// expressions, code used only during overload resolution, etc., are not 12197 /// potentially evaluated. This routine will suppress such diagnostics or, 12198 /// in the absolutely nutty case of potentially potentially evaluated 12199 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 12200 /// later. 12201 /// 12202 /// This routine should be used for all diagnostics that describe the run-time 12203 /// behavior of a program, such as passing a non-POD value through an ellipsis. 12204 /// Failure to do so will likely result in spurious diagnostics or failures 12205 /// during overload resolution or within sizeof/alignof/typeof/typeid. 12206 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 12207 const PartialDiagnostic &PD) { 12208 switch (ExprEvalContexts.back().Context) { 12209 case Unevaluated: 12210 case UnevaluatedAbstract: 12211 // The argument will never be evaluated, so don't complain. 12212 break; 12213 12214 case ConstantEvaluated: 12215 // Relevant diagnostics should be produced by constant evaluation. 12216 break; 12217 12218 case PotentiallyEvaluated: 12219 case PotentiallyEvaluatedIfUsed: 12220 if (Statement && getCurFunctionOrMethodDecl()) { 12221 FunctionScopes.back()->PossiblyUnreachableDiags. 12222 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 12223 } 12224 else 12225 Diag(Loc, PD); 12226 12227 return true; 12228 } 12229 12230 return false; 12231 } 12232 12233 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 12234 CallExpr *CE, FunctionDecl *FD) { 12235 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 12236 return false; 12237 12238 // If we're inside a decltype's expression, don't check for a valid return 12239 // type or construct temporaries until we know whether this is the last call. 12240 if (ExprEvalContexts.back().IsDecltype) { 12241 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 12242 return false; 12243 } 12244 12245 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 12246 FunctionDecl *FD; 12247 CallExpr *CE; 12248 12249 public: 12250 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 12251 : FD(FD), CE(CE) { } 12252 12253 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 12254 if (!FD) { 12255 S.Diag(Loc, diag::err_call_incomplete_return) 12256 << T << CE->getSourceRange(); 12257 return; 12258 } 12259 12260 S.Diag(Loc, diag::err_call_function_incomplete_return) 12261 << CE->getSourceRange() << FD->getDeclName() << T; 12262 S.Diag(FD->getLocation(), 12263 diag::note_function_with_incomplete_return_type_declared_here) 12264 << FD->getDeclName(); 12265 } 12266 } Diagnoser(FD, CE); 12267 12268 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 12269 return true; 12270 12271 return false; 12272 } 12273 12274 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 12275 // will prevent this condition from triggering, which is what we want. 12276 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 12277 SourceLocation Loc; 12278 12279 unsigned diagnostic = diag::warn_condition_is_assignment; 12280 bool IsOrAssign = false; 12281 12282 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 12283 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 12284 return; 12285 12286 IsOrAssign = Op->getOpcode() == BO_OrAssign; 12287 12288 // Greylist some idioms by putting them into a warning subcategory. 12289 if (ObjCMessageExpr *ME 12290 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 12291 Selector Sel = ME->getSelector(); 12292 12293 // self = [<foo> init...] 12294 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 12295 diagnostic = diag::warn_condition_is_idiomatic_assignment; 12296 12297 // <foo> = [<bar> nextObject] 12298 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 12299 diagnostic = diag::warn_condition_is_idiomatic_assignment; 12300 } 12301 12302 Loc = Op->getOperatorLoc(); 12303 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 12304 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 12305 return; 12306 12307 IsOrAssign = Op->getOperator() == OO_PipeEqual; 12308 Loc = Op->getOperatorLoc(); 12309 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 12310 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 12311 else { 12312 // Not an assignment. 12313 return; 12314 } 12315 12316 Diag(Loc, diagnostic) << E->getSourceRange(); 12317 12318 SourceLocation Open = E->getLocStart(); 12319 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd()); 12320 Diag(Loc, diag::note_condition_assign_silence) 12321 << FixItHint::CreateInsertion(Open, "(") 12322 << FixItHint::CreateInsertion(Close, ")"); 12323 12324 if (IsOrAssign) 12325 Diag(Loc, diag::note_condition_or_assign_to_comparison) 12326 << FixItHint::CreateReplacement(Loc, "!="); 12327 else 12328 Diag(Loc, diag::note_condition_assign_to_comparison) 12329 << FixItHint::CreateReplacement(Loc, "=="); 12330 } 12331 12332 /// \brief Redundant parentheses over an equality comparison can indicate 12333 /// that the user intended an assignment used as condition. 12334 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 12335 // Don't warn if the parens came from a macro. 12336 SourceLocation parenLoc = ParenE->getLocStart(); 12337 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 12338 return; 12339 // Don't warn for dependent expressions. 12340 if (ParenE->isTypeDependent()) 12341 return; 12342 12343 Expr *E = ParenE->IgnoreParens(); 12344 12345 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 12346 if (opE->getOpcode() == BO_EQ && 12347 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 12348 == Expr::MLV_Valid) { 12349 SourceLocation Loc = opE->getOperatorLoc(); 12350 12351 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 12352 SourceRange ParenERange = ParenE->getSourceRange(); 12353 Diag(Loc, diag::note_equality_comparison_silence) 12354 << FixItHint::CreateRemoval(ParenERange.getBegin()) 12355 << FixItHint::CreateRemoval(ParenERange.getEnd()); 12356 Diag(Loc, diag::note_equality_comparison_to_assign) 12357 << FixItHint::CreateReplacement(Loc, "="); 12358 } 12359 } 12360 12361 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) { 12362 DiagnoseAssignmentAsCondition(E); 12363 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 12364 DiagnoseEqualityWithExtraParens(parenE); 12365 12366 ExprResult result = CheckPlaceholderExpr(E); 12367 if (result.isInvalid()) return ExprError(); 12368 E = result.take(); 12369 12370 if (!E->isTypeDependent()) { 12371 if (getLangOpts().CPlusPlus) 12372 return CheckCXXBooleanCondition(E); // C++ 6.4p4 12373 12374 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 12375 if (ERes.isInvalid()) 12376 return ExprError(); 12377 E = ERes.take(); 12378 12379 QualType T = E->getType(); 12380 if (!T->isScalarType()) { // C99 6.8.4.1p1 12381 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 12382 << T << E->getSourceRange(); 12383 return ExprError(); 12384 } 12385 } 12386 12387 return Owned(E); 12388 } 12389 12390 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc, 12391 Expr *SubExpr) { 12392 if (!SubExpr) 12393 return ExprError(); 12394 12395 return CheckBooleanCondition(SubExpr, Loc); 12396 } 12397 12398 namespace { 12399 /// A visitor for rebuilding a call to an __unknown_any expression 12400 /// to have an appropriate type. 12401 struct RebuildUnknownAnyFunction 12402 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 12403 12404 Sema &S; 12405 12406 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 12407 12408 ExprResult VisitStmt(Stmt *S) { 12409 llvm_unreachable("unexpected statement!"); 12410 } 12411 12412 ExprResult VisitExpr(Expr *E) { 12413 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 12414 << E->getSourceRange(); 12415 return ExprError(); 12416 } 12417 12418 /// Rebuild an expression which simply semantically wraps another 12419 /// expression which it shares the type and value kind of. 12420 template <class T> ExprResult rebuildSugarExpr(T *E) { 12421 ExprResult SubResult = Visit(E->getSubExpr()); 12422 if (SubResult.isInvalid()) return ExprError(); 12423 12424 Expr *SubExpr = SubResult.take(); 12425 E->setSubExpr(SubExpr); 12426 E->setType(SubExpr->getType()); 12427 E->setValueKind(SubExpr->getValueKind()); 12428 assert(E->getObjectKind() == OK_Ordinary); 12429 return E; 12430 } 12431 12432 ExprResult VisitParenExpr(ParenExpr *E) { 12433 return rebuildSugarExpr(E); 12434 } 12435 12436 ExprResult VisitUnaryExtension(UnaryOperator *E) { 12437 return rebuildSugarExpr(E); 12438 } 12439 12440 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 12441 ExprResult SubResult = Visit(E->getSubExpr()); 12442 if (SubResult.isInvalid()) return ExprError(); 12443 12444 Expr *SubExpr = SubResult.take(); 12445 E->setSubExpr(SubExpr); 12446 E->setType(S.Context.getPointerType(SubExpr->getType())); 12447 assert(E->getValueKind() == VK_RValue); 12448 assert(E->getObjectKind() == OK_Ordinary); 12449 return E; 12450 } 12451 12452 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 12453 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 12454 12455 E->setType(VD->getType()); 12456 12457 assert(E->getValueKind() == VK_RValue); 12458 if (S.getLangOpts().CPlusPlus && 12459 !(isa<CXXMethodDecl>(VD) && 12460 cast<CXXMethodDecl>(VD)->isInstance())) 12461 E->setValueKind(VK_LValue); 12462 12463 return E; 12464 } 12465 12466 ExprResult VisitMemberExpr(MemberExpr *E) { 12467 return resolveDecl(E, E->getMemberDecl()); 12468 } 12469 12470 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 12471 return resolveDecl(E, E->getDecl()); 12472 } 12473 }; 12474 } 12475 12476 /// Given a function expression of unknown-any type, try to rebuild it 12477 /// to have a function type. 12478 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 12479 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 12480 if (Result.isInvalid()) return ExprError(); 12481 return S.DefaultFunctionArrayConversion(Result.take()); 12482 } 12483 12484 namespace { 12485 /// A visitor for rebuilding an expression of type __unknown_anytype 12486 /// into one which resolves the type directly on the referring 12487 /// expression. Strict preservation of the original source 12488 /// structure is not a goal. 12489 struct RebuildUnknownAnyExpr 12490 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 12491 12492 Sema &S; 12493 12494 /// The current destination type. 12495 QualType DestType; 12496 12497 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 12498 : S(S), DestType(CastType) {} 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_expr) 12506 << E->getSourceRange(); 12507 return ExprError(); 12508 } 12509 12510 ExprResult VisitCallExpr(CallExpr *E); 12511 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 12512 12513 /// Rebuild an expression which simply semantically wraps another 12514 /// expression which it shares the type and value kind of. 12515 template <class T> ExprResult rebuildSugarExpr(T *E) { 12516 ExprResult SubResult = Visit(E->getSubExpr()); 12517 if (SubResult.isInvalid()) return ExprError(); 12518 Expr *SubExpr = SubResult.take(); 12519 E->setSubExpr(SubExpr); 12520 E->setType(SubExpr->getType()); 12521 E->setValueKind(SubExpr->getValueKind()); 12522 assert(E->getObjectKind() == OK_Ordinary); 12523 return E; 12524 } 12525 12526 ExprResult VisitParenExpr(ParenExpr *E) { 12527 return rebuildSugarExpr(E); 12528 } 12529 12530 ExprResult VisitUnaryExtension(UnaryOperator *E) { 12531 return rebuildSugarExpr(E); 12532 } 12533 12534 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 12535 const PointerType *Ptr = DestType->getAs<PointerType>(); 12536 if (!Ptr) { 12537 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 12538 << E->getSourceRange(); 12539 return ExprError(); 12540 } 12541 assert(E->getValueKind() == VK_RValue); 12542 assert(E->getObjectKind() == OK_Ordinary); 12543 E->setType(DestType); 12544 12545 // Build the sub-expression as if it were an object of the pointee type. 12546 DestType = Ptr->getPointeeType(); 12547 ExprResult SubResult = Visit(E->getSubExpr()); 12548 if (SubResult.isInvalid()) return ExprError(); 12549 E->setSubExpr(SubResult.take()); 12550 return E; 12551 } 12552 12553 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 12554 12555 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 12556 12557 ExprResult VisitMemberExpr(MemberExpr *E) { 12558 return resolveDecl(E, E->getMemberDecl()); 12559 } 12560 12561 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 12562 return resolveDecl(E, E->getDecl()); 12563 } 12564 }; 12565 } 12566 12567 /// Rebuilds a call expression which yielded __unknown_anytype. 12568 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 12569 Expr *CalleeExpr = E->getCallee(); 12570 12571 enum FnKind { 12572 FK_MemberFunction, 12573 FK_FunctionPointer, 12574 FK_BlockPointer 12575 }; 12576 12577 FnKind Kind; 12578 QualType CalleeType = CalleeExpr->getType(); 12579 if (CalleeType == S.Context.BoundMemberTy) { 12580 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 12581 Kind = FK_MemberFunction; 12582 CalleeType = Expr::findBoundMemberType(CalleeExpr); 12583 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 12584 CalleeType = Ptr->getPointeeType(); 12585 Kind = FK_FunctionPointer; 12586 } else { 12587 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 12588 Kind = FK_BlockPointer; 12589 } 12590 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 12591 12592 // Verify that this is a legal result type of a function. 12593 if (DestType->isArrayType() || DestType->isFunctionType()) { 12594 unsigned diagID = diag::err_func_returning_array_function; 12595 if (Kind == FK_BlockPointer) 12596 diagID = diag::err_block_returning_array_function; 12597 12598 S.Diag(E->getExprLoc(), diagID) 12599 << DestType->isFunctionType() << DestType; 12600 return ExprError(); 12601 } 12602 12603 // Otherwise, go ahead and set DestType as the call's result. 12604 E->setType(DestType.getNonLValueExprType(S.Context)); 12605 E->setValueKind(Expr::getValueKindForType(DestType)); 12606 assert(E->getObjectKind() == OK_Ordinary); 12607 12608 // Rebuild the function type, replacing the result type with DestType. 12609 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 12610 if (Proto) { 12611 // __unknown_anytype(...) is a special case used by the debugger when 12612 // it has no idea what a function's signature is. 12613 // 12614 // We want to build this call essentially under the K&R 12615 // unprototyped rules, but making a FunctionNoProtoType in C++ 12616 // would foul up all sorts of assumptions. However, we cannot 12617 // simply pass all arguments as variadic arguments, nor can we 12618 // portably just call the function under a non-variadic type; see 12619 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 12620 // However, it turns out that in practice it is generally safe to 12621 // call a function declared as "A foo(B,C,D);" under the prototype 12622 // "A foo(B,C,D,...);". The only known exception is with the 12623 // Windows ABI, where any variadic function is implicitly cdecl 12624 // regardless of its normal CC. Therefore we change the parameter 12625 // types to match the types of the arguments. 12626 // 12627 // This is a hack, but it is far superior to moving the 12628 // corresponding target-specific code from IR-gen to Sema/AST. 12629 12630 ArrayRef<QualType> ParamTypes = Proto->getArgTypes(); 12631 SmallVector<QualType, 8> ArgTypes; 12632 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 12633 ArgTypes.reserve(E->getNumArgs()); 12634 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 12635 Expr *Arg = E->getArg(i); 12636 QualType ArgType = Arg->getType(); 12637 if (E->isLValue()) { 12638 ArgType = S.Context.getLValueReferenceType(ArgType); 12639 } else if (E->isXValue()) { 12640 ArgType = S.Context.getRValueReferenceType(ArgType); 12641 } 12642 ArgTypes.push_back(ArgType); 12643 } 12644 ParamTypes = ArgTypes; 12645 } 12646 DestType = S.Context.getFunctionType(DestType, ParamTypes, 12647 Proto->getExtProtoInfo()); 12648 } else { 12649 DestType = S.Context.getFunctionNoProtoType(DestType, 12650 FnType->getExtInfo()); 12651 } 12652 12653 // Rebuild the appropriate pointer-to-function type. 12654 switch (Kind) { 12655 case FK_MemberFunction: 12656 // Nothing to do. 12657 break; 12658 12659 case FK_FunctionPointer: 12660 DestType = S.Context.getPointerType(DestType); 12661 break; 12662 12663 case FK_BlockPointer: 12664 DestType = S.Context.getBlockPointerType(DestType); 12665 break; 12666 } 12667 12668 // Finally, we can recurse. 12669 ExprResult CalleeResult = Visit(CalleeExpr); 12670 if (!CalleeResult.isUsable()) return ExprError(); 12671 E->setCallee(CalleeResult.take()); 12672 12673 // Bind a temporary if necessary. 12674 return S.MaybeBindToTemporary(E); 12675 } 12676 12677 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 12678 // Verify that this is a legal result type of a call. 12679 if (DestType->isArrayType() || DestType->isFunctionType()) { 12680 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 12681 << DestType->isFunctionType() << DestType; 12682 return ExprError(); 12683 } 12684 12685 // Rewrite the method result type if available. 12686 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 12687 assert(Method->getResultType() == S.Context.UnknownAnyTy); 12688 Method->setResultType(DestType); 12689 } 12690 12691 // Change the type of the message. 12692 E->setType(DestType.getNonReferenceType()); 12693 E->setValueKind(Expr::getValueKindForType(DestType)); 12694 12695 return S.MaybeBindToTemporary(E); 12696 } 12697 12698 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 12699 // The only case we should ever see here is a function-to-pointer decay. 12700 if (E->getCastKind() == CK_FunctionToPointerDecay) { 12701 assert(E->getValueKind() == VK_RValue); 12702 assert(E->getObjectKind() == OK_Ordinary); 12703 12704 E->setType(DestType); 12705 12706 // Rebuild the sub-expression as the pointee (function) type. 12707 DestType = DestType->castAs<PointerType>()->getPointeeType(); 12708 12709 ExprResult Result = Visit(E->getSubExpr()); 12710 if (!Result.isUsable()) return ExprError(); 12711 12712 E->setSubExpr(Result.take()); 12713 return S.Owned(E); 12714 } else if (E->getCastKind() == CK_LValueToRValue) { 12715 assert(E->getValueKind() == VK_RValue); 12716 assert(E->getObjectKind() == OK_Ordinary); 12717 12718 assert(isa<BlockPointerType>(E->getType())); 12719 12720 E->setType(DestType); 12721 12722 // The sub-expression has to be a lvalue reference, so rebuild it as such. 12723 DestType = S.Context.getLValueReferenceType(DestType); 12724 12725 ExprResult Result = Visit(E->getSubExpr()); 12726 if (!Result.isUsable()) return ExprError(); 12727 12728 E->setSubExpr(Result.take()); 12729 return S.Owned(E); 12730 } else { 12731 llvm_unreachable("Unhandled cast type!"); 12732 } 12733 } 12734 12735 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 12736 ExprValueKind ValueKind = VK_LValue; 12737 QualType Type = DestType; 12738 12739 // We know how to make this work for certain kinds of decls: 12740 12741 // - functions 12742 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 12743 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 12744 DestType = Ptr->getPointeeType(); 12745 ExprResult Result = resolveDecl(E, VD); 12746 if (Result.isInvalid()) return ExprError(); 12747 return S.ImpCastExprToType(Result.take(), Type, 12748 CK_FunctionToPointerDecay, VK_RValue); 12749 } 12750 12751 if (!Type->isFunctionType()) { 12752 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 12753 << VD << E->getSourceRange(); 12754 return ExprError(); 12755 } 12756 12757 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 12758 if (MD->isInstance()) { 12759 ValueKind = VK_RValue; 12760 Type = S.Context.BoundMemberTy; 12761 } 12762 12763 // Function references aren't l-values in C. 12764 if (!S.getLangOpts().CPlusPlus) 12765 ValueKind = VK_RValue; 12766 12767 // - variables 12768 } else if (isa<VarDecl>(VD)) { 12769 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 12770 Type = RefTy->getPointeeType(); 12771 } else if (Type->isFunctionType()) { 12772 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 12773 << VD << E->getSourceRange(); 12774 return ExprError(); 12775 } 12776 12777 // - nothing else 12778 } else { 12779 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 12780 << VD << E->getSourceRange(); 12781 return ExprError(); 12782 } 12783 12784 // Modifying the declaration like this is friendly to IR-gen but 12785 // also really dangerous. 12786 VD->setType(DestType); 12787 E->setType(Type); 12788 E->setValueKind(ValueKind); 12789 return S.Owned(E); 12790 } 12791 12792 /// Check a cast of an unknown-any type. We intentionally only 12793 /// trigger this for C-style casts. 12794 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 12795 Expr *CastExpr, CastKind &CastKind, 12796 ExprValueKind &VK, CXXCastPath &Path) { 12797 // Rewrite the casted expression from scratch. 12798 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 12799 if (!result.isUsable()) return ExprError(); 12800 12801 CastExpr = result.take(); 12802 VK = CastExpr->getValueKind(); 12803 CastKind = CK_NoOp; 12804 12805 return CastExpr; 12806 } 12807 12808 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 12809 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 12810 } 12811 12812 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 12813 Expr *arg, QualType ¶mType) { 12814 // If the syntactic form of the argument is not an explicit cast of 12815 // any sort, just do default argument promotion. 12816 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 12817 if (!castArg) { 12818 ExprResult result = DefaultArgumentPromotion(arg); 12819 if (result.isInvalid()) return ExprError(); 12820 paramType = result.get()->getType(); 12821 return result; 12822 } 12823 12824 // Otherwise, use the type that was written in the explicit cast. 12825 assert(!arg->hasPlaceholderType()); 12826 paramType = castArg->getTypeAsWritten(); 12827 12828 // Copy-initialize a parameter of that type. 12829 InitializedEntity entity = 12830 InitializedEntity::InitializeParameter(Context, paramType, 12831 /*consumed*/ false); 12832 return PerformCopyInitialization(entity, callLoc, Owned(arg)); 12833 } 12834 12835 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 12836 Expr *orig = E; 12837 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 12838 while (true) { 12839 E = E->IgnoreParenImpCasts(); 12840 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 12841 E = call->getCallee(); 12842 diagID = diag::err_uncasted_call_of_unknown_any; 12843 } else { 12844 break; 12845 } 12846 } 12847 12848 SourceLocation loc; 12849 NamedDecl *d; 12850 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 12851 loc = ref->getLocation(); 12852 d = ref->getDecl(); 12853 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 12854 loc = mem->getMemberLoc(); 12855 d = mem->getMemberDecl(); 12856 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 12857 diagID = diag::err_uncasted_call_of_unknown_any; 12858 loc = msg->getSelectorStartLoc(); 12859 d = msg->getMethodDecl(); 12860 if (!d) { 12861 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 12862 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 12863 << orig->getSourceRange(); 12864 return ExprError(); 12865 } 12866 } else { 12867 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 12868 << E->getSourceRange(); 12869 return ExprError(); 12870 } 12871 12872 S.Diag(loc, diagID) << d << orig->getSourceRange(); 12873 12874 // Never recoverable. 12875 return ExprError(); 12876 } 12877 12878 /// Check for operands with placeholder types and complain if found. 12879 /// Returns true if there was an error and no recovery was possible. 12880 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 12881 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 12882 if (!placeholderType) return Owned(E); 12883 12884 switch (placeholderType->getKind()) { 12885 12886 // Overloaded expressions. 12887 case BuiltinType::Overload: { 12888 // Try to resolve a single function template specialization. 12889 // This is obligatory. 12890 ExprResult result = Owned(E); 12891 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) { 12892 return result; 12893 12894 // If that failed, try to recover with a call. 12895 } else { 12896 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable), 12897 /*complain*/ true); 12898 return result; 12899 } 12900 } 12901 12902 // Bound member functions. 12903 case BuiltinType::BoundMember: { 12904 ExprResult result = Owned(E); 12905 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function), 12906 /*complain*/ true); 12907 return result; 12908 } 12909 12910 // ARC unbridged casts. 12911 case BuiltinType::ARCUnbridgedCast: { 12912 Expr *realCast = stripARCUnbridgedCast(E); 12913 diagnoseARCUnbridgedCast(realCast); 12914 return Owned(realCast); 12915 } 12916 12917 // Expressions of unknown type. 12918 case BuiltinType::UnknownAny: 12919 return diagnoseUnknownAnyExpr(*this, E); 12920 12921 // Pseudo-objects. 12922 case BuiltinType::PseudoObject: 12923 return checkPseudoObjectRValue(E); 12924 12925 case BuiltinType::BuiltinFn: 12926 Diag(E->getLocStart(), diag::err_builtin_fn_use); 12927 return ExprError(); 12928 12929 // Everything else should be impossible. 12930 #define BUILTIN_TYPE(Id, SingletonId) \ 12931 case BuiltinType::Id: 12932 #define PLACEHOLDER_TYPE(Id, SingletonId) 12933 #include "clang/AST/BuiltinTypes.def" 12934 break; 12935 } 12936 12937 llvm_unreachable("invalid placeholder type!"); 12938 } 12939 12940 bool Sema::CheckCaseExpression(Expr *E) { 12941 if (E->isTypeDependent()) 12942 return true; 12943 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 12944 return E->getType()->isIntegralOrEnumerationType(); 12945 return false; 12946 } 12947 12948 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 12949 ExprResult 12950 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 12951 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 12952 "Unknown Objective-C Boolean value!"); 12953 QualType BoolT = Context.ObjCBuiltinBoolTy; 12954 if (!Context.getBOOLDecl()) { 12955 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 12956 Sema::LookupOrdinaryName); 12957 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 12958 NamedDecl *ND = Result.getFoundDecl(); 12959 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 12960 Context.setBOOLDecl(TD); 12961 } 12962 } 12963 if (Context.getBOOLDecl()) 12964 BoolT = Context.getBOOLType(); 12965 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, 12966 BoolT, OpLoc)); 12967 } 12968