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 or unavailable. 144 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 145 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 146 147 if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) { 148 // If the method was explicitly defaulted, point at that declaration. 149 if (!Method->isImplicit()) 150 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 151 152 // Try to diagnose why this special member function was implicitly 153 // deleted. This might fail, if that reason no longer applies. 154 CXXSpecialMember CSM = getSpecialMember(Method); 155 if (CSM != CXXInvalid) 156 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true); 157 158 return; 159 } 160 161 Diag(Decl->getLocation(), diag::note_unavailable_here) 162 << 1 << Decl->isDeleted(); 163 } 164 165 /// \brief Determine whether a FunctionDecl was ever declared with an 166 /// explicit storage class. 167 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 168 for (FunctionDecl::redecl_iterator I = D->redecls_begin(), 169 E = D->redecls_end(); 170 I != E; ++I) { 171 if (I->getStorageClass() != SC_None) 172 return true; 173 } 174 return false; 175 } 176 177 /// \brief Check whether we're in an extern inline function and referring to a 178 /// variable or function with internal linkage (C11 6.7.4p3). 179 /// 180 /// This is only a warning because we used to silently accept this code, but 181 /// in many cases it will not behave correctly. This is not enabled in C++ mode 182 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 183 /// and so while there may still be user mistakes, most of the time we can't 184 /// prove that there are errors. 185 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 186 const NamedDecl *D, 187 SourceLocation Loc) { 188 // This is disabled under C++; there are too many ways for this to fire in 189 // contexts where the warning is a false positive, or where it is technically 190 // correct but benign. 191 if (S.getLangOpts().CPlusPlus) 192 return; 193 194 // Check if this is an inlined function or method. 195 FunctionDecl *Current = S.getCurFunctionDecl(); 196 if (!Current) 197 return; 198 if (!Current->isInlined()) 199 return; 200 if (Current->getLinkage() != ExternalLinkage) 201 return; 202 203 // Check if the decl has internal linkage. 204 if (D->getLinkage() != InternalLinkage) 205 return; 206 207 // Downgrade from ExtWarn to Extension if 208 // (1) the supposedly external inline function is in the main file, 209 // and probably won't be included anywhere else. 210 // (2) the thing we're referencing is a pure function. 211 // (3) the thing we're referencing is another inline function. 212 // This last can give us false negatives, but it's better than warning on 213 // wrappers for simple C library functions. 214 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 215 bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc); 216 if (!DowngradeWarning && UsedFn) 217 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 218 219 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline 220 : diag::warn_internal_in_extern_inline) 221 << /*IsVar=*/!UsedFn << D; 222 223 S.MaybeSuggestAddingStaticToDecl(Current); 224 225 S.Diag(D->getCanonicalDecl()->getLocation(), 226 diag::note_internal_decl_declared_here) 227 << D; 228 } 229 230 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 231 const FunctionDecl *First = Cur->getFirstDeclaration(); 232 233 // Suggest "static" on the function, if possible. 234 if (!hasAnyExplicitStorageClass(First)) { 235 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 236 Diag(DeclBegin, diag::note_convert_inline_to_static) 237 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 238 } 239 } 240 241 /// \brief Determine whether the use of this declaration is valid, and 242 /// emit any corresponding diagnostics. 243 /// 244 /// This routine diagnoses various problems with referencing 245 /// declarations that can occur when using a declaration. For example, 246 /// it might warn if a deprecated or unavailable declaration is being 247 /// used, or produce an error (and return true) if a C++0x deleted 248 /// function is being used. 249 /// 250 /// \returns true if there was an error (this declaration cannot be 251 /// referenced), false otherwise. 252 /// 253 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 254 const ObjCInterfaceDecl *UnknownObjCClass) { 255 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 256 // If there were any diagnostics suppressed by template argument deduction, 257 // emit them now. 258 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator 259 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 260 if (Pos != SuppressedDiagnostics.end()) { 261 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second; 262 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I) 263 Diag(Suppressed[I].first, Suppressed[I].second); 264 265 // Clear out the list of suppressed diagnostics, so that we don't emit 266 // them again for this specialization. However, we don't obsolete this 267 // entry from the table, because we want to avoid ever emitting these 268 // diagnostics again. 269 Suppressed.clear(); 270 } 271 } 272 273 // See if this is an auto-typed variable whose initializer we are parsing. 274 if (ParsingInitForAutoVars.count(D)) { 275 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 276 << D->getDeclName(); 277 return true; 278 } 279 280 // See if this is a deleted function. 281 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 282 if (FD->isDeleted()) { 283 Diag(Loc, diag::err_deleted_function_use); 284 NoteDeletedFunction(FD); 285 return true; 286 } 287 288 // If the function has a deduced return type, and we can't deduce it, 289 // then we can't use it either. 290 if (getLangOpts().CPlusPlus1y && FD->getResultType()->isUndeducedType() && 291 DeduceReturnType(FD, Loc)) 292 return true; 293 } 294 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass); 295 296 DiagnoseUnusedOfDecl(*this, D, Loc); 297 298 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 299 300 return false; 301 } 302 303 /// \brief Retrieve the message suffix that should be added to a 304 /// diagnostic complaining about the given function being deleted or 305 /// unavailable. 306 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 307 std::string Message; 308 if (FD->getAvailability(&Message)) 309 return ": " + Message; 310 311 return std::string(); 312 } 313 314 /// DiagnoseSentinelCalls - This routine checks whether a call or 315 /// message-send is to a declaration with the sentinel attribute, and 316 /// if so, it checks that the requirements of the sentinel are 317 /// satisfied. 318 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 319 ArrayRef<Expr *> Args) { 320 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 321 if (!attr) 322 return; 323 324 // The number of formal parameters of the declaration. 325 unsigned numFormalParams; 326 327 // The kind of declaration. This is also an index into a %select in 328 // the diagnostic. 329 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 330 331 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 332 numFormalParams = MD->param_size(); 333 calleeType = CT_Method; 334 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 335 numFormalParams = FD->param_size(); 336 calleeType = CT_Function; 337 } else if (isa<VarDecl>(D)) { 338 QualType type = cast<ValueDecl>(D)->getType(); 339 const FunctionType *fn = 0; 340 if (const PointerType *ptr = type->getAs<PointerType>()) { 341 fn = ptr->getPointeeType()->getAs<FunctionType>(); 342 if (!fn) return; 343 calleeType = CT_Function; 344 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 345 fn = ptr->getPointeeType()->castAs<FunctionType>(); 346 calleeType = CT_Block; 347 } else { 348 return; 349 } 350 351 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 352 numFormalParams = proto->getNumArgs(); 353 } else { 354 numFormalParams = 0; 355 } 356 } else { 357 return; 358 } 359 360 // "nullPos" is the number of formal parameters at the end which 361 // effectively count as part of the variadic arguments. This is 362 // useful if you would prefer to not have *any* formal parameters, 363 // but the language forces you to have at least one. 364 unsigned nullPos = attr->getNullPos(); 365 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 366 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 367 368 // The number of arguments which should follow the sentinel. 369 unsigned numArgsAfterSentinel = attr->getSentinel(); 370 371 // If there aren't enough arguments for all the formal parameters, 372 // the sentinel, and the args after the sentinel, complain. 373 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 374 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 375 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType; 376 return; 377 } 378 379 // Otherwise, find the sentinel expression. 380 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 381 if (!sentinelExpr) return; 382 if (sentinelExpr->isValueDependent()) return; 383 if (Context.isSentinelNullExpr(sentinelExpr)) return; 384 385 // Pick a reasonable string to insert. Optimistically use 'nil' or 386 // 'NULL' if those are actually defined in the context. Only use 387 // 'nil' for ObjC methods, where it's much more likely that the 388 // variadic arguments form a list of object pointers. 389 SourceLocation MissingNilLoc 390 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd()); 391 std::string NullValue; 392 if (calleeType == CT_Method && 393 PP.getIdentifierInfo("nil")->hasMacroDefinition()) 394 NullValue = "nil"; 395 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition()) 396 NullValue = "NULL"; 397 else 398 NullValue = "(void*) 0"; 399 400 if (MissingNilLoc.isInvalid()) 401 Diag(Loc, diag::warn_missing_sentinel) << calleeType; 402 else 403 Diag(MissingNilLoc, diag::warn_missing_sentinel) 404 << calleeType 405 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 406 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType; 407 } 408 409 SourceRange Sema::getExprRange(Expr *E) const { 410 return E ? E->getSourceRange() : SourceRange(); 411 } 412 413 //===----------------------------------------------------------------------===// 414 // Standard Promotions and Conversions 415 //===----------------------------------------------------------------------===// 416 417 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 418 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) { 419 // Handle any placeholder expressions which made it here. 420 if (E->getType()->isPlaceholderType()) { 421 ExprResult result = CheckPlaceholderExpr(E); 422 if (result.isInvalid()) return ExprError(); 423 E = result.take(); 424 } 425 426 QualType Ty = E->getType(); 427 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 428 429 if (Ty->isFunctionType()) 430 E = ImpCastExprToType(E, Context.getPointerType(Ty), 431 CK_FunctionToPointerDecay).take(); 432 else if (Ty->isArrayType()) { 433 // In C90 mode, arrays only promote to pointers if the array expression is 434 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 435 // type 'array of type' is converted to an expression that has type 'pointer 436 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 437 // that has type 'array of type' ...". The relevant change is "an lvalue" 438 // (C90) to "an expression" (C99). 439 // 440 // C++ 4.2p1: 441 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 442 // T" can be converted to an rvalue of type "pointer to T". 443 // 444 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 445 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 446 CK_ArrayToPointerDecay).take(); 447 } 448 return Owned(E); 449 } 450 451 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 452 // Check to see if we are dereferencing a null pointer. If so, 453 // and if not volatile-qualified, this is undefined behavior that the 454 // optimizer will delete, so warn about it. People sometimes try to use this 455 // to get a deterministic trap and are surprised by clang's behavior. This 456 // only handles the pattern "*null", which is a very syntactic check. 457 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 458 if (UO->getOpcode() == UO_Deref && 459 UO->getSubExpr()->IgnoreParenCasts()-> 460 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 461 !UO->getType().isVolatileQualified()) { 462 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 463 S.PDiag(diag::warn_indirection_through_null) 464 << UO->getSubExpr()->getSourceRange()); 465 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 466 S.PDiag(diag::note_indirection_through_null)); 467 } 468 } 469 470 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 471 SourceLocation AssignLoc, 472 const Expr* RHS) { 473 const ObjCIvarDecl *IV = OIRE->getDecl(); 474 if (!IV) 475 return; 476 477 DeclarationName MemberName = IV->getDeclName(); 478 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 479 if (!Member || !Member->isStr("isa")) 480 return; 481 482 const Expr *Base = OIRE->getBase(); 483 QualType BaseType = Base->getType(); 484 if (OIRE->isArrow()) 485 BaseType = BaseType->getPointeeType(); 486 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 487 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 488 ObjCInterfaceDecl *ClassDeclared = 0; 489 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 490 if (!ClassDeclared->getSuperClass() 491 && (*ClassDeclared->ivar_begin()) == IV) { 492 if (RHS) { 493 NamedDecl *ObjectSetClass = 494 S.LookupSingleName(S.TUScope, 495 &S.Context.Idents.get("object_setClass"), 496 SourceLocation(), S.LookupOrdinaryName); 497 if (ObjectSetClass) { 498 SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd()); 499 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 500 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 501 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 502 AssignLoc), ",") << 503 FixItHint::CreateInsertion(RHSLocEnd, ")"); 504 } 505 else 506 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 507 } else { 508 NamedDecl *ObjectGetClass = 509 S.LookupSingleName(S.TUScope, 510 &S.Context.Idents.get("object_getClass"), 511 SourceLocation(), S.LookupOrdinaryName); 512 if (ObjectGetClass) 513 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 514 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 515 FixItHint::CreateReplacement( 516 SourceRange(OIRE->getOpLoc(), 517 OIRE->getLocEnd()), ")"); 518 else 519 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 520 } 521 S.Diag(IV->getLocation(), diag::note_ivar_decl); 522 } 523 } 524 } 525 526 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 527 // Handle any placeholder expressions which made it here. 528 if (E->getType()->isPlaceholderType()) { 529 ExprResult result = CheckPlaceholderExpr(E); 530 if (result.isInvalid()) return ExprError(); 531 E = result.take(); 532 } 533 534 // C++ [conv.lval]p1: 535 // A glvalue of a non-function, non-array type T can be 536 // converted to a prvalue. 537 if (!E->isGLValue()) return Owned(E); 538 539 QualType T = E->getType(); 540 assert(!T.isNull() && "r-value conversion on typeless expression?"); 541 542 // We don't want to throw lvalue-to-rvalue casts on top of 543 // expressions of certain types in C++. 544 if (getLangOpts().CPlusPlus && 545 (E->getType() == Context.OverloadTy || 546 T->isDependentType() || 547 T->isRecordType())) 548 return Owned(E); 549 550 // The C standard is actually really unclear on this point, and 551 // DR106 tells us what the result should be but not why. It's 552 // generally best to say that void types just doesn't undergo 553 // lvalue-to-rvalue at all. Note that expressions of unqualified 554 // 'void' type are never l-values, but qualified void can be. 555 if (T->isVoidType()) 556 return Owned(E); 557 558 // OpenCL usually rejects direct accesses to values of 'half' type. 559 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 560 T->isHalfType()) { 561 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 562 << 0 << T; 563 return ExprError(); 564 } 565 566 CheckForNullPointerDereference(*this, E); 567 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 568 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 569 &Context.Idents.get("object_getClass"), 570 SourceLocation(), LookupOrdinaryName); 571 if (ObjectGetClass) 572 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 573 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 574 FixItHint::CreateReplacement( 575 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 576 else 577 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 578 } 579 else if (const ObjCIvarRefExpr *OIRE = 580 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 581 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/0); 582 583 // C++ [conv.lval]p1: 584 // [...] If T is a non-class type, the type of the prvalue is the 585 // cv-unqualified version of T. Otherwise, the type of the 586 // rvalue is T. 587 // 588 // C99 6.3.2.1p2: 589 // If the lvalue has qualified type, the value has the unqualified 590 // version of the type of the lvalue; otherwise, the value has the 591 // type of the lvalue. 592 if (T.hasQualifiers()) 593 T = T.getUnqualifiedType(); 594 595 UpdateMarkingForLValueToRValue(E); 596 597 // Loading a __weak object implicitly retains the value, so we need a cleanup to 598 // balance that. 599 if (getLangOpts().ObjCAutoRefCount && 600 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 601 ExprNeedsCleanups = true; 602 603 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, 604 E, 0, VK_RValue)); 605 606 // C11 6.3.2.1p2: 607 // ... if the lvalue has atomic type, the value has the non-atomic version 608 // of the type of the lvalue ... 609 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 610 T = Atomic->getValueType().getUnqualifiedType(); 611 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, 612 Res.get(), 0, VK_RValue)); 613 } 614 615 return Res; 616 } 617 618 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) { 619 ExprResult Res = DefaultFunctionArrayConversion(E); 620 if (Res.isInvalid()) 621 return ExprError(); 622 Res = DefaultLvalueConversion(Res.take()); 623 if (Res.isInvalid()) 624 return ExprError(); 625 return Res; 626 } 627 628 629 /// UsualUnaryConversions - Performs various conversions that are common to most 630 /// operators (C99 6.3). The conversions of array and function types are 631 /// sometimes suppressed. For example, the array->pointer conversion doesn't 632 /// apply if the array is an argument to the sizeof or address (&) operators. 633 /// In these instances, this routine should *not* be called. 634 ExprResult Sema::UsualUnaryConversions(Expr *E) { 635 // First, convert to an r-value. 636 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 637 if (Res.isInvalid()) 638 return ExprError(); 639 E = Res.take(); 640 641 QualType Ty = E->getType(); 642 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 643 644 // Half FP have to be promoted to float unless it is natively supported 645 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 646 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast); 647 648 // Try to perform integral promotions if the object has a theoretically 649 // promotable type. 650 if (Ty->isIntegralOrUnscopedEnumerationType()) { 651 // C99 6.3.1.1p2: 652 // 653 // The following may be used in an expression wherever an int or 654 // unsigned int may be used: 655 // - an object or expression with an integer type whose integer 656 // conversion rank is less than or equal to the rank of int 657 // and unsigned int. 658 // - A bit-field of type _Bool, int, signed int, or unsigned int. 659 // 660 // If an int can represent all values of the original type, the 661 // value is converted to an int; otherwise, it is converted to an 662 // unsigned int. These are called the integer promotions. All 663 // other types are unchanged by the integer promotions. 664 665 QualType PTy = Context.isPromotableBitField(E); 666 if (!PTy.isNull()) { 667 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take(); 668 return Owned(E); 669 } 670 if (Ty->isPromotableIntegerType()) { 671 QualType PT = Context.getPromotedIntegerType(Ty); 672 E = ImpCastExprToType(E, PT, CK_IntegralCast).take(); 673 return Owned(E); 674 } 675 } 676 return Owned(E); 677 } 678 679 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 680 /// do not have a prototype. Arguments that have type float or __fp16 681 /// are promoted to double. All other argument types are converted by 682 /// UsualUnaryConversions(). 683 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 684 QualType Ty = E->getType(); 685 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 686 687 ExprResult Res = UsualUnaryConversions(E); 688 if (Res.isInvalid()) 689 return ExprError(); 690 E = Res.take(); 691 692 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 693 // double. 694 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 695 if (BTy && (BTy->getKind() == BuiltinType::Half || 696 BTy->getKind() == BuiltinType::Float)) 697 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take(); 698 699 // C++ performs lvalue-to-rvalue conversion as a default argument 700 // promotion, even on class types, but note: 701 // C++11 [conv.lval]p2: 702 // When an lvalue-to-rvalue conversion occurs in an unevaluated 703 // operand or a subexpression thereof the value contained in the 704 // referenced object is not accessed. Otherwise, if the glvalue 705 // has a class type, the conversion copy-initializes a temporary 706 // of type T from the glvalue and the result of the conversion 707 // is a prvalue for the temporary. 708 // FIXME: add some way to gate this entire thing for correctness in 709 // potentially potentially evaluated contexts. 710 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 711 ExprResult Temp = PerformCopyInitialization( 712 InitializedEntity::InitializeTemporary(E->getType()), 713 E->getExprLoc(), 714 Owned(E)); 715 if (Temp.isInvalid()) 716 return ExprError(); 717 E = Temp.get(); 718 } 719 720 return Owned(E); 721 } 722 723 /// Determine the degree of POD-ness for an expression. 724 /// Incomplete types are considered POD, since this check can be performed 725 /// when we're in an unevaluated context. 726 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 727 if (Ty->isIncompleteType()) { 728 if (Ty->isObjCObjectType()) 729 return VAK_Invalid; 730 return VAK_Valid; 731 } 732 733 if (Ty.isCXX98PODType(Context)) 734 return VAK_Valid; 735 736 // C++11 [expr.call]p7: 737 // Passing a potentially-evaluated argument of class type (Clause 9) 738 // having a non-trivial copy constructor, a non-trivial move constructor, 739 // or a non-trivial destructor, with no corresponding parameter, 740 // is conditionally-supported with implementation-defined semantics. 741 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 742 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 743 if (!Record->hasNonTrivialCopyConstructor() && 744 !Record->hasNonTrivialMoveConstructor() && 745 !Record->hasNonTrivialDestructor()) 746 return VAK_ValidInCXX11; 747 748 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 749 return VAK_Valid; 750 return VAK_Invalid; 751 } 752 753 bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) { 754 // Don't allow one to pass an Objective-C interface to a vararg. 755 const QualType & Ty = E->getType(); 756 757 // Complain about passing non-POD types through varargs. 758 switch (isValidVarArgType(Ty)) { 759 case VAK_Valid: 760 break; 761 case VAK_ValidInCXX11: 762 DiagRuntimeBehavior(E->getLocStart(), 0, 763 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 764 << E->getType() << CT); 765 break; 766 case VAK_Invalid: { 767 if (Ty->isObjCObjectType()) 768 return DiagRuntimeBehavior(E->getLocStart(), 0, 769 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 770 << Ty << CT); 771 772 return DiagRuntimeBehavior(E->getLocStart(), 0, 773 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 774 << getLangOpts().CPlusPlus11 << Ty << CT); 775 } 776 } 777 // c++ rules are enforced elsewhere. 778 return false; 779 } 780 781 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 782 /// will create a trap if the resulting type is not a POD type. 783 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 784 FunctionDecl *FDecl) { 785 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 786 // Strip the unbridged-cast placeholder expression off, if applicable. 787 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 788 (CT == VariadicMethod || 789 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 790 E = stripARCUnbridgedCast(E); 791 792 // Otherwise, do normal placeholder checking. 793 } else { 794 ExprResult ExprRes = CheckPlaceholderExpr(E); 795 if (ExprRes.isInvalid()) 796 return ExprError(); 797 E = ExprRes.take(); 798 } 799 } 800 801 ExprResult ExprRes = DefaultArgumentPromotion(E); 802 if (ExprRes.isInvalid()) 803 return ExprError(); 804 E = ExprRes.take(); 805 806 // Diagnostics regarding non-POD argument types are 807 // emitted along with format string checking in Sema::CheckFunctionCall(). 808 if (isValidVarArgType(E->getType()) == VAK_Invalid) { 809 // Turn this into a trap. 810 CXXScopeSpec SS; 811 SourceLocation TemplateKWLoc; 812 UnqualifiedId Name; 813 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 814 E->getLocStart()); 815 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 816 Name, true, false); 817 if (TrapFn.isInvalid()) 818 return ExprError(); 819 820 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 821 E->getLocStart(), None, 822 E->getLocEnd()); 823 if (Call.isInvalid()) 824 return ExprError(); 825 826 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 827 Call.get(), E); 828 if (Comma.isInvalid()) 829 return ExprError(); 830 return Comma.get(); 831 } 832 833 if (!getLangOpts().CPlusPlus && 834 RequireCompleteType(E->getExprLoc(), E->getType(), 835 diag::err_call_incomplete_argument)) 836 return ExprError(); 837 838 return Owned(E); 839 } 840 841 /// \brief Converts an integer to complex float type. Helper function of 842 /// UsualArithmeticConversions() 843 /// 844 /// \return false if the integer expression is an integer type and is 845 /// successfully converted to the complex type. 846 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 847 ExprResult &ComplexExpr, 848 QualType IntTy, 849 QualType ComplexTy, 850 bool SkipCast) { 851 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 852 if (SkipCast) return false; 853 if (IntTy->isIntegerType()) { 854 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 855 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating); 856 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy, 857 CK_FloatingRealToComplex); 858 } else { 859 assert(IntTy->isComplexIntegerType()); 860 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy, 861 CK_IntegralComplexToFloatingComplex); 862 } 863 return false; 864 } 865 866 /// \brief Takes two complex float types and converts them to the same type. 867 /// Helper function of UsualArithmeticConversions() 868 static QualType 869 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS, 870 ExprResult &RHS, QualType LHSType, 871 QualType RHSType, 872 bool IsCompAssign) { 873 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 874 875 if (order < 0) { 876 // _Complex float -> _Complex double 877 if (!IsCompAssign) 878 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast); 879 return RHSType; 880 } 881 if (order > 0) 882 // _Complex float -> _Complex double 883 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast); 884 return LHSType; 885 } 886 887 /// \brief Converts otherExpr to complex float and promotes complexExpr if 888 /// necessary. Helper function of UsualArithmeticConversions() 889 static QualType handleOtherComplexFloatConversion(Sema &S, 890 ExprResult &ComplexExpr, 891 ExprResult &OtherExpr, 892 QualType ComplexTy, 893 QualType OtherTy, 894 bool ConvertComplexExpr, 895 bool ConvertOtherExpr) { 896 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy); 897 898 // If just the complexExpr is complex, the otherExpr needs to be converted, 899 // and the complexExpr might need to be promoted. 900 if (order > 0) { // complexExpr is wider 901 // float -> _Complex double 902 if (ConvertOtherExpr) { 903 QualType fp = cast<ComplexType>(ComplexTy)->getElementType(); 904 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast); 905 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy, 906 CK_FloatingRealToComplex); 907 } 908 return ComplexTy; 909 } 910 911 // otherTy is at least as wide. Find its corresponding complex type. 912 QualType result = (order == 0 ? ComplexTy : 913 S.Context.getComplexType(OtherTy)); 914 915 // double -> _Complex double 916 if (ConvertOtherExpr) 917 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result, 918 CK_FloatingRealToComplex); 919 920 // _Complex float -> _Complex double 921 if (ConvertComplexExpr && order < 0) 922 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result, 923 CK_FloatingComplexCast); 924 925 return result; 926 } 927 928 /// \brief Handle arithmetic conversion with complex types. Helper function of 929 /// UsualArithmeticConversions() 930 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 931 ExprResult &RHS, QualType LHSType, 932 QualType RHSType, 933 bool IsCompAssign) { 934 // if we have an integer operand, the result is the complex type. 935 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 936 /*skipCast*/false)) 937 return LHSType; 938 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 939 /*skipCast*/IsCompAssign)) 940 return RHSType; 941 942 // This handles complex/complex, complex/float, or float/complex. 943 // When both operands are complex, the shorter operand is converted to the 944 // type of the longer, and that is the type of the result. This corresponds 945 // to what is done when combining two real floating-point operands. 946 // The fun begins when size promotion occur across type domains. 947 // From H&S 6.3.4: When one operand is complex and the other is a real 948 // floating-point type, the less precise type is converted, within it's 949 // real or complex domain, to the precision of the other type. For example, 950 // when combining a "long double" with a "double _Complex", the 951 // "double _Complex" is promoted to "long double _Complex". 952 953 bool LHSComplexFloat = LHSType->isComplexType(); 954 bool RHSComplexFloat = RHSType->isComplexType(); 955 956 // If both are complex, just cast to the more precise type. 957 if (LHSComplexFloat && RHSComplexFloat) 958 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS, 959 LHSType, RHSType, 960 IsCompAssign); 961 962 // If only one operand is complex, promote it if necessary and convert the 963 // other operand to complex. 964 if (LHSComplexFloat) 965 return handleOtherComplexFloatConversion( 966 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign, 967 /*convertOtherExpr*/ true); 968 969 assert(RHSComplexFloat); 970 return handleOtherComplexFloatConversion( 971 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true, 972 /*convertOtherExpr*/ !IsCompAssign); 973 } 974 975 /// \brief Hande arithmetic conversion from integer to float. Helper function 976 /// of UsualArithmeticConversions() 977 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 978 ExprResult &IntExpr, 979 QualType FloatTy, QualType IntTy, 980 bool ConvertFloat, bool ConvertInt) { 981 if (IntTy->isIntegerType()) { 982 if (ConvertInt) 983 // Convert intExpr to the lhs floating point type. 984 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy, 985 CK_IntegralToFloating); 986 return FloatTy; 987 } 988 989 // Convert both sides to the appropriate complex float. 990 assert(IntTy->isComplexIntegerType()); 991 QualType result = S.Context.getComplexType(FloatTy); 992 993 // _Complex int -> _Complex float 994 if (ConvertInt) 995 IntExpr = S.ImpCastExprToType(IntExpr.take(), result, 996 CK_IntegralComplexToFloatingComplex); 997 998 // float -> _Complex float 999 if (ConvertFloat) 1000 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result, 1001 CK_FloatingRealToComplex); 1002 1003 return result; 1004 } 1005 1006 /// \brief Handle arithmethic conversion with floating point types. Helper 1007 /// function of UsualArithmeticConversions() 1008 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1009 ExprResult &RHS, QualType LHSType, 1010 QualType RHSType, bool IsCompAssign) { 1011 bool LHSFloat = LHSType->isRealFloatingType(); 1012 bool RHSFloat = RHSType->isRealFloatingType(); 1013 1014 // If we have two real floating types, convert the smaller operand 1015 // to the bigger result. 1016 if (LHSFloat && RHSFloat) { 1017 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1018 if (order > 0) { 1019 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast); 1020 return LHSType; 1021 } 1022 1023 assert(order < 0 && "illegal float comparison"); 1024 if (!IsCompAssign) 1025 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast); 1026 return RHSType; 1027 } 1028 1029 if (LHSFloat) 1030 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1031 /*convertFloat=*/!IsCompAssign, 1032 /*convertInt=*/ true); 1033 assert(RHSFloat); 1034 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1035 /*convertInt=*/ true, 1036 /*convertFloat=*/!IsCompAssign); 1037 } 1038 1039 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1040 1041 namespace { 1042 /// These helper callbacks are placed in an anonymous namespace to 1043 /// permit their use as function template parameters. 1044 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1045 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1046 } 1047 1048 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1049 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1050 CK_IntegralComplexCast); 1051 } 1052 } 1053 1054 /// \brief Handle integer arithmetic conversions. Helper function of 1055 /// UsualArithmeticConversions() 1056 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1057 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1058 ExprResult &RHS, QualType LHSType, 1059 QualType RHSType, bool IsCompAssign) { 1060 // The rules for this case are in C99 6.3.1.8 1061 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1062 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1063 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1064 if (LHSSigned == RHSSigned) { 1065 // Same signedness; use the higher-ranked type 1066 if (order >= 0) { 1067 RHS = (*doRHSCast)(S, RHS.take(), LHSType); 1068 return LHSType; 1069 } else if (!IsCompAssign) 1070 LHS = (*doLHSCast)(S, LHS.take(), RHSType); 1071 return RHSType; 1072 } else if (order != (LHSSigned ? 1 : -1)) { 1073 // The unsigned type has greater than or equal rank to the 1074 // signed type, so use the unsigned type 1075 if (RHSSigned) { 1076 RHS = (*doRHSCast)(S, RHS.take(), LHSType); 1077 return LHSType; 1078 } else if (!IsCompAssign) 1079 LHS = (*doLHSCast)(S, LHS.take(), RHSType); 1080 return RHSType; 1081 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1082 // The two types are different widths; if we are here, that 1083 // means the signed type is larger than the unsigned type, so 1084 // use the signed type. 1085 if (LHSSigned) { 1086 RHS = (*doRHSCast)(S, RHS.take(), LHSType); 1087 return LHSType; 1088 } else if (!IsCompAssign) 1089 LHS = (*doLHSCast)(S, LHS.take(), RHSType); 1090 return RHSType; 1091 } else { 1092 // The signed type is higher-ranked than the unsigned type, 1093 // but isn't actually any bigger (like unsigned int and long 1094 // on most 32-bit systems). Use the unsigned type corresponding 1095 // to the signed type. 1096 QualType result = 1097 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1098 RHS = (*doRHSCast)(S, RHS.take(), result); 1099 if (!IsCompAssign) 1100 LHS = (*doLHSCast)(S, LHS.take(), result); 1101 return result; 1102 } 1103 } 1104 1105 /// \brief Handle conversions with GCC complex int extension. Helper function 1106 /// of UsualArithmeticConversions() 1107 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1108 ExprResult &RHS, QualType LHSType, 1109 QualType RHSType, 1110 bool IsCompAssign) { 1111 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1112 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1113 1114 if (LHSComplexInt && RHSComplexInt) { 1115 QualType LHSEltType = LHSComplexInt->getElementType(); 1116 QualType RHSEltType = RHSComplexInt->getElementType(); 1117 QualType ScalarType = 1118 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1119 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1120 1121 return S.Context.getComplexType(ScalarType); 1122 } 1123 1124 if (LHSComplexInt) { 1125 QualType LHSEltType = LHSComplexInt->getElementType(); 1126 QualType ScalarType = 1127 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1128 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1129 QualType ComplexType = S.Context.getComplexType(ScalarType); 1130 RHS = S.ImpCastExprToType(RHS.take(), ComplexType, 1131 CK_IntegralRealToComplex); 1132 1133 return ComplexType; 1134 } 1135 1136 assert(RHSComplexInt); 1137 1138 QualType RHSEltType = RHSComplexInt->getElementType(); 1139 QualType ScalarType = 1140 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1141 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1142 QualType ComplexType = S.Context.getComplexType(ScalarType); 1143 1144 if (!IsCompAssign) 1145 LHS = S.ImpCastExprToType(LHS.take(), ComplexType, 1146 CK_IntegralRealToComplex); 1147 return ComplexType; 1148 } 1149 1150 /// UsualArithmeticConversions - Performs various conversions that are common to 1151 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1152 /// routine returns the first non-arithmetic type found. The client is 1153 /// responsible for emitting appropriate error diagnostics. 1154 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1155 bool IsCompAssign) { 1156 if (!IsCompAssign) { 1157 LHS = UsualUnaryConversions(LHS.take()); 1158 if (LHS.isInvalid()) 1159 return QualType(); 1160 } 1161 1162 RHS = UsualUnaryConversions(RHS.take()); 1163 if (RHS.isInvalid()) 1164 return QualType(); 1165 1166 // For conversion purposes, we ignore any qualifiers. 1167 // For example, "const float" and "float" are equivalent. 1168 QualType LHSType = 1169 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1170 QualType RHSType = 1171 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1172 1173 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1174 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1175 LHSType = AtomicLHS->getValueType(); 1176 1177 // If both types are identical, no conversion is needed. 1178 if (LHSType == RHSType) 1179 return LHSType; 1180 1181 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1182 // The caller can deal with this (e.g. pointer + int). 1183 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1184 return QualType(); 1185 1186 // Apply unary and bitfield promotions to the LHS's type. 1187 QualType LHSUnpromotedType = LHSType; 1188 if (LHSType->isPromotableIntegerType()) 1189 LHSType = Context.getPromotedIntegerType(LHSType); 1190 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1191 if (!LHSBitfieldPromoteTy.isNull()) 1192 LHSType = LHSBitfieldPromoteTy; 1193 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1194 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast); 1195 1196 // If both types are identical, no conversion is needed. 1197 if (LHSType == RHSType) 1198 return LHSType; 1199 1200 // At this point, we have two different arithmetic types. 1201 1202 // Handle complex types first (C99 6.3.1.8p1). 1203 if (LHSType->isComplexType() || RHSType->isComplexType()) 1204 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1205 IsCompAssign); 1206 1207 // Now handle "real" floating types (i.e. float, double, long double). 1208 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1209 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1210 IsCompAssign); 1211 1212 // Handle GCC complex int extension. 1213 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1214 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1215 IsCompAssign); 1216 1217 // Finally, we have two differing integer types. 1218 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1219 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1220 } 1221 1222 1223 //===----------------------------------------------------------------------===// 1224 // Semantic Analysis for various Expression Types 1225 //===----------------------------------------------------------------------===// 1226 1227 1228 ExprResult 1229 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1230 SourceLocation DefaultLoc, 1231 SourceLocation RParenLoc, 1232 Expr *ControllingExpr, 1233 ArrayRef<ParsedType> ArgTypes, 1234 ArrayRef<Expr *> ArgExprs) { 1235 unsigned NumAssocs = ArgTypes.size(); 1236 assert(NumAssocs == ArgExprs.size()); 1237 1238 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1239 for (unsigned i = 0; i < NumAssocs; ++i) { 1240 if (ArgTypes[i]) 1241 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1242 else 1243 Types[i] = 0; 1244 } 1245 1246 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1247 ControllingExpr, 1248 llvm::makeArrayRef(Types, NumAssocs), 1249 ArgExprs); 1250 delete [] Types; 1251 return ER; 1252 } 1253 1254 ExprResult 1255 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1256 SourceLocation DefaultLoc, 1257 SourceLocation RParenLoc, 1258 Expr *ControllingExpr, 1259 ArrayRef<TypeSourceInfo *> Types, 1260 ArrayRef<Expr *> Exprs) { 1261 unsigned NumAssocs = Types.size(); 1262 assert(NumAssocs == Exprs.size()); 1263 if (ControllingExpr->getType()->isPlaceholderType()) { 1264 ExprResult result = CheckPlaceholderExpr(ControllingExpr); 1265 if (result.isInvalid()) return ExprError(); 1266 ControllingExpr = result.take(); 1267 } 1268 1269 bool TypeErrorFound = false, 1270 IsResultDependent = ControllingExpr->isTypeDependent(), 1271 ContainsUnexpandedParameterPack 1272 = ControllingExpr->containsUnexpandedParameterPack(); 1273 1274 for (unsigned i = 0; i < NumAssocs; ++i) { 1275 if (Exprs[i]->containsUnexpandedParameterPack()) 1276 ContainsUnexpandedParameterPack = true; 1277 1278 if (Types[i]) { 1279 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1280 ContainsUnexpandedParameterPack = true; 1281 1282 if (Types[i]->getType()->isDependentType()) { 1283 IsResultDependent = true; 1284 } else { 1285 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1286 // complete object type other than a variably modified type." 1287 unsigned D = 0; 1288 if (Types[i]->getType()->isIncompleteType()) 1289 D = diag::err_assoc_type_incomplete; 1290 else if (!Types[i]->getType()->isObjectType()) 1291 D = diag::err_assoc_type_nonobject; 1292 else if (Types[i]->getType()->isVariablyModifiedType()) 1293 D = diag::err_assoc_type_variably_modified; 1294 1295 if (D != 0) { 1296 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1297 << Types[i]->getTypeLoc().getSourceRange() 1298 << Types[i]->getType(); 1299 TypeErrorFound = true; 1300 } 1301 1302 // C11 6.5.1.1p2 "No two generic associations in the same generic 1303 // selection shall specify compatible types." 1304 for (unsigned j = i+1; j < NumAssocs; ++j) 1305 if (Types[j] && !Types[j]->getType()->isDependentType() && 1306 Context.typesAreCompatible(Types[i]->getType(), 1307 Types[j]->getType())) { 1308 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1309 diag::err_assoc_compatible_types) 1310 << Types[j]->getTypeLoc().getSourceRange() 1311 << Types[j]->getType() 1312 << Types[i]->getType(); 1313 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1314 diag::note_compat_assoc) 1315 << Types[i]->getTypeLoc().getSourceRange() 1316 << Types[i]->getType(); 1317 TypeErrorFound = true; 1318 } 1319 } 1320 } 1321 } 1322 if (TypeErrorFound) 1323 return ExprError(); 1324 1325 // If we determined that the generic selection is result-dependent, don't 1326 // try to compute the result expression. 1327 if (IsResultDependent) 1328 return Owned(new (Context) GenericSelectionExpr( 1329 Context, KeyLoc, ControllingExpr, 1330 Types, Exprs, 1331 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack)); 1332 1333 SmallVector<unsigned, 1> CompatIndices; 1334 unsigned DefaultIndex = -1U; 1335 for (unsigned i = 0; i < NumAssocs; ++i) { 1336 if (!Types[i]) 1337 DefaultIndex = i; 1338 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1339 Types[i]->getType())) 1340 CompatIndices.push_back(i); 1341 } 1342 1343 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1344 // type compatible with at most one of the types named in its generic 1345 // association list." 1346 if (CompatIndices.size() > 1) { 1347 // We strip parens here because the controlling expression is typically 1348 // parenthesized in macro definitions. 1349 ControllingExpr = ControllingExpr->IgnoreParens(); 1350 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1351 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1352 << (unsigned) CompatIndices.size(); 1353 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(), 1354 E = CompatIndices.end(); I != E; ++I) { 1355 Diag(Types[*I]->getTypeLoc().getBeginLoc(), 1356 diag::note_compat_assoc) 1357 << Types[*I]->getTypeLoc().getSourceRange() 1358 << Types[*I]->getType(); 1359 } 1360 return ExprError(); 1361 } 1362 1363 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1364 // its controlling expression shall have type compatible with exactly one of 1365 // the types named in its generic association list." 1366 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1367 // We strip parens here because the controlling expression is typically 1368 // parenthesized in macro definitions. 1369 ControllingExpr = ControllingExpr->IgnoreParens(); 1370 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1371 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1372 return ExprError(); 1373 } 1374 1375 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1376 // type name that is compatible with the type of the controlling expression, 1377 // then the result expression of the generic selection is the expression 1378 // in that generic association. Otherwise, the result expression of the 1379 // generic selection is the expression in the default generic association." 1380 unsigned ResultIndex = 1381 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1382 1383 return Owned(new (Context) GenericSelectionExpr( 1384 Context, KeyLoc, ControllingExpr, 1385 Types, Exprs, 1386 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack, 1387 ResultIndex)); 1388 } 1389 1390 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1391 /// location of the token and the offset of the ud-suffix within it. 1392 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1393 unsigned Offset) { 1394 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1395 S.getLangOpts()); 1396 } 1397 1398 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1399 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1400 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1401 IdentifierInfo *UDSuffix, 1402 SourceLocation UDSuffixLoc, 1403 ArrayRef<Expr*> Args, 1404 SourceLocation LitEndLoc) { 1405 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1406 1407 QualType ArgTy[2]; 1408 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1409 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1410 if (ArgTy[ArgIdx]->isArrayType()) 1411 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1412 } 1413 1414 DeclarationName OpName = 1415 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1416 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1417 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1418 1419 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1420 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1421 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error) 1422 return ExprError(); 1423 1424 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1425 } 1426 1427 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1428 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1429 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1430 /// multiple tokens. However, the common case is that StringToks points to one 1431 /// string. 1432 /// 1433 ExprResult 1434 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks, 1435 Scope *UDLScope) { 1436 assert(NumStringToks && "Must have at least one string!"); 1437 1438 StringLiteralParser Literal(StringToks, NumStringToks, PP); 1439 if (Literal.hadError) 1440 return ExprError(); 1441 1442 SmallVector<SourceLocation, 4> StringTokLocs; 1443 for (unsigned i = 0; i != NumStringToks; ++i) 1444 StringTokLocs.push_back(StringToks[i].getLocation()); 1445 1446 QualType StrTy = Context.CharTy; 1447 if (Literal.isWide()) 1448 StrTy = Context.getWideCharType(); 1449 else if (Literal.isUTF16()) 1450 StrTy = Context.Char16Ty; 1451 else if (Literal.isUTF32()) 1452 StrTy = Context.Char32Ty; 1453 else if (Literal.isPascal()) 1454 StrTy = Context.UnsignedCharTy; 1455 1456 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1457 if (Literal.isWide()) 1458 Kind = StringLiteral::Wide; 1459 else if (Literal.isUTF8()) 1460 Kind = StringLiteral::UTF8; 1461 else if (Literal.isUTF16()) 1462 Kind = StringLiteral::UTF16; 1463 else if (Literal.isUTF32()) 1464 Kind = StringLiteral::UTF32; 1465 1466 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1467 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1468 StrTy.addConst(); 1469 1470 // Get an array type for the string, according to C99 6.4.5. This includes 1471 // the nul terminator character as well as the string length for pascal 1472 // strings. 1473 StrTy = Context.getConstantArrayType(StrTy, 1474 llvm::APInt(32, Literal.GetNumStringChars()+1), 1475 ArrayType::Normal, 0); 1476 1477 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1478 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1479 Kind, Literal.Pascal, StrTy, 1480 &StringTokLocs[0], 1481 StringTokLocs.size()); 1482 if (Literal.getUDSuffix().empty()) 1483 return Owned(Lit); 1484 1485 // We're building a user-defined literal. 1486 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1487 SourceLocation UDSuffixLoc = 1488 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1489 Literal.getUDSuffixOffset()); 1490 1491 // Make sure we're allowed user-defined literals here. 1492 if (!UDLScope) 1493 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1494 1495 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1496 // operator "" X (str, len) 1497 QualType SizeType = Context.getSizeType(); 1498 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1499 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1500 StringTokLocs[0]); 1501 Expr *Args[] = { Lit, LenArg }; 1502 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 1503 Args, StringTokLocs.back()); 1504 } 1505 1506 ExprResult 1507 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1508 SourceLocation Loc, 1509 const CXXScopeSpec *SS) { 1510 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1511 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1512 } 1513 1514 /// BuildDeclRefExpr - Build an expression that references a 1515 /// declaration that does not require a closure capture. 1516 ExprResult 1517 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1518 const DeclarationNameInfo &NameInfo, 1519 const CXXScopeSpec *SS, NamedDecl *FoundD) { 1520 if (getLangOpts().CUDA) 1521 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 1522 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) { 1523 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller), 1524 CalleeTarget = IdentifyCUDATarget(Callee); 1525 if (CheckCUDATarget(CallerTarget, CalleeTarget)) { 1526 Diag(NameInfo.getLoc(), diag::err_ref_bad_target) 1527 << CalleeTarget << D->getIdentifier() << CallerTarget; 1528 Diag(D->getLocation(), diag::note_previous_decl) 1529 << D->getIdentifier(); 1530 return ExprError(); 1531 } 1532 } 1533 1534 bool refersToEnclosingScope = 1535 (CurContext != D->getDeclContext() && 1536 D->getDeclContext()->isFunctionOrMethod()); 1537 1538 DeclRefExpr *E = DeclRefExpr::Create(Context, 1539 SS ? SS->getWithLocInContext(Context) 1540 : NestedNameSpecifierLoc(), 1541 SourceLocation(), 1542 D, refersToEnclosingScope, 1543 NameInfo, Ty, VK, FoundD); 1544 1545 MarkDeclRefReferenced(E); 1546 1547 if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) && 1548 Ty.getObjCLifetime() == Qualifiers::OCL_Weak) { 1549 DiagnosticsEngine::Level Level = 1550 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 1551 E->getLocStart()); 1552 if (Level != DiagnosticsEngine::Ignored) 1553 getCurFunction()->recordUseOfWeak(E); 1554 } 1555 1556 // Just in case we're building an illegal pointer-to-member. 1557 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1558 if (FD && FD->isBitField()) 1559 E->setObjectKind(OK_BitField); 1560 1561 return Owned(E); 1562 } 1563 1564 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1565 /// possibly a list of template arguments. 1566 /// 1567 /// If this produces template arguments, it is permitted to call 1568 /// DecomposeTemplateName. 1569 /// 1570 /// This actually loses a lot of source location information for 1571 /// non-standard name kinds; we should consider preserving that in 1572 /// some way. 1573 void 1574 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1575 TemplateArgumentListInfo &Buffer, 1576 DeclarationNameInfo &NameInfo, 1577 const TemplateArgumentListInfo *&TemplateArgs) { 1578 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1579 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1580 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1581 1582 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1583 Id.TemplateId->NumArgs); 1584 translateTemplateArguments(TemplateArgsPtr, Buffer); 1585 1586 TemplateName TName = Id.TemplateId->Template.get(); 1587 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1588 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1589 TemplateArgs = &Buffer; 1590 } else { 1591 NameInfo = GetNameFromUnqualifiedId(Id); 1592 TemplateArgs = 0; 1593 } 1594 } 1595 1596 /// Diagnose an empty lookup. 1597 /// 1598 /// \return false if new lookup candidates were found 1599 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1600 CorrectionCandidateCallback &CCC, 1601 TemplateArgumentListInfo *ExplicitTemplateArgs, 1602 llvm::ArrayRef<Expr *> Args) { 1603 DeclarationName Name = R.getLookupName(); 1604 1605 unsigned diagnostic = diag::err_undeclared_var_use; 1606 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1607 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1608 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1609 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1610 diagnostic = diag::err_undeclared_use; 1611 diagnostic_suggest = diag::err_undeclared_use_suggest; 1612 } 1613 1614 // If the original lookup was an unqualified lookup, fake an 1615 // unqualified lookup. This is useful when (for example) the 1616 // original lookup would not have found something because it was a 1617 // dependent name. 1618 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty()) 1619 ? CurContext : 0; 1620 while (DC) { 1621 if (isa<CXXRecordDecl>(DC)) { 1622 LookupQualifiedName(R, DC); 1623 1624 if (!R.empty()) { 1625 // Don't give errors about ambiguities in this lookup. 1626 R.suppressDiagnostics(); 1627 1628 // During a default argument instantiation the CurContext points 1629 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1630 // function parameter list, hence add an explicit check. 1631 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1632 ActiveTemplateInstantiations.back().Kind == 1633 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1634 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1635 bool isInstance = CurMethod && 1636 CurMethod->isInstance() && 1637 DC == CurMethod->getParent() && !isDefaultArgument; 1638 1639 1640 // Give a code modification hint to insert 'this->'. 1641 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1642 // Actually quite difficult! 1643 if (getLangOpts().MicrosoftMode) 1644 diagnostic = diag::warn_found_via_dependent_bases_lookup; 1645 if (isInstance) { 1646 Diag(R.getNameLoc(), diagnostic) << Name 1647 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1648 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>( 1649 CallsUndergoingInstantiation.back()->getCallee()); 1650 1651 CXXMethodDecl *DepMethod; 1652 if (CurMethod->isDependentContext()) 1653 DepMethod = CurMethod; 1654 else if (CurMethod->getTemplatedKind() == 1655 FunctionDecl::TK_FunctionTemplateSpecialization) 1656 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()-> 1657 getInstantiatedFromMemberTemplate()->getTemplatedDecl()); 1658 else 1659 DepMethod = cast<CXXMethodDecl>( 1660 CurMethod->getInstantiatedFromMemberFunction()); 1661 assert(DepMethod && "No template pattern found"); 1662 1663 QualType DepThisType = DepMethod->getThisType(Context); 1664 CheckCXXThisCapture(R.getNameLoc()); 1665 CXXThisExpr *DepThis = new (Context) CXXThisExpr( 1666 R.getNameLoc(), DepThisType, false); 1667 TemplateArgumentListInfo TList; 1668 if (ULE->hasExplicitTemplateArgs()) 1669 ULE->copyTemplateArgumentsInto(TList); 1670 1671 CXXScopeSpec SS; 1672 SS.Adopt(ULE->getQualifierLoc()); 1673 CXXDependentScopeMemberExpr *DepExpr = 1674 CXXDependentScopeMemberExpr::Create( 1675 Context, DepThis, DepThisType, true, SourceLocation(), 1676 SS.getWithLocInContext(Context), 1677 ULE->getTemplateKeywordLoc(), 0, 1678 R.getLookupNameInfo(), 1679 ULE->hasExplicitTemplateArgs() ? &TList : 0); 1680 CallsUndergoingInstantiation.back()->setCallee(DepExpr); 1681 } else { 1682 Diag(R.getNameLoc(), diagnostic) << Name; 1683 } 1684 1685 // Do we really want to note all of these? 1686 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 1687 Diag((*I)->getLocation(), diag::note_dependent_var_use); 1688 1689 // Return true if we are inside a default argument instantiation 1690 // and the found name refers to an instance member function, otherwise 1691 // the function calling DiagnoseEmptyLookup will try to create an 1692 // implicit member call and this is wrong for default argument. 1693 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1694 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1695 return true; 1696 } 1697 1698 // Tell the callee to try to recover. 1699 return false; 1700 } 1701 1702 R.clear(); 1703 } 1704 1705 // In Microsoft mode, if we are performing lookup from within a friend 1706 // function definition declared at class scope then we must set 1707 // DC to the lexical parent to be able to search into the parent 1708 // class. 1709 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) && 1710 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1711 DC->getLexicalParent()->isRecord()) 1712 DC = DC->getLexicalParent(); 1713 else 1714 DC = DC->getParent(); 1715 } 1716 1717 // We didn't find anything, so try to correct for a typo. 1718 TypoCorrection Corrected; 1719 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 1720 S, &SS, CCC))) { 1721 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1722 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts())); 1723 R.setLookupName(Corrected.getCorrection()); 1724 1725 if (NamedDecl *ND = Corrected.getCorrectionDecl()) { 1726 if (Corrected.isOverloaded()) { 1727 OverloadCandidateSet OCS(R.getNameLoc()); 1728 OverloadCandidateSet::iterator Best; 1729 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 1730 CDEnd = Corrected.end(); 1731 CD != CDEnd; ++CD) { 1732 if (FunctionTemplateDecl *FTD = 1733 dyn_cast<FunctionTemplateDecl>(*CD)) 1734 AddTemplateOverloadCandidate( 1735 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1736 Args, OCS); 1737 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 1738 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1739 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1740 Args, OCS); 1741 } 1742 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1743 case OR_Success: 1744 ND = Best->Function; 1745 break; 1746 default: 1747 break; 1748 } 1749 } 1750 R.addDecl(ND); 1751 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) { 1752 if (SS.isEmpty()) 1753 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr 1754 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 1755 else 1756 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1757 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 1758 << SS.getRange() 1759 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(), 1760 CorrectedStr); 1761 1762 unsigned diag = isa<ImplicitParamDecl>(ND) 1763 ? diag::note_implicit_param_decl 1764 : diag::note_previous_decl; 1765 1766 Diag(ND->getLocation(), diag) 1767 << CorrectedQuotedStr; 1768 1769 // Tell the callee to try to recover. 1770 return false; 1771 } 1772 1773 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) { 1774 // FIXME: If we ended up with a typo for a type name or 1775 // Objective-C class name, we're in trouble because the parser 1776 // is in the wrong place to recover. Suggest the typo 1777 // correction, but don't make it a fix-it since we're not going 1778 // to recover well anyway. 1779 if (SS.isEmpty()) 1780 Diag(R.getNameLoc(), diagnostic_suggest) 1781 << Name << CorrectedQuotedStr; 1782 else 1783 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1784 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 1785 << SS.getRange(); 1786 1787 // Don't try to recover; it won't work. 1788 return true; 1789 } 1790 } else { 1791 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1792 // because we aren't able to recover. 1793 if (SS.isEmpty()) 1794 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr; 1795 else 1796 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1797 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 1798 << SS.getRange(); 1799 return true; 1800 } 1801 } 1802 R.clear(); 1803 1804 // Emit a special diagnostic for failed member lookups. 1805 // FIXME: computing the declaration context might fail here (?) 1806 if (!SS.isEmpty()) { 1807 Diag(R.getNameLoc(), diag::err_no_member) 1808 << Name << computeDeclContext(SS, false) 1809 << SS.getRange(); 1810 return true; 1811 } 1812 1813 // Give up, we can't recover. 1814 Diag(R.getNameLoc(), diagnostic) << Name; 1815 return true; 1816 } 1817 1818 ExprResult Sema::ActOnIdExpression(Scope *S, 1819 CXXScopeSpec &SS, 1820 SourceLocation TemplateKWLoc, 1821 UnqualifiedId &Id, 1822 bool HasTrailingLParen, 1823 bool IsAddressOfOperand, 1824 CorrectionCandidateCallback *CCC) { 1825 assert(!(IsAddressOfOperand && HasTrailingLParen) && 1826 "cannot be direct & operand and have a trailing lparen"); 1827 1828 if (SS.isInvalid()) 1829 return ExprError(); 1830 1831 TemplateArgumentListInfo TemplateArgsBuffer; 1832 1833 // Decompose the UnqualifiedId into the following data. 1834 DeclarationNameInfo NameInfo; 1835 const TemplateArgumentListInfo *TemplateArgs; 1836 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 1837 1838 DeclarationName Name = NameInfo.getName(); 1839 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1840 SourceLocation NameLoc = NameInfo.getLoc(); 1841 1842 // C++ [temp.dep.expr]p3: 1843 // An id-expression is type-dependent if it contains: 1844 // -- an identifier that was declared with a dependent type, 1845 // (note: handled after lookup) 1846 // -- a template-id that is dependent, 1847 // (note: handled in BuildTemplateIdExpr) 1848 // -- a conversion-function-id that specifies a dependent type, 1849 // -- a nested-name-specifier that contains a class-name that 1850 // names a dependent type. 1851 // Determine whether this is a member of an unknown specialization; 1852 // we need to handle these differently. 1853 bool DependentID = false; 1854 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 1855 Name.getCXXNameType()->isDependentType()) { 1856 DependentID = true; 1857 } else if (SS.isSet()) { 1858 if (DeclContext *DC = computeDeclContext(SS, false)) { 1859 if (RequireCompleteDeclContext(SS, DC)) 1860 return ExprError(); 1861 } else { 1862 DependentID = true; 1863 } 1864 } 1865 1866 if (DependentID) 1867 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1868 IsAddressOfOperand, TemplateArgs); 1869 1870 // Perform the required lookup. 1871 LookupResult R(*this, NameInfo, 1872 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 1873 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 1874 if (TemplateArgs) { 1875 // Lookup the template name again to correctly establish the context in 1876 // which it was found. This is really unfortunate as we already did the 1877 // lookup to determine that it was a template name in the first place. If 1878 // this becomes a performance hit, we can work harder to preserve those 1879 // results until we get here but it's likely not worth it. 1880 bool MemberOfUnknownSpecialization; 1881 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 1882 MemberOfUnknownSpecialization); 1883 1884 if (MemberOfUnknownSpecialization || 1885 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 1886 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1887 IsAddressOfOperand, TemplateArgs); 1888 } else { 1889 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 1890 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 1891 1892 // If the result might be in a dependent base class, this is a dependent 1893 // id-expression. 1894 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 1895 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1896 IsAddressOfOperand, TemplateArgs); 1897 1898 // If this reference is in an Objective-C method, then we need to do 1899 // some special Objective-C lookup, too. 1900 if (IvarLookupFollowUp) { 1901 ExprResult E(LookupInObjCMethod(R, S, II, true)); 1902 if (E.isInvalid()) 1903 return ExprError(); 1904 1905 if (Expr *Ex = E.takeAs<Expr>()) 1906 return Owned(Ex); 1907 } 1908 } 1909 1910 if (R.isAmbiguous()) 1911 return ExprError(); 1912 1913 // Determine whether this name might be a candidate for 1914 // argument-dependent lookup. 1915 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 1916 1917 if (R.empty() && !ADL) { 1918 // Otherwise, this could be an implicitly declared function reference (legal 1919 // in C90, extension in C99, forbidden in C++). 1920 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 1921 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 1922 if (D) R.addDecl(D); 1923 } 1924 1925 // If this name wasn't predeclared and if this is not a function 1926 // call, diagnose the problem. 1927 if (R.empty()) { 1928 // In Microsoft mode, if we are inside a template class member function 1929 // whose parent class has dependent base classes, and we can't resolve 1930 // an identifier, then assume the identifier is type dependent. The 1931 // goal is to postpone name lookup to instantiation time to be able to 1932 // search into the type dependent base classes. 1933 if (getLangOpts().MicrosoftMode) { 1934 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext); 1935 if (MD && MD->getParent()->hasAnyDependentBases()) 1936 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1937 IsAddressOfOperand, TemplateArgs); 1938 } 1939 1940 CorrectionCandidateCallback DefaultValidator; 1941 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator)) 1942 return ExprError(); 1943 1944 assert(!R.empty() && 1945 "DiagnoseEmptyLookup returned false but added no results"); 1946 1947 // If we found an Objective-C instance variable, let 1948 // LookupInObjCMethod build the appropriate expression to 1949 // reference the ivar. 1950 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 1951 R.clear(); 1952 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 1953 // In a hopelessly buggy code, Objective-C instance variable 1954 // lookup fails and no expression will be built to reference it. 1955 if (!E.isInvalid() && !E.get()) 1956 return ExprError(); 1957 return E; 1958 } 1959 } 1960 } 1961 1962 // This is guaranteed from this point on. 1963 assert(!R.empty() || ADL); 1964 1965 // Check whether this might be a C++ implicit instance member access. 1966 // C++ [class.mfct.non-static]p3: 1967 // When an id-expression that is not part of a class member access 1968 // syntax and not used to form a pointer to member is used in the 1969 // body of a non-static member function of class X, if name lookup 1970 // resolves the name in the id-expression to a non-static non-type 1971 // member of some class C, the id-expression is transformed into a 1972 // class member access expression using (*this) as the 1973 // postfix-expression to the left of the . operator. 1974 // 1975 // But we don't actually need to do this for '&' operands if R 1976 // resolved to a function or overloaded function set, because the 1977 // expression is ill-formed if it actually works out to be a 1978 // non-static member function: 1979 // 1980 // C++ [expr.ref]p4: 1981 // Otherwise, if E1.E2 refers to a non-static member function. . . 1982 // [t]he expression can be used only as the left-hand operand of a 1983 // member function call. 1984 // 1985 // There are other safeguards against such uses, but it's important 1986 // to get this right here so that we don't end up making a 1987 // spuriously dependent expression if we're inside a dependent 1988 // instance method. 1989 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 1990 bool MightBeImplicitMember; 1991 if (!IsAddressOfOperand) 1992 MightBeImplicitMember = true; 1993 else if (!SS.isEmpty()) 1994 MightBeImplicitMember = false; 1995 else if (R.isOverloadedResult()) 1996 MightBeImplicitMember = false; 1997 else if (R.isUnresolvableResult()) 1998 MightBeImplicitMember = true; 1999 else 2000 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2001 isa<IndirectFieldDecl>(R.getFoundDecl()); 2002 2003 if (MightBeImplicitMember) 2004 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2005 R, TemplateArgs); 2006 } 2007 2008 if (TemplateArgs || TemplateKWLoc.isValid()) 2009 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2010 2011 return BuildDeclarationNameExpr(SS, R, ADL); 2012 } 2013 2014 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2015 /// declaration name, generally during template instantiation. 2016 /// There's a large number of things which don't need to be done along 2017 /// this path. 2018 ExprResult 2019 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 2020 const DeclarationNameInfo &NameInfo, 2021 bool IsAddressOfOperand) { 2022 DeclContext *DC = computeDeclContext(SS, false); 2023 if (!DC) 2024 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2025 NameInfo, /*TemplateArgs=*/0); 2026 2027 if (RequireCompleteDeclContext(SS, DC)) 2028 return ExprError(); 2029 2030 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2031 LookupQualifiedName(R, DC); 2032 2033 if (R.isAmbiguous()) 2034 return ExprError(); 2035 2036 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2037 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2038 NameInfo, /*TemplateArgs=*/0); 2039 2040 if (R.empty()) { 2041 Diag(NameInfo.getLoc(), diag::err_no_member) 2042 << NameInfo.getName() << DC << SS.getRange(); 2043 return ExprError(); 2044 } 2045 2046 // Defend against this resolving to an implicit member access. We usually 2047 // won't get here if this might be a legitimate a class member (we end up in 2048 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2049 // a pointer-to-member or in an unevaluated context in C++11. 2050 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2051 return BuildPossibleImplicitMemberExpr(SS, 2052 /*TemplateKWLoc=*/SourceLocation(), 2053 R, /*TemplateArgs=*/0); 2054 2055 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2056 } 2057 2058 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2059 /// detected that we're currently inside an ObjC method. Perform some 2060 /// additional lookup. 2061 /// 2062 /// Ideally, most of this would be done by lookup, but there's 2063 /// actually quite a lot of extra work involved. 2064 /// 2065 /// Returns a null sentinel to indicate trivial success. 2066 ExprResult 2067 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2068 IdentifierInfo *II, bool AllowBuiltinCreation) { 2069 SourceLocation Loc = Lookup.getNameLoc(); 2070 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2071 2072 // Check for error condition which is already reported. 2073 if (!CurMethod) 2074 return ExprError(); 2075 2076 // There are two cases to handle here. 1) scoped lookup could have failed, 2077 // in which case we should look for an ivar. 2) scoped lookup could have 2078 // found a decl, but that decl is outside the current instance method (i.e. 2079 // a global variable). In these two cases, we do a lookup for an ivar with 2080 // this name, if the lookup sucedes, we replace it our current decl. 2081 2082 // If we're in a class method, we don't normally want to look for 2083 // ivars. But if we don't find anything else, and there's an 2084 // ivar, that's an error. 2085 bool IsClassMethod = CurMethod->isClassMethod(); 2086 2087 bool LookForIvars; 2088 if (Lookup.empty()) 2089 LookForIvars = true; 2090 else if (IsClassMethod) 2091 LookForIvars = false; 2092 else 2093 LookForIvars = (Lookup.isSingleResult() && 2094 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2095 ObjCInterfaceDecl *IFace = 0; 2096 if (LookForIvars) { 2097 IFace = CurMethod->getClassInterface(); 2098 ObjCInterfaceDecl *ClassDeclared; 2099 ObjCIvarDecl *IV = 0; 2100 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2101 // Diagnose using an ivar in a class method. 2102 if (IsClassMethod) 2103 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2104 << IV->getDeclName()); 2105 2106 // If we're referencing an invalid decl, just return this as a silent 2107 // error node. The error diagnostic was already emitted on the decl. 2108 if (IV->isInvalidDecl()) 2109 return ExprError(); 2110 2111 // Check if referencing a field with __attribute__((deprecated)). 2112 if (DiagnoseUseOfDecl(IV, Loc)) 2113 return ExprError(); 2114 2115 // Diagnose the use of an ivar outside of the declaring class. 2116 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2117 !declaresSameEntity(ClassDeclared, IFace) && 2118 !getLangOpts().DebuggerSupport) 2119 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2120 2121 // FIXME: This should use a new expr for a direct reference, don't 2122 // turn this into Self->ivar, just return a BareIVarExpr or something. 2123 IdentifierInfo &II = Context.Idents.get("self"); 2124 UnqualifiedId SelfName; 2125 SelfName.setIdentifier(&II, SourceLocation()); 2126 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2127 CXXScopeSpec SelfScopeSpec; 2128 SourceLocation TemplateKWLoc; 2129 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2130 SelfName, false, false); 2131 if (SelfExpr.isInvalid()) 2132 return ExprError(); 2133 2134 SelfExpr = DefaultLvalueConversion(SelfExpr.take()); 2135 if (SelfExpr.isInvalid()) 2136 return ExprError(); 2137 2138 MarkAnyDeclReferenced(Loc, IV, true); 2139 2140 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2141 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2142 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2143 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2144 2145 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(), 2146 Loc, IV->getLocation(), 2147 SelfExpr.take(), 2148 true, true); 2149 2150 if (getLangOpts().ObjCAutoRefCount) { 2151 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2152 DiagnosticsEngine::Level Level = 2153 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc); 2154 if (Level != DiagnosticsEngine::Ignored) 2155 getCurFunction()->recordUseOfWeak(Result); 2156 } 2157 if (CurContext->isClosure()) 2158 Diag(Loc, diag::warn_implicitly_retains_self) 2159 << FixItHint::CreateInsertion(Loc, "self->"); 2160 } 2161 2162 return Owned(Result); 2163 } 2164 } else if (CurMethod->isInstanceMethod()) { 2165 // We should warn if a local variable hides an ivar. 2166 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2167 ObjCInterfaceDecl *ClassDeclared; 2168 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2169 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2170 declaresSameEntity(IFace, ClassDeclared)) 2171 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2172 } 2173 } 2174 } else if (Lookup.isSingleResult() && 2175 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2176 // If accessing a stand-alone ivar in a class method, this is an error. 2177 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2178 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2179 << IV->getDeclName()); 2180 } 2181 2182 if (Lookup.empty() && II && AllowBuiltinCreation) { 2183 // FIXME. Consolidate this with similar code in LookupName. 2184 if (unsigned BuiltinID = II->getBuiltinID()) { 2185 if (!(getLangOpts().CPlusPlus && 2186 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2187 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2188 S, Lookup.isForRedeclaration(), 2189 Lookup.getNameLoc()); 2190 if (D) Lookup.addDecl(D); 2191 } 2192 } 2193 } 2194 // Sentinel value saying that we didn't do anything special. 2195 return Owned((Expr*) 0); 2196 } 2197 2198 /// \brief Cast a base object to a member's actual type. 2199 /// 2200 /// Logically this happens in three phases: 2201 /// 2202 /// * First we cast from the base type to the naming class. 2203 /// The naming class is the class into which we were looking 2204 /// when we found the member; it's the qualifier type if a 2205 /// qualifier was provided, and otherwise it's the base type. 2206 /// 2207 /// * Next we cast from the naming class to the declaring class. 2208 /// If the member we found was brought into a class's scope by 2209 /// a using declaration, this is that class; otherwise it's 2210 /// the class declaring the member. 2211 /// 2212 /// * Finally we cast from the declaring class to the "true" 2213 /// declaring class of the member. This conversion does not 2214 /// obey access control. 2215 ExprResult 2216 Sema::PerformObjectMemberConversion(Expr *From, 2217 NestedNameSpecifier *Qualifier, 2218 NamedDecl *FoundDecl, 2219 NamedDecl *Member) { 2220 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2221 if (!RD) 2222 return Owned(From); 2223 2224 QualType DestRecordType; 2225 QualType DestType; 2226 QualType FromRecordType; 2227 QualType FromType = From->getType(); 2228 bool PointerConversions = false; 2229 if (isa<FieldDecl>(Member)) { 2230 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2231 2232 if (FromType->getAs<PointerType>()) { 2233 DestType = Context.getPointerType(DestRecordType); 2234 FromRecordType = FromType->getPointeeType(); 2235 PointerConversions = true; 2236 } else { 2237 DestType = DestRecordType; 2238 FromRecordType = FromType; 2239 } 2240 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2241 if (Method->isStatic()) 2242 return Owned(From); 2243 2244 DestType = Method->getThisType(Context); 2245 DestRecordType = DestType->getPointeeType(); 2246 2247 if (FromType->getAs<PointerType>()) { 2248 FromRecordType = FromType->getPointeeType(); 2249 PointerConversions = true; 2250 } else { 2251 FromRecordType = FromType; 2252 DestType = DestRecordType; 2253 } 2254 } else { 2255 // No conversion necessary. 2256 return Owned(From); 2257 } 2258 2259 if (DestType->isDependentType() || FromType->isDependentType()) 2260 return Owned(From); 2261 2262 // If the unqualified types are the same, no conversion is necessary. 2263 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2264 return Owned(From); 2265 2266 SourceRange FromRange = From->getSourceRange(); 2267 SourceLocation FromLoc = FromRange.getBegin(); 2268 2269 ExprValueKind VK = From->getValueKind(); 2270 2271 // C++ [class.member.lookup]p8: 2272 // [...] Ambiguities can often be resolved by qualifying a name with its 2273 // class name. 2274 // 2275 // If the member was a qualified name and the qualified referred to a 2276 // specific base subobject type, we'll cast to that intermediate type 2277 // first and then to the object in which the member is declared. That allows 2278 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2279 // 2280 // class Base { public: int x; }; 2281 // class Derived1 : public Base { }; 2282 // class Derived2 : public Base { }; 2283 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2284 // 2285 // void VeryDerived::f() { 2286 // x = 17; // error: ambiguous base subobjects 2287 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2288 // } 2289 if (Qualifier) { 2290 QualType QType = QualType(Qualifier->getAsType(), 0); 2291 assert(!QType.isNull() && "lookup done with dependent qualifier?"); 2292 assert(QType->isRecordType() && "lookup done with non-record type"); 2293 2294 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2295 2296 // In C++98, the qualifier type doesn't actually have to be a base 2297 // type of the object type, in which case we just ignore it. 2298 // Otherwise build the appropriate casts. 2299 if (IsDerivedFrom(FromRecordType, QRecordType)) { 2300 CXXCastPath BasePath; 2301 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2302 FromLoc, FromRange, &BasePath)) 2303 return ExprError(); 2304 2305 if (PointerConversions) 2306 QType = Context.getPointerType(QType); 2307 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2308 VK, &BasePath).take(); 2309 2310 FromType = QType; 2311 FromRecordType = QRecordType; 2312 2313 // If the qualifier type was the same as the destination type, 2314 // we're done. 2315 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2316 return Owned(From); 2317 } 2318 } 2319 2320 bool IgnoreAccess = false; 2321 2322 // If we actually found the member through a using declaration, cast 2323 // down to the using declaration's type. 2324 // 2325 // Pointer equality is fine here because only one declaration of a 2326 // class ever has member declarations. 2327 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2328 assert(isa<UsingShadowDecl>(FoundDecl)); 2329 QualType URecordType = Context.getTypeDeclType( 2330 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2331 2332 // We only need to do this if the naming-class to declaring-class 2333 // conversion is non-trivial. 2334 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2335 assert(IsDerivedFrom(FromRecordType, URecordType)); 2336 CXXCastPath BasePath; 2337 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2338 FromLoc, FromRange, &BasePath)) 2339 return ExprError(); 2340 2341 QualType UType = URecordType; 2342 if (PointerConversions) 2343 UType = Context.getPointerType(UType); 2344 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2345 VK, &BasePath).take(); 2346 FromType = UType; 2347 FromRecordType = URecordType; 2348 } 2349 2350 // We don't do access control for the conversion from the 2351 // declaring class to the true declaring class. 2352 IgnoreAccess = true; 2353 } 2354 2355 CXXCastPath BasePath; 2356 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2357 FromLoc, FromRange, &BasePath, 2358 IgnoreAccess)) 2359 return ExprError(); 2360 2361 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2362 VK, &BasePath); 2363 } 2364 2365 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2366 const LookupResult &R, 2367 bool HasTrailingLParen) { 2368 // Only when used directly as the postfix-expression of a call. 2369 if (!HasTrailingLParen) 2370 return false; 2371 2372 // Never if a scope specifier was provided. 2373 if (SS.isSet()) 2374 return false; 2375 2376 // Only in C++ or ObjC++. 2377 if (!getLangOpts().CPlusPlus) 2378 return false; 2379 2380 // Turn off ADL when we find certain kinds of declarations during 2381 // normal lookup: 2382 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2383 NamedDecl *D = *I; 2384 2385 // C++0x [basic.lookup.argdep]p3: 2386 // -- a declaration of a class member 2387 // Since using decls preserve this property, we check this on the 2388 // original decl. 2389 if (D->isCXXClassMember()) 2390 return false; 2391 2392 // C++0x [basic.lookup.argdep]p3: 2393 // -- a block-scope function declaration that is not a 2394 // using-declaration 2395 // NOTE: we also trigger this for function templates (in fact, we 2396 // don't check the decl type at all, since all other decl types 2397 // turn off ADL anyway). 2398 if (isa<UsingShadowDecl>(D)) 2399 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2400 else if (D->getDeclContext()->isFunctionOrMethod()) 2401 return false; 2402 2403 // C++0x [basic.lookup.argdep]p3: 2404 // -- a declaration that is neither a function or a function 2405 // template 2406 // And also for builtin functions. 2407 if (isa<FunctionDecl>(D)) { 2408 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2409 2410 // But also builtin functions. 2411 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2412 return false; 2413 } else if (!isa<FunctionTemplateDecl>(D)) 2414 return false; 2415 } 2416 2417 return true; 2418 } 2419 2420 2421 /// Diagnoses obvious problems with the use of the given declaration 2422 /// as an expression. This is only actually called for lookups that 2423 /// were not overloaded, and it doesn't promise that the declaration 2424 /// will in fact be used. 2425 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2426 if (isa<TypedefNameDecl>(D)) { 2427 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2428 return true; 2429 } 2430 2431 if (isa<ObjCInterfaceDecl>(D)) { 2432 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2433 return true; 2434 } 2435 2436 if (isa<NamespaceDecl>(D)) { 2437 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2438 return true; 2439 } 2440 2441 return false; 2442 } 2443 2444 ExprResult 2445 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2446 LookupResult &R, 2447 bool NeedsADL) { 2448 // If this is a single, fully-resolved result and we don't need ADL, 2449 // just build an ordinary singleton decl ref. 2450 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2451 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2452 R.getRepresentativeDecl()); 2453 2454 // We only need to check the declaration if there's exactly one 2455 // result, because in the overloaded case the results can only be 2456 // functions and function templates. 2457 if (R.isSingleResult() && 2458 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2459 return ExprError(); 2460 2461 // Otherwise, just build an unresolved lookup expression. Suppress 2462 // any lookup-related diagnostics; we'll hash these out later, when 2463 // we've picked a target. 2464 R.suppressDiagnostics(); 2465 2466 UnresolvedLookupExpr *ULE 2467 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2468 SS.getWithLocInContext(Context), 2469 R.getLookupNameInfo(), 2470 NeedsADL, R.isOverloadedResult(), 2471 R.begin(), R.end()); 2472 2473 return Owned(ULE); 2474 } 2475 2476 /// \brief Complete semantic analysis for a reference to the given declaration. 2477 ExprResult 2478 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2479 const DeclarationNameInfo &NameInfo, 2480 NamedDecl *D, NamedDecl *FoundD) { 2481 assert(D && "Cannot refer to a NULL declaration"); 2482 assert(!isa<FunctionTemplateDecl>(D) && 2483 "Cannot refer unambiguously to a function template"); 2484 2485 SourceLocation Loc = NameInfo.getLoc(); 2486 if (CheckDeclInExpr(*this, Loc, D)) 2487 return ExprError(); 2488 2489 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2490 // Specifically diagnose references to class templates that are missing 2491 // a template argument list. 2492 Diag(Loc, diag::err_template_decl_ref) 2493 << Template << SS.getRange(); 2494 Diag(Template->getLocation(), diag::note_template_decl_here); 2495 return ExprError(); 2496 } 2497 2498 // Make sure that we're referring to a value. 2499 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2500 if (!VD) { 2501 Diag(Loc, diag::err_ref_non_value) 2502 << D << SS.getRange(); 2503 Diag(D->getLocation(), diag::note_declared_at); 2504 return ExprError(); 2505 } 2506 2507 // Check whether this declaration can be used. Note that we suppress 2508 // this check when we're going to perform argument-dependent lookup 2509 // on this function name, because this might not be the function 2510 // that overload resolution actually selects. 2511 if (DiagnoseUseOfDecl(VD, Loc)) 2512 return ExprError(); 2513 2514 // Only create DeclRefExpr's for valid Decl's. 2515 if (VD->isInvalidDecl()) 2516 return ExprError(); 2517 2518 // Handle members of anonymous structs and unions. If we got here, 2519 // and the reference is to a class member indirect field, then this 2520 // must be the subject of a pointer-to-member expression. 2521 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2522 if (!indirectField->isCXXClassMember()) 2523 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2524 indirectField); 2525 2526 { 2527 QualType type = VD->getType(); 2528 ExprValueKind valueKind = VK_RValue; 2529 2530 switch (D->getKind()) { 2531 // Ignore all the non-ValueDecl kinds. 2532 #define ABSTRACT_DECL(kind) 2533 #define VALUE(type, base) 2534 #define DECL(type, base) \ 2535 case Decl::type: 2536 #include "clang/AST/DeclNodes.inc" 2537 llvm_unreachable("invalid value decl kind"); 2538 2539 // These shouldn't make it here. 2540 case Decl::ObjCAtDefsField: 2541 case Decl::ObjCIvar: 2542 llvm_unreachable("forming non-member reference to ivar?"); 2543 2544 // Enum constants are always r-values and never references. 2545 // Unresolved using declarations are dependent. 2546 case Decl::EnumConstant: 2547 case Decl::UnresolvedUsingValue: 2548 valueKind = VK_RValue; 2549 break; 2550 2551 // Fields and indirect fields that got here must be for 2552 // pointer-to-member expressions; we just call them l-values for 2553 // internal consistency, because this subexpression doesn't really 2554 // exist in the high-level semantics. 2555 case Decl::Field: 2556 case Decl::IndirectField: 2557 assert(getLangOpts().CPlusPlus && 2558 "building reference to field in C?"); 2559 2560 // These can't have reference type in well-formed programs, but 2561 // for internal consistency we do this anyway. 2562 type = type.getNonReferenceType(); 2563 valueKind = VK_LValue; 2564 break; 2565 2566 // Non-type template parameters are either l-values or r-values 2567 // depending on the type. 2568 case Decl::NonTypeTemplateParm: { 2569 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2570 type = reftype->getPointeeType(); 2571 valueKind = VK_LValue; // even if the parameter is an r-value reference 2572 break; 2573 } 2574 2575 // For non-references, we need to strip qualifiers just in case 2576 // the template parameter was declared as 'const int' or whatever. 2577 valueKind = VK_RValue; 2578 type = type.getUnqualifiedType(); 2579 break; 2580 } 2581 2582 case Decl::Var: 2583 // In C, "extern void blah;" is valid and is an r-value. 2584 if (!getLangOpts().CPlusPlus && 2585 !type.hasQualifiers() && 2586 type->isVoidType()) { 2587 valueKind = VK_RValue; 2588 break; 2589 } 2590 // fallthrough 2591 2592 case Decl::ImplicitParam: 2593 case Decl::ParmVar: { 2594 // These are always l-values. 2595 valueKind = VK_LValue; 2596 type = type.getNonReferenceType(); 2597 2598 // FIXME: Does the addition of const really only apply in 2599 // potentially-evaluated contexts? Since the variable isn't actually 2600 // captured in an unevaluated context, it seems that the answer is no. 2601 if (!isUnevaluatedContext()) { 2602 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2603 if (!CapturedType.isNull()) 2604 type = CapturedType; 2605 } 2606 2607 break; 2608 } 2609 2610 case Decl::Function: { 2611 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2612 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2613 type = Context.BuiltinFnTy; 2614 valueKind = VK_RValue; 2615 break; 2616 } 2617 } 2618 2619 const FunctionType *fty = type->castAs<FunctionType>(); 2620 2621 // If we're referring to a function with an __unknown_anytype 2622 // result type, make the entire expression __unknown_anytype. 2623 if (fty->getResultType() == Context.UnknownAnyTy) { 2624 type = Context.UnknownAnyTy; 2625 valueKind = VK_RValue; 2626 break; 2627 } 2628 2629 // Functions are l-values in C++. 2630 if (getLangOpts().CPlusPlus) { 2631 valueKind = VK_LValue; 2632 break; 2633 } 2634 2635 // C99 DR 316 says that, if a function type comes from a 2636 // function definition (without a prototype), that type is only 2637 // used for checking compatibility. Therefore, when referencing 2638 // the function, we pretend that we don't have the full function 2639 // type. 2640 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2641 isa<FunctionProtoType>(fty)) 2642 type = Context.getFunctionNoProtoType(fty->getResultType(), 2643 fty->getExtInfo()); 2644 2645 // Functions are r-values in C. 2646 valueKind = VK_RValue; 2647 break; 2648 } 2649 2650 case Decl::MSProperty: 2651 valueKind = VK_LValue; 2652 break; 2653 2654 case Decl::CXXMethod: 2655 // If we're referring to a method with an __unknown_anytype 2656 // result type, make the entire expression __unknown_anytype. 2657 // This should only be possible with a type written directly. 2658 if (const FunctionProtoType *proto 2659 = dyn_cast<FunctionProtoType>(VD->getType())) 2660 if (proto->getResultType() == Context.UnknownAnyTy) { 2661 type = Context.UnknownAnyTy; 2662 valueKind = VK_RValue; 2663 break; 2664 } 2665 2666 // C++ methods are l-values if static, r-values if non-static. 2667 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2668 valueKind = VK_LValue; 2669 break; 2670 } 2671 // fallthrough 2672 2673 case Decl::CXXConversion: 2674 case Decl::CXXDestructor: 2675 case Decl::CXXConstructor: 2676 valueKind = VK_RValue; 2677 break; 2678 } 2679 2680 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD); 2681 } 2682 } 2683 2684 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 2685 PredefinedExpr::IdentType IT; 2686 2687 switch (Kind) { 2688 default: llvm_unreachable("Unknown simple primary expr!"); 2689 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 2690 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 2691 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 2692 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 2693 } 2694 2695 // Pre-defined identifiers are of type char[x], where x is the length of the 2696 // string. 2697 2698 Decl *currentDecl = getCurFunctionOrMethodDecl(); 2699 // Blocks and lambdas can occur at global scope. Don't emit a warning. 2700 if (!currentDecl) { 2701 if (const BlockScopeInfo *BSI = getCurBlock()) 2702 currentDecl = BSI->TheDecl; 2703 else if (const LambdaScopeInfo *LSI = getCurLambda()) 2704 currentDecl = LSI->CallOperator; 2705 } 2706 2707 if (!currentDecl) { 2708 Diag(Loc, diag::ext_predef_outside_function); 2709 currentDecl = Context.getTranslationUnitDecl(); 2710 } 2711 2712 QualType ResTy; 2713 if (cast<DeclContext>(currentDecl)->isDependentContext()) { 2714 ResTy = Context.DependentTy; 2715 } else { 2716 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length(); 2717 2718 llvm::APInt LengthI(32, Length + 1); 2719 if (IT == PredefinedExpr::LFunction) 2720 ResTy = Context.WideCharTy.withConst(); 2721 else 2722 ResTy = Context.CharTy.withConst(); 2723 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); 2724 } 2725 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT)); 2726 } 2727 2728 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 2729 SmallString<16> CharBuffer; 2730 bool Invalid = false; 2731 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 2732 if (Invalid) 2733 return ExprError(); 2734 2735 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 2736 PP, Tok.getKind()); 2737 if (Literal.hadError()) 2738 return ExprError(); 2739 2740 QualType Ty; 2741 if (Literal.isWide()) 2742 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 2743 else if (Literal.isUTF16()) 2744 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 2745 else if (Literal.isUTF32()) 2746 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 2747 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 2748 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 2749 else 2750 Ty = Context.CharTy; // 'x' -> char in C++ 2751 2752 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 2753 if (Literal.isWide()) 2754 Kind = CharacterLiteral::Wide; 2755 else if (Literal.isUTF16()) 2756 Kind = CharacterLiteral::UTF16; 2757 else if (Literal.isUTF32()) 2758 Kind = CharacterLiteral::UTF32; 2759 2760 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 2761 Tok.getLocation()); 2762 2763 if (Literal.getUDSuffix().empty()) 2764 return Owned(Lit); 2765 2766 // We're building a user-defined literal. 2767 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 2768 SourceLocation UDSuffixLoc = 2769 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 2770 2771 // Make sure we're allowed user-defined literals here. 2772 if (!UDLScope) 2773 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 2774 2775 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 2776 // operator "" X (ch) 2777 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 2778 Lit, Tok.getLocation()); 2779 } 2780 2781 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 2782 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 2783 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 2784 Context.IntTy, Loc)); 2785 } 2786 2787 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 2788 QualType Ty, SourceLocation Loc) { 2789 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 2790 2791 using llvm::APFloat; 2792 APFloat Val(Format); 2793 2794 APFloat::opStatus result = Literal.GetFloatValue(Val); 2795 2796 // Overflow is always an error, but underflow is only an error if 2797 // we underflowed to zero (APFloat reports denormals as underflow). 2798 if ((result & APFloat::opOverflow) || 2799 ((result & APFloat::opUnderflow) && Val.isZero())) { 2800 unsigned diagnostic; 2801 SmallString<20> buffer; 2802 if (result & APFloat::opOverflow) { 2803 diagnostic = diag::warn_float_overflow; 2804 APFloat::getLargest(Format).toString(buffer); 2805 } else { 2806 diagnostic = diag::warn_float_underflow; 2807 APFloat::getSmallest(Format).toString(buffer); 2808 } 2809 2810 S.Diag(Loc, diagnostic) 2811 << Ty 2812 << StringRef(buffer.data(), buffer.size()); 2813 } 2814 2815 bool isExact = (result == APFloat::opOK); 2816 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 2817 } 2818 2819 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 2820 // Fast path for a single digit (which is quite common). A single digit 2821 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 2822 if (Tok.getLength() == 1) { 2823 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 2824 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 2825 } 2826 2827 SmallString<128> SpellingBuffer; 2828 // NumericLiteralParser wants to overread by one character. Add padding to 2829 // the buffer in case the token is copied to the buffer. If getSpelling() 2830 // returns a StringRef to the memory buffer, it should have a null char at 2831 // the EOF, so it is also safe. 2832 SpellingBuffer.resize(Tok.getLength() + 1); 2833 2834 // Get the spelling of the token, which eliminates trigraphs, etc. 2835 bool Invalid = false; 2836 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 2837 if (Invalid) 2838 return ExprError(); 2839 2840 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 2841 if (Literal.hadError) 2842 return ExprError(); 2843 2844 if (Literal.hasUDSuffix()) { 2845 // We're building a user-defined literal. 2846 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 2847 SourceLocation UDSuffixLoc = 2848 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 2849 2850 // Make sure we're allowed user-defined literals here. 2851 if (!UDLScope) 2852 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 2853 2854 QualType CookedTy; 2855 if (Literal.isFloatingLiteral()) { 2856 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 2857 // long double, the literal is treated as a call of the form 2858 // operator "" X (f L) 2859 CookedTy = Context.LongDoubleTy; 2860 } else { 2861 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 2862 // unsigned long long, the literal is treated as a call of the form 2863 // operator "" X (n ULL) 2864 CookedTy = Context.UnsignedLongLongTy; 2865 } 2866 2867 DeclarationName OpName = 2868 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 2869 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 2870 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 2871 2872 // Perform literal operator lookup to determine if we're building a raw 2873 // literal or a cooked one. 2874 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 2875 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 2876 /*AllowRawAndTemplate*/true)) { 2877 case LOLR_Error: 2878 return ExprError(); 2879 2880 case LOLR_Cooked: { 2881 Expr *Lit; 2882 if (Literal.isFloatingLiteral()) { 2883 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 2884 } else { 2885 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 2886 if (Literal.GetIntegerValue(ResultVal)) 2887 Diag(Tok.getLocation(), diag::warn_integer_too_large); 2888 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 2889 Tok.getLocation()); 2890 } 2891 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, 2892 Tok.getLocation()); 2893 } 2894 2895 case LOLR_Raw: { 2896 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 2897 // literal is treated as a call of the form 2898 // operator "" X ("n") 2899 SourceLocation TokLoc = Tok.getLocation(); 2900 unsigned Length = Literal.getUDSuffixOffset(); 2901 QualType StrTy = Context.getConstantArrayType( 2902 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 2903 ArrayType::Normal, 0); 2904 Expr *Lit = StringLiteral::Create( 2905 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 2906 /*Pascal*/false, StrTy, &TokLoc, 1); 2907 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 2908 } 2909 2910 case LOLR_Template: 2911 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 2912 // template), L is treated as a call fo the form 2913 // operator "" X <'c1', 'c2', ... 'ck'>() 2914 // where n is the source character sequence c1 c2 ... ck. 2915 TemplateArgumentListInfo ExplicitArgs; 2916 unsigned CharBits = Context.getIntWidth(Context.CharTy); 2917 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 2918 llvm::APSInt Value(CharBits, CharIsUnsigned); 2919 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 2920 Value = TokSpelling[I]; 2921 TemplateArgument Arg(Context, Value, Context.CharTy); 2922 TemplateArgumentLocInfo ArgInfo; 2923 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 2924 } 2925 return BuildLiteralOperatorCall(R, OpNameInfo, None, Tok.getLocation(), 2926 &ExplicitArgs); 2927 } 2928 2929 llvm_unreachable("unexpected literal operator lookup result"); 2930 } 2931 2932 Expr *Res; 2933 2934 if (Literal.isFloatingLiteral()) { 2935 QualType Ty; 2936 if (Literal.isFloat) 2937 Ty = Context.FloatTy; 2938 else if (!Literal.isLong) 2939 Ty = Context.DoubleTy; 2940 else 2941 Ty = Context.LongDoubleTy; 2942 2943 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 2944 2945 if (Ty == Context.DoubleTy) { 2946 if (getLangOpts().SinglePrecisionConstants) { 2947 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 2948 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) { 2949 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 2950 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 2951 } 2952 } 2953 } else if (!Literal.isIntegerLiteral()) { 2954 return ExprError(); 2955 } else { 2956 QualType Ty; 2957 2958 // 'long long' is a C99 or C++11 feature. 2959 if (!getLangOpts().C99 && Literal.isLongLong) { 2960 if (getLangOpts().CPlusPlus) 2961 Diag(Tok.getLocation(), 2962 getLangOpts().CPlusPlus11 ? 2963 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 2964 else 2965 Diag(Tok.getLocation(), diag::ext_c99_longlong); 2966 } 2967 2968 // Get the value in the widest-possible width. 2969 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 2970 // The microsoft literal suffix extensions support 128-bit literals, which 2971 // may be wider than [u]intmax_t. 2972 // FIXME: Actually, they don't. We seem to have accidentally invented the 2973 // i128 suffix. 2974 if (Literal.isMicrosoftInteger && MaxWidth < 128 && 2975 PP.getTargetInfo().hasInt128Type()) 2976 MaxWidth = 128; 2977 llvm::APInt ResultVal(MaxWidth, 0); 2978 2979 if (Literal.GetIntegerValue(ResultVal)) { 2980 // If this value didn't fit into uintmax_t, warn and force to ull. 2981 Diag(Tok.getLocation(), diag::warn_integer_too_large); 2982 Ty = Context.UnsignedLongLongTy; 2983 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 2984 "long long is not intmax_t?"); 2985 } else { 2986 // If this value fits into a ULL, try to figure out what else it fits into 2987 // according to the rules of C99 6.4.4.1p5. 2988 2989 // Octal, Hexadecimal, and integers with a U suffix are allowed to 2990 // be an unsigned int. 2991 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 2992 2993 // Check from smallest to largest, picking the smallest type we can. 2994 unsigned Width = 0; 2995 if (!Literal.isLong && !Literal.isLongLong) { 2996 // Are int/unsigned possibilities? 2997 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 2998 2999 // Does it fit in a unsigned int? 3000 if (ResultVal.isIntN(IntSize)) { 3001 // Does it fit in a signed int? 3002 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3003 Ty = Context.IntTy; 3004 else if (AllowUnsigned) 3005 Ty = Context.UnsignedIntTy; 3006 Width = IntSize; 3007 } 3008 } 3009 3010 // Are long/unsigned long possibilities? 3011 if (Ty.isNull() && !Literal.isLongLong) { 3012 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3013 3014 // Does it fit in a unsigned long? 3015 if (ResultVal.isIntN(LongSize)) { 3016 // Does it fit in a signed long? 3017 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3018 Ty = Context.LongTy; 3019 else if (AllowUnsigned) 3020 Ty = Context.UnsignedLongTy; 3021 Width = LongSize; 3022 } 3023 } 3024 3025 // Check long long if needed. 3026 if (Ty.isNull()) { 3027 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3028 3029 // Does it fit in a unsigned long long? 3030 if (ResultVal.isIntN(LongLongSize)) { 3031 // Does it fit in a signed long long? 3032 // To be compatible with MSVC, hex integer literals ending with the 3033 // LL or i64 suffix are always signed in Microsoft mode. 3034 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3035 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 3036 Ty = Context.LongLongTy; 3037 else if (AllowUnsigned) 3038 Ty = Context.UnsignedLongLongTy; 3039 Width = LongLongSize; 3040 } 3041 } 3042 3043 // If it doesn't fit in unsigned long long, and we're using Microsoft 3044 // extensions, then its a 128-bit integer literal. 3045 if (Ty.isNull() && Literal.isMicrosoftInteger && 3046 PP.getTargetInfo().hasInt128Type()) { 3047 if (Literal.isUnsigned) 3048 Ty = Context.UnsignedInt128Ty; 3049 else 3050 Ty = Context.Int128Ty; 3051 Width = 128; 3052 } 3053 3054 // If we still couldn't decide a type, we probably have something that 3055 // does not fit in a signed long long, but has no U suffix. 3056 if (Ty.isNull()) { 3057 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed); 3058 Ty = Context.UnsignedLongLongTy; 3059 Width = Context.getTargetInfo().getLongLongWidth(); 3060 } 3061 3062 if (ResultVal.getBitWidth() != Width) 3063 ResultVal = ResultVal.trunc(Width); 3064 } 3065 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3066 } 3067 3068 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3069 if (Literal.isImaginary) 3070 Res = new (Context) ImaginaryLiteral(Res, 3071 Context.getComplexType(Res->getType())); 3072 3073 return Owned(Res); 3074 } 3075 3076 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3077 assert((E != 0) && "ActOnParenExpr() missing expr"); 3078 return Owned(new (Context) ParenExpr(L, R, E)); 3079 } 3080 3081 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3082 SourceLocation Loc, 3083 SourceRange ArgRange) { 3084 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3085 // scalar or vector data type argument..." 3086 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3087 // type (C99 6.2.5p18) or void. 3088 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3089 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3090 << T << ArgRange; 3091 return true; 3092 } 3093 3094 assert((T->isVoidType() || !T->isIncompleteType()) && 3095 "Scalar types should always be complete"); 3096 return false; 3097 } 3098 3099 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3100 SourceLocation Loc, 3101 SourceRange ArgRange, 3102 UnaryExprOrTypeTrait TraitKind) { 3103 // C99 6.5.3.4p1: 3104 if (T->isFunctionType() && 3105 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3106 // sizeof(function)/alignof(function) is allowed as an extension. 3107 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3108 << TraitKind << ArgRange; 3109 return false; 3110 } 3111 3112 // Allow sizeof(void)/alignof(void) as an extension. 3113 if (T->isVoidType()) { 3114 S.Diag(Loc, diag::ext_sizeof_alignof_void_type) << TraitKind << ArgRange; 3115 return false; 3116 } 3117 3118 return true; 3119 } 3120 3121 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3122 SourceLocation Loc, 3123 SourceRange ArgRange, 3124 UnaryExprOrTypeTrait TraitKind) { 3125 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3126 // runtime doesn't allow it. 3127 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3128 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3129 << T << (TraitKind == UETT_SizeOf) 3130 << ArgRange; 3131 return true; 3132 } 3133 3134 return false; 3135 } 3136 3137 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3138 /// pointer type is equal to T) and emit a warning if it is. 3139 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3140 Expr *E) { 3141 // Don't warn if the operation changed the type. 3142 if (T != E->getType()) 3143 return; 3144 3145 // Now look for array decays. 3146 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3147 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3148 return; 3149 3150 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3151 << ICE->getType() 3152 << ICE->getSubExpr()->getType(); 3153 } 3154 3155 /// \brief Check the constrains on expression operands to unary type expression 3156 /// and type traits. 3157 /// 3158 /// Completes any types necessary and validates the constraints on the operand 3159 /// expression. The logic mostly mirrors the type-based overload, but may modify 3160 /// the expression as it completes the type for that expression through template 3161 /// instantiation, etc. 3162 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3163 UnaryExprOrTypeTrait ExprKind) { 3164 QualType ExprTy = E->getType(); 3165 assert(!ExprTy->isReferenceType()); 3166 3167 if (ExprKind == UETT_VecStep) 3168 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3169 E->getSourceRange()); 3170 3171 // Whitelist some types as extensions 3172 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3173 E->getSourceRange(), ExprKind)) 3174 return false; 3175 3176 if (RequireCompleteExprType(E, 3177 diag::err_sizeof_alignof_incomplete_type, 3178 ExprKind, E->getSourceRange())) 3179 return true; 3180 3181 // Completing the expression's type may have changed it. 3182 ExprTy = E->getType(); 3183 assert(!ExprTy->isReferenceType()); 3184 3185 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3186 E->getSourceRange(), ExprKind)) 3187 return true; 3188 3189 if (ExprKind == UETT_SizeOf) { 3190 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3191 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3192 QualType OType = PVD->getOriginalType(); 3193 QualType Type = PVD->getType(); 3194 if (Type->isPointerType() && OType->isArrayType()) { 3195 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3196 << Type << OType; 3197 Diag(PVD->getLocation(), diag::note_declared_at); 3198 } 3199 } 3200 } 3201 3202 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3203 // decays into a pointer and returns an unintended result. This is most 3204 // likely a typo for "sizeof(array) op x". 3205 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3206 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3207 BO->getLHS()); 3208 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3209 BO->getRHS()); 3210 } 3211 } 3212 3213 return false; 3214 } 3215 3216 /// \brief Check the constraints on operands to unary expression and type 3217 /// traits. 3218 /// 3219 /// This will complete any types necessary, and validate the various constraints 3220 /// on those operands. 3221 /// 3222 /// The UsualUnaryConversions() function is *not* called by this routine. 3223 /// C99 6.3.2.1p[2-4] all state: 3224 /// Except when it is the operand of the sizeof operator ... 3225 /// 3226 /// C++ [expr.sizeof]p4 3227 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3228 /// standard conversions are not applied to the operand of sizeof. 3229 /// 3230 /// This policy is followed for all of the unary trait expressions. 3231 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3232 SourceLocation OpLoc, 3233 SourceRange ExprRange, 3234 UnaryExprOrTypeTrait ExprKind) { 3235 if (ExprType->isDependentType()) 3236 return false; 3237 3238 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 3239 // the result is the size of the referenced type." 3240 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 3241 // result shall be the alignment of the referenced type." 3242 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3243 ExprType = Ref->getPointeeType(); 3244 3245 if (ExprKind == UETT_VecStep) 3246 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3247 3248 // Whitelist some types as extensions 3249 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3250 ExprKind)) 3251 return false; 3252 3253 if (RequireCompleteType(OpLoc, ExprType, 3254 diag::err_sizeof_alignof_incomplete_type, 3255 ExprKind, ExprRange)) 3256 return true; 3257 3258 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3259 ExprKind)) 3260 return true; 3261 3262 return false; 3263 } 3264 3265 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3266 E = E->IgnoreParens(); 3267 3268 // Cannot know anything else if the expression is dependent. 3269 if (E->isTypeDependent()) 3270 return false; 3271 3272 if (E->getObjectKind() == OK_BitField) { 3273 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) 3274 << 1 << E->getSourceRange(); 3275 return true; 3276 } 3277 3278 ValueDecl *D = 0; 3279 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3280 D = DRE->getDecl(); 3281 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3282 D = ME->getMemberDecl(); 3283 } 3284 3285 // If it's a field, require the containing struct to have a 3286 // complete definition so that we can compute the layout. 3287 // 3288 // This requires a very particular set of circumstances. For a 3289 // field to be contained within an incomplete type, we must in the 3290 // process of parsing that type. To have an expression refer to a 3291 // field, it must be an id-expression or a member-expression, but 3292 // the latter are always ill-formed when the base type is 3293 // incomplete, including only being partially complete. An 3294 // id-expression can never refer to a field in C because fields 3295 // are not in the ordinary namespace. In C++, an id-expression 3296 // can implicitly be a member access, but only if there's an 3297 // implicit 'this' value, and all such contexts are subject to 3298 // delayed parsing --- except for trailing return types in C++11. 3299 // And if an id-expression referring to a field occurs in a 3300 // context that lacks a 'this' value, it's ill-formed --- except, 3301 // agian, in C++11, where such references are allowed in an 3302 // unevaluated context. So C++11 introduces some new complexity. 3303 // 3304 // For the record, since __alignof__ on expressions is a GCC 3305 // extension, GCC seems to permit this but always gives the 3306 // nonsensical answer 0. 3307 // 3308 // We don't really need the layout here --- we could instead just 3309 // directly check for all the appropriate alignment-lowing 3310 // attributes --- but that would require duplicating a lot of 3311 // logic that just isn't worth duplicating for such a marginal 3312 // use-case. 3313 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3314 // Fast path this check, since we at least know the record has a 3315 // definition if we can find a member of it. 3316 if (!FD->getParent()->isCompleteDefinition()) { 3317 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3318 << E->getSourceRange(); 3319 return true; 3320 } 3321 3322 // Otherwise, if it's a field, and the field doesn't have 3323 // reference type, then it must have a complete type (or be a 3324 // flexible array member, which we explicitly want to 3325 // white-list anyway), which makes the following checks trivial. 3326 if (!FD->getType()->isReferenceType()) 3327 return false; 3328 } 3329 3330 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3331 } 3332 3333 bool Sema::CheckVecStepExpr(Expr *E) { 3334 E = E->IgnoreParens(); 3335 3336 // Cannot know anything else if the expression is dependent. 3337 if (E->isTypeDependent()) 3338 return false; 3339 3340 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3341 } 3342 3343 /// \brief Build a sizeof or alignof expression given a type operand. 3344 ExprResult 3345 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3346 SourceLocation OpLoc, 3347 UnaryExprOrTypeTrait ExprKind, 3348 SourceRange R) { 3349 if (!TInfo) 3350 return ExprError(); 3351 3352 QualType T = TInfo->getType(); 3353 3354 if (!T->isDependentType() && 3355 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3356 return ExprError(); 3357 3358 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3359 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo, 3360 Context.getSizeType(), 3361 OpLoc, R.getEnd())); 3362 } 3363 3364 /// \brief Build a sizeof or alignof expression given an expression 3365 /// operand. 3366 ExprResult 3367 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3368 UnaryExprOrTypeTrait ExprKind) { 3369 ExprResult PE = CheckPlaceholderExpr(E); 3370 if (PE.isInvalid()) 3371 return ExprError(); 3372 3373 E = PE.get(); 3374 3375 // Verify that the operand is valid. 3376 bool isInvalid = false; 3377 if (E->isTypeDependent()) { 3378 // Delay type-checking for type-dependent expressions. 3379 } else if (ExprKind == UETT_AlignOf) { 3380 isInvalid = CheckAlignOfExpr(*this, E); 3381 } else if (ExprKind == UETT_VecStep) { 3382 isInvalid = CheckVecStepExpr(E); 3383 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 3384 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0; 3385 isInvalid = true; 3386 } else { 3387 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3388 } 3389 3390 if (isInvalid) 3391 return ExprError(); 3392 3393 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3394 PE = TransformToPotentiallyEvaluated(E); 3395 if (PE.isInvalid()) return ExprError(); 3396 E = PE.take(); 3397 } 3398 3399 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3400 return Owned(new (Context) UnaryExprOrTypeTraitExpr( 3401 ExprKind, E, Context.getSizeType(), OpLoc, 3402 E->getSourceRange().getEnd())); 3403 } 3404 3405 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 3406 /// expr and the same for @c alignof and @c __alignof 3407 /// Note that the ArgRange is invalid if isType is false. 3408 ExprResult 3409 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 3410 UnaryExprOrTypeTrait ExprKind, bool IsType, 3411 void *TyOrEx, const SourceRange &ArgRange) { 3412 // If error parsing type, ignore. 3413 if (TyOrEx == 0) return ExprError(); 3414 3415 if (IsType) { 3416 TypeSourceInfo *TInfo; 3417 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 3418 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 3419 } 3420 3421 Expr *ArgEx = (Expr *)TyOrEx; 3422 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 3423 return Result; 3424 } 3425 3426 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 3427 bool IsReal) { 3428 if (V.get()->isTypeDependent()) 3429 return S.Context.DependentTy; 3430 3431 // _Real and _Imag are only l-values for normal l-values. 3432 if (V.get()->getObjectKind() != OK_Ordinary) { 3433 V = S.DefaultLvalueConversion(V.take()); 3434 if (V.isInvalid()) 3435 return QualType(); 3436 } 3437 3438 // These operators return the element type of a complex type. 3439 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 3440 return CT->getElementType(); 3441 3442 // Otherwise they pass through real integer and floating point types here. 3443 if (V.get()->getType()->isArithmeticType()) 3444 return V.get()->getType(); 3445 3446 // Test for placeholders. 3447 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 3448 if (PR.isInvalid()) return QualType(); 3449 if (PR.get() != V.get()) { 3450 V = PR; 3451 return CheckRealImagOperand(S, V, Loc, IsReal); 3452 } 3453 3454 // Reject anything else. 3455 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 3456 << (IsReal ? "__real" : "__imag"); 3457 return QualType(); 3458 } 3459 3460 3461 3462 ExprResult 3463 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 3464 tok::TokenKind Kind, Expr *Input) { 3465 UnaryOperatorKind Opc; 3466 switch (Kind) { 3467 default: llvm_unreachable("Unknown unary op!"); 3468 case tok::plusplus: Opc = UO_PostInc; break; 3469 case tok::minusminus: Opc = UO_PostDec; break; 3470 } 3471 3472 // Since this might is a postfix expression, get rid of ParenListExprs. 3473 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 3474 if (Result.isInvalid()) return ExprError(); 3475 Input = Result.take(); 3476 3477 return BuildUnaryOp(S, OpLoc, Opc, Input); 3478 } 3479 3480 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 3481 /// 3482 /// \return true on error 3483 static bool checkArithmeticOnObjCPointer(Sema &S, 3484 SourceLocation opLoc, 3485 Expr *op) { 3486 assert(op->getType()->isObjCObjectPointerType()); 3487 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic()) 3488 return false; 3489 3490 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 3491 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 3492 << op->getSourceRange(); 3493 return true; 3494 } 3495 3496 ExprResult 3497 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 3498 Expr *idx, SourceLocation rbLoc) { 3499 // Since this might be a postfix expression, get rid of ParenListExprs. 3500 if (isa<ParenListExpr>(base)) { 3501 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 3502 if (result.isInvalid()) return ExprError(); 3503 base = result.take(); 3504 } 3505 3506 // Handle any non-overload placeholder types in the base and index 3507 // expressions. We can't handle overloads here because the other 3508 // operand might be an overloadable type, in which case the overload 3509 // resolution for the operator overload should get the first crack 3510 // at the overload. 3511 if (base->getType()->isNonOverloadPlaceholderType()) { 3512 ExprResult result = CheckPlaceholderExpr(base); 3513 if (result.isInvalid()) return ExprError(); 3514 base = result.take(); 3515 } 3516 if (idx->getType()->isNonOverloadPlaceholderType()) { 3517 ExprResult result = CheckPlaceholderExpr(idx); 3518 if (result.isInvalid()) return ExprError(); 3519 idx = result.take(); 3520 } 3521 3522 // Build an unanalyzed expression if either operand is type-dependent. 3523 if (getLangOpts().CPlusPlus && 3524 (base->isTypeDependent() || idx->isTypeDependent())) { 3525 return Owned(new (Context) ArraySubscriptExpr(base, idx, 3526 Context.DependentTy, 3527 VK_LValue, OK_Ordinary, 3528 rbLoc)); 3529 } 3530 3531 // Use C++ overloaded-operator rules if either operand has record 3532 // type. The spec says to do this if either type is *overloadable*, 3533 // but enum types can't declare subscript operators or conversion 3534 // operators, so there's nothing interesting for overload resolution 3535 // to do if there aren't any record types involved. 3536 // 3537 // ObjC pointers have their own subscripting logic that is not tied 3538 // to overload resolution and so should not take this path. 3539 if (getLangOpts().CPlusPlus && 3540 (base->getType()->isRecordType() || 3541 (!base->getType()->isObjCObjectPointerType() && 3542 idx->getType()->isRecordType()))) { 3543 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 3544 } 3545 3546 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 3547 } 3548 3549 ExprResult 3550 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 3551 Expr *Idx, SourceLocation RLoc) { 3552 Expr *LHSExp = Base; 3553 Expr *RHSExp = Idx; 3554 3555 // Perform default conversions. 3556 if (!LHSExp->getType()->getAs<VectorType>()) { 3557 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 3558 if (Result.isInvalid()) 3559 return ExprError(); 3560 LHSExp = Result.take(); 3561 } 3562 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 3563 if (Result.isInvalid()) 3564 return ExprError(); 3565 RHSExp = Result.take(); 3566 3567 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 3568 ExprValueKind VK = VK_LValue; 3569 ExprObjectKind OK = OK_Ordinary; 3570 3571 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 3572 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 3573 // in the subscript position. As a result, we need to derive the array base 3574 // and index from the expression types. 3575 Expr *BaseExpr, *IndexExpr; 3576 QualType ResultType; 3577 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 3578 BaseExpr = LHSExp; 3579 IndexExpr = RHSExp; 3580 ResultType = Context.DependentTy; 3581 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 3582 BaseExpr = LHSExp; 3583 IndexExpr = RHSExp; 3584 ResultType = PTy->getPointeeType(); 3585 } else if (const ObjCObjectPointerType *PTy = 3586 LHSTy->getAs<ObjCObjectPointerType>()) { 3587 BaseExpr = LHSExp; 3588 IndexExpr = RHSExp; 3589 3590 // Use custom logic if this should be the pseudo-object subscript 3591 // expression. 3592 if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic()) 3593 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0); 3594 3595 ResultType = PTy->getPointeeType(); 3596 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) { 3597 Diag(LLoc, diag::err_subscript_nonfragile_interface) 3598 << ResultType << BaseExpr->getSourceRange(); 3599 return ExprError(); 3600 } 3601 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 3602 // Handle the uncommon case of "123[Ptr]". 3603 BaseExpr = RHSExp; 3604 IndexExpr = LHSExp; 3605 ResultType = PTy->getPointeeType(); 3606 } else if (const ObjCObjectPointerType *PTy = 3607 RHSTy->getAs<ObjCObjectPointerType>()) { 3608 // Handle the uncommon case of "123[Ptr]". 3609 BaseExpr = RHSExp; 3610 IndexExpr = LHSExp; 3611 ResultType = PTy->getPointeeType(); 3612 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) { 3613 Diag(LLoc, diag::err_subscript_nonfragile_interface) 3614 << ResultType << BaseExpr->getSourceRange(); 3615 return ExprError(); 3616 } 3617 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 3618 BaseExpr = LHSExp; // vectors: V[123] 3619 IndexExpr = RHSExp; 3620 VK = LHSExp->getValueKind(); 3621 if (VK != VK_RValue) 3622 OK = OK_VectorComponent; 3623 3624 // FIXME: need to deal with const... 3625 ResultType = VTy->getElementType(); 3626 } else if (LHSTy->isArrayType()) { 3627 // If we see an array that wasn't promoted by 3628 // DefaultFunctionArrayLvalueConversion, it must be an array that 3629 // wasn't promoted because of the C90 rule that doesn't 3630 // allow promoting non-lvalue arrays. Warn, then 3631 // force the promotion here. 3632 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3633 LHSExp->getSourceRange(); 3634 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 3635 CK_ArrayToPointerDecay).take(); 3636 LHSTy = LHSExp->getType(); 3637 3638 BaseExpr = LHSExp; 3639 IndexExpr = RHSExp; 3640 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 3641 } else if (RHSTy->isArrayType()) { 3642 // Same as previous, except for 123[f().a] case 3643 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3644 RHSExp->getSourceRange(); 3645 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 3646 CK_ArrayToPointerDecay).take(); 3647 RHSTy = RHSExp->getType(); 3648 3649 BaseExpr = RHSExp; 3650 IndexExpr = LHSExp; 3651 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 3652 } else { 3653 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 3654 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 3655 } 3656 // C99 6.5.2.1p1 3657 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 3658 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 3659 << IndexExpr->getSourceRange()); 3660 3661 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 3662 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 3663 && !IndexExpr->isTypeDependent()) 3664 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 3665 3666 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 3667 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 3668 // type. Note that Functions are not objects, and that (in C99 parlance) 3669 // incomplete types are not object types. 3670 if (ResultType->isFunctionType()) { 3671 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 3672 << ResultType << BaseExpr->getSourceRange(); 3673 return ExprError(); 3674 } 3675 3676 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 3677 // GNU extension: subscripting on pointer to void 3678 Diag(LLoc, diag::ext_gnu_subscript_void_type) 3679 << BaseExpr->getSourceRange(); 3680 3681 // C forbids expressions of unqualified void type from being l-values. 3682 // See IsCForbiddenLValueType. 3683 if (!ResultType.hasQualifiers()) VK = VK_RValue; 3684 } else if (!ResultType->isDependentType() && 3685 RequireCompleteType(LLoc, ResultType, 3686 diag::err_subscript_incomplete_type, BaseExpr)) 3687 return ExprError(); 3688 3689 assert(VK == VK_RValue || LangOpts.CPlusPlus || 3690 !ResultType.isCForbiddenLValueType()); 3691 3692 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 3693 ResultType, VK, OK, RLoc)); 3694 } 3695 3696 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 3697 FunctionDecl *FD, 3698 ParmVarDecl *Param) { 3699 if (Param->hasUnparsedDefaultArg()) { 3700 Diag(CallLoc, 3701 diag::err_use_of_default_argument_to_function_declared_later) << 3702 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 3703 Diag(UnparsedDefaultArgLocs[Param], 3704 diag::note_default_argument_declared_here); 3705 return ExprError(); 3706 } 3707 3708 if (Param->hasUninstantiatedDefaultArg()) { 3709 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 3710 3711 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 3712 Param); 3713 3714 // Instantiate the expression. 3715 MultiLevelTemplateArgumentList MutiLevelArgList 3716 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true); 3717 3718 InstantiatingTemplate Inst(*this, CallLoc, Param, 3719 MutiLevelArgList.getInnermost()); 3720 if (Inst) 3721 return ExprError(); 3722 3723 ExprResult Result; 3724 { 3725 // C++ [dcl.fct.default]p5: 3726 // The names in the [default argument] expression are bound, and 3727 // the semantic constraints are checked, at the point where the 3728 // default argument expression appears. 3729 ContextRAII SavedContext(*this, FD); 3730 LocalInstantiationScope Local(*this); 3731 Result = SubstExpr(UninstExpr, MutiLevelArgList); 3732 } 3733 if (Result.isInvalid()) 3734 return ExprError(); 3735 3736 // Check the expression as an initializer for the parameter. 3737 InitializedEntity Entity 3738 = InitializedEntity::InitializeParameter(Context, Param); 3739 InitializationKind Kind 3740 = InitializationKind::CreateCopy(Param->getLocation(), 3741 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 3742 Expr *ResultE = Result.takeAs<Expr>(); 3743 3744 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 3745 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 3746 if (Result.isInvalid()) 3747 return ExprError(); 3748 3749 Expr *Arg = Result.takeAs<Expr>(); 3750 CheckCompletedExpr(Arg, Param->getOuterLocStart()); 3751 // Build the default argument expression. 3752 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg)); 3753 } 3754 3755 // If the default expression creates temporaries, we need to 3756 // push them to the current stack of expression temporaries so they'll 3757 // be properly destroyed. 3758 // FIXME: We should really be rebuilding the default argument with new 3759 // bound temporaries; see the comment in PR5810. 3760 // We don't need to do that with block decls, though, because 3761 // blocks in default argument expression can never capture anything. 3762 if (isa<ExprWithCleanups>(Param->getInit())) { 3763 // Set the "needs cleanups" bit regardless of whether there are 3764 // any explicit objects. 3765 ExprNeedsCleanups = true; 3766 3767 // Append all the objects to the cleanup list. Right now, this 3768 // should always be a no-op, because blocks in default argument 3769 // expressions should never be able to capture anything. 3770 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() && 3771 "default argument expression has capturing blocks?"); 3772 } 3773 3774 // We already type-checked the argument, so we know it works. 3775 // Just mark all of the declarations in this potentially-evaluated expression 3776 // as being "referenced". 3777 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 3778 /*SkipLocalVariables=*/true); 3779 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param)); 3780 } 3781 3782 3783 Sema::VariadicCallType 3784 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 3785 Expr *Fn) { 3786 if (Proto && Proto->isVariadic()) { 3787 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 3788 return VariadicConstructor; 3789 else if (Fn && Fn->getType()->isBlockPointerType()) 3790 return VariadicBlock; 3791 else if (FDecl) { 3792 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 3793 if (Method->isInstance()) 3794 return VariadicMethod; 3795 } 3796 return VariadicFunction; 3797 } 3798 return VariadicDoesNotApply; 3799 } 3800 3801 /// ConvertArgumentsForCall - Converts the arguments specified in 3802 /// Args/NumArgs to the parameter types of the function FDecl with 3803 /// function prototype Proto. Call is the call expression itself, and 3804 /// Fn is the function expression. For a C++ member function, this 3805 /// routine does not attempt to convert the object argument. Returns 3806 /// true if the call is ill-formed. 3807 bool 3808 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 3809 FunctionDecl *FDecl, 3810 const FunctionProtoType *Proto, 3811 ArrayRef<Expr *> Args, 3812 SourceLocation RParenLoc, 3813 bool IsExecConfig) { 3814 // Bail out early if calling a builtin with custom typechecking. 3815 // We don't need to do this in the 3816 if (FDecl) 3817 if (unsigned ID = FDecl->getBuiltinID()) 3818 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 3819 return false; 3820 3821 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 3822 // assignment, to the types of the corresponding parameter, ... 3823 unsigned NumArgsInProto = Proto->getNumArgs(); 3824 bool Invalid = false; 3825 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto; 3826 unsigned FnKind = Fn->getType()->isBlockPointerType() 3827 ? 1 /* block */ 3828 : (IsExecConfig ? 3 /* kernel function (exec config) */ 3829 : 0 /* function */); 3830 3831 // If too few arguments are available (and we don't have default 3832 // arguments for the remaining parameters), don't make the call. 3833 if (Args.size() < NumArgsInProto) { 3834 if (Args.size() < MinArgs) { 3835 if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 3836 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic() 3837 ? diag::err_typecheck_call_too_few_args_one 3838 : diag::err_typecheck_call_too_few_args_at_least_one) 3839 << FnKind 3840 << FDecl->getParamDecl(0) << Fn->getSourceRange(); 3841 else 3842 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic() 3843 ? diag::err_typecheck_call_too_few_args 3844 : diag::err_typecheck_call_too_few_args_at_least) 3845 << FnKind 3846 << MinArgs << static_cast<unsigned>(Args.size()) 3847 << Fn->getSourceRange(); 3848 3849 // Emit the location of the prototype. 3850 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 3851 Diag(FDecl->getLocStart(), diag::note_callee_decl) 3852 << FDecl; 3853 3854 return true; 3855 } 3856 Call->setNumArgs(Context, NumArgsInProto); 3857 } 3858 3859 // If too many are passed and not variadic, error on the extras and drop 3860 // them. 3861 if (Args.size() > NumArgsInProto) { 3862 if (!Proto->isVariadic()) { 3863 if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 3864 Diag(Args[NumArgsInProto]->getLocStart(), 3865 MinArgs == NumArgsInProto 3866 ? diag::err_typecheck_call_too_many_args_one 3867 : diag::err_typecheck_call_too_many_args_at_most_one) 3868 << FnKind 3869 << FDecl->getParamDecl(0) << static_cast<unsigned>(Args.size()) 3870 << Fn->getSourceRange() 3871 << SourceRange(Args[NumArgsInProto]->getLocStart(), 3872 Args.back()->getLocEnd()); 3873 else 3874 Diag(Args[NumArgsInProto]->getLocStart(), 3875 MinArgs == NumArgsInProto 3876 ? diag::err_typecheck_call_too_many_args 3877 : diag::err_typecheck_call_too_many_args_at_most) 3878 << FnKind 3879 << NumArgsInProto << static_cast<unsigned>(Args.size()) 3880 << Fn->getSourceRange() 3881 << SourceRange(Args[NumArgsInProto]->getLocStart(), 3882 Args.back()->getLocEnd()); 3883 3884 // Emit the location of the prototype. 3885 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 3886 Diag(FDecl->getLocStart(), diag::note_callee_decl) 3887 << FDecl; 3888 3889 // This deletes the extra arguments. 3890 Call->setNumArgs(Context, NumArgsInProto); 3891 return true; 3892 } 3893 } 3894 SmallVector<Expr *, 8> AllArgs; 3895 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 3896 3897 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 3898 Proto, 0, Args, AllArgs, CallType); 3899 if (Invalid) 3900 return true; 3901 unsigned TotalNumArgs = AllArgs.size(); 3902 for (unsigned i = 0; i < TotalNumArgs; ++i) 3903 Call->setArg(i, AllArgs[i]); 3904 3905 return false; 3906 } 3907 3908 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, 3909 FunctionDecl *FDecl, 3910 const FunctionProtoType *Proto, 3911 unsigned FirstProtoArg, 3912 ArrayRef<Expr *> Args, 3913 SmallVector<Expr *, 8> &AllArgs, 3914 VariadicCallType CallType, 3915 bool AllowExplicit, 3916 bool IsListInitialization) { 3917 unsigned NumArgsInProto = Proto->getNumArgs(); 3918 unsigned NumArgsToCheck = Args.size(); 3919 bool Invalid = false; 3920 if (Args.size() != NumArgsInProto) 3921 // Use default arguments for missing arguments 3922 NumArgsToCheck = NumArgsInProto; 3923 unsigned ArgIx = 0; 3924 // Continue to check argument types (even if we have too few/many args). 3925 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) { 3926 QualType ProtoArgType = Proto->getArgType(i); 3927 3928 Expr *Arg; 3929 ParmVarDecl *Param; 3930 if (ArgIx < Args.size()) { 3931 Arg = Args[ArgIx++]; 3932 3933 if (RequireCompleteType(Arg->getLocStart(), 3934 ProtoArgType, 3935 diag::err_call_incomplete_argument, Arg)) 3936 return true; 3937 3938 // Pass the argument 3939 Param = 0; 3940 if (FDecl && i < FDecl->getNumParams()) 3941 Param = FDecl->getParamDecl(i); 3942 3943 // Strip the unbridged-cast placeholder expression off, if applicable. 3944 if (Arg->getType() == Context.ARCUnbridgedCastTy && 3945 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 3946 (!Param || !Param->hasAttr<CFConsumedAttr>())) 3947 Arg = stripARCUnbridgedCast(Arg); 3948 3949 InitializedEntity Entity = Param ? 3950 InitializedEntity::InitializeParameter(Context, Param, ProtoArgType) 3951 : InitializedEntity::InitializeParameter(Context, ProtoArgType, 3952 Proto->isArgConsumed(i)); 3953 ExprResult ArgE = PerformCopyInitialization(Entity, 3954 SourceLocation(), 3955 Owned(Arg), 3956 IsListInitialization, 3957 AllowExplicit); 3958 if (ArgE.isInvalid()) 3959 return true; 3960 3961 Arg = ArgE.takeAs<Expr>(); 3962 } else { 3963 assert(FDecl && "can't use default arguments without a known callee"); 3964 Param = FDecl->getParamDecl(i); 3965 3966 ExprResult ArgExpr = 3967 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 3968 if (ArgExpr.isInvalid()) 3969 return true; 3970 3971 Arg = ArgExpr.takeAs<Expr>(); 3972 } 3973 3974 // Check for array bounds violations for each argument to the call. This 3975 // check only triggers warnings when the argument isn't a more complex Expr 3976 // with its own checking, such as a BinaryOperator. 3977 CheckArrayAccess(Arg); 3978 3979 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 3980 CheckStaticArrayArgument(CallLoc, Param, Arg); 3981 3982 AllArgs.push_back(Arg); 3983 } 3984 3985 // If this is a variadic call, handle args passed through "...". 3986 if (CallType != VariadicDoesNotApply) { 3987 // Assume that extern "C" functions with variadic arguments that 3988 // return __unknown_anytype aren't *really* variadic. 3989 if (Proto->getResultType() == Context.UnknownAnyTy && 3990 FDecl && FDecl->isExternC()) { 3991 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 3992 QualType paramType; // ignored 3993 ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType); 3994 Invalid |= arg.isInvalid(); 3995 AllArgs.push_back(arg.take()); 3996 } 3997 3998 // Otherwise do argument promotion, (C99 6.5.2.2p7). 3999 } else { 4000 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4001 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, 4002 FDecl); 4003 Invalid |= Arg.isInvalid(); 4004 AllArgs.push_back(Arg.take()); 4005 } 4006 } 4007 4008 // Check for array bounds violations. 4009 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) 4010 CheckArrayAccess(Args[i]); 4011 } 4012 return Invalid; 4013 } 4014 4015 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4016 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4017 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4018 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4019 << ATL.getLocalSourceRange(); 4020 } 4021 4022 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4023 /// array parameter, check that it is non-null, and that if it is formed by 4024 /// array-to-pointer decay, the underlying array is sufficiently large. 4025 /// 4026 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4027 /// array type derivation, then for each call to the function, the value of the 4028 /// corresponding actual argument shall provide access to the first element of 4029 /// an array with at least as many elements as specified by the size expression. 4030 void 4031 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4032 ParmVarDecl *Param, 4033 const Expr *ArgExpr) { 4034 // Static array parameters are not supported in C++. 4035 if (!Param || getLangOpts().CPlusPlus) 4036 return; 4037 4038 QualType OrigTy = Param->getOriginalType(); 4039 4040 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4041 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4042 return; 4043 4044 if (ArgExpr->isNullPointerConstant(Context, 4045 Expr::NPC_NeverValueDependent)) { 4046 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4047 DiagnoseCalleeStaticArrayParam(*this, Param); 4048 return; 4049 } 4050 4051 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4052 if (!CAT) 4053 return; 4054 4055 const ConstantArrayType *ArgCAT = 4056 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4057 if (!ArgCAT) 4058 return; 4059 4060 if (ArgCAT->getSize().ult(CAT->getSize())) { 4061 Diag(CallLoc, diag::warn_static_array_too_small) 4062 << ArgExpr->getSourceRange() 4063 << (unsigned) ArgCAT->getSize().getZExtValue() 4064 << (unsigned) CAT->getSize().getZExtValue(); 4065 DiagnoseCalleeStaticArrayParam(*this, Param); 4066 } 4067 } 4068 4069 /// Given a function expression of unknown-any type, try to rebuild it 4070 /// to have a function type. 4071 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4072 4073 /// Is the given type a placeholder that we need to lower out 4074 /// immediately during argument processing? 4075 static bool isPlaceholderToRemoveAsArg(QualType type) { 4076 // Placeholders are never sugared. 4077 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4078 if (!placeholder) return false; 4079 4080 switch (placeholder->getKind()) { 4081 // Ignore all the non-placeholder types. 4082 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4083 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4084 #include "clang/AST/BuiltinTypes.def" 4085 return false; 4086 4087 // We cannot lower out overload sets; they might validly be resolved 4088 // by the call machinery. 4089 case BuiltinType::Overload: 4090 return false; 4091 4092 // Unbridged casts in ARC can be handled in some call positions and 4093 // should be left in place. 4094 case BuiltinType::ARCUnbridgedCast: 4095 return false; 4096 4097 // Pseudo-objects should be converted as soon as possible. 4098 case BuiltinType::PseudoObject: 4099 return true; 4100 4101 // The debugger mode could theoretically but currently does not try 4102 // to resolve unknown-typed arguments based on known parameter types. 4103 case BuiltinType::UnknownAny: 4104 return true; 4105 4106 // These are always invalid as call arguments and should be reported. 4107 case BuiltinType::BoundMember: 4108 case BuiltinType::BuiltinFn: 4109 return true; 4110 } 4111 llvm_unreachable("bad builtin type kind"); 4112 } 4113 4114 /// Check an argument list for placeholders that we won't try to 4115 /// handle later. 4116 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 4117 // Apply this processing to all the arguments at once instead of 4118 // dying at the first failure. 4119 bool hasInvalid = false; 4120 for (size_t i = 0, e = args.size(); i != e; i++) { 4121 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 4122 ExprResult result = S.CheckPlaceholderExpr(args[i]); 4123 if (result.isInvalid()) hasInvalid = true; 4124 else args[i] = result.take(); 4125 } 4126 } 4127 return hasInvalid; 4128 } 4129 4130 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 4131 /// This provides the location of the left/right parens and a list of comma 4132 /// locations. 4133 ExprResult 4134 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 4135 MultiExprArg ArgExprs, SourceLocation RParenLoc, 4136 Expr *ExecConfig, bool IsExecConfig) { 4137 // Since this might be a postfix expression, get rid of ParenListExprs. 4138 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 4139 if (Result.isInvalid()) return ExprError(); 4140 Fn = Result.take(); 4141 4142 if (checkArgsForPlaceholders(*this, ArgExprs)) 4143 return ExprError(); 4144 4145 if (getLangOpts().CPlusPlus) { 4146 // If this is a pseudo-destructor expression, build the call immediately. 4147 if (isa<CXXPseudoDestructorExpr>(Fn)) { 4148 if (!ArgExprs.empty()) { 4149 // Pseudo-destructor calls should not have any arguments. 4150 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 4151 << FixItHint::CreateRemoval( 4152 SourceRange(ArgExprs[0]->getLocStart(), 4153 ArgExprs.back()->getLocEnd())); 4154 } 4155 4156 return Owned(new (Context) CallExpr(Context, Fn, None, 4157 Context.VoidTy, VK_RValue, 4158 RParenLoc)); 4159 } 4160 if (Fn->getType() == Context.PseudoObjectTy) { 4161 ExprResult result = CheckPlaceholderExpr(Fn); 4162 if (result.isInvalid()) return ExprError(); 4163 Fn = result.take(); 4164 } 4165 4166 // Determine whether this is a dependent call inside a C++ template, 4167 // in which case we won't do any semantic analysis now. 4168 // FIXME: Will need to cache the results of name lookup (including ADL) in 4169 // Fn. 4170 bool Dependent = false; 4171 if (Fn->isTypeDependent()) 4172 Dependent = true; 4173 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 4174 Dependent = true; 4175 4176 if (Dependent) { 4177 if (ExecConfig) { 4178 return Owned(new (Context) CUDAKernelCallExpr( 4179 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 4180 Context.DependentTy, VK_RValue, RParenLoc)); 4181 } else { 4182 return Owned(new (Context) CallExpr(Context, Fn, ArgExprs, 4183 Context.DependentTy, VK_RValue, 4184 RParenLoc)); 4185 } 4186 } 4187 4188 // Determine whether this is a call to an object (C++ [over.call.object]). 4189 if (Fn->getType()->isRecordType()) 4190 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, 4191 ArgExprs, RParenLoc)); 4192 4193 if (Fn->getType() == Context.UnknownAnyTy) { 4194 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4195 if (result.isInvalid()) return ExprError(); 4196 Fn = result.take(); 4197 } 4198 4199 if (Fn->getType() == Context.BoundMemberTy) { 4200 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 4201 } 4202 } 4203 4204 // Check for overloaded calls. This can happen even in C due to extensions. 4205 if (Fn->getType() == Context.OverloadTy) { 4206 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 4207 4208 // We aren't supposed to apply this logic for if there's an '&' involved. 4209 if (!find.HasFormOfMemberPointer) { 4210 OverloadExpr *ovl = find.Expression; 4211 if (isa<UnresolvedLookupExpr>(ovl)) { 4212 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl); 4213 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs, 4214 RParenLoc, ExecConfig); 4215 } else { 4216 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, 4217 RParenLoc); 4218 } 4219 } 4220 } 4221 4222 // If we're directly calling a function, get the appropriate declaration. 4223 if (Fn->getType() == Context.UnknownAnyTy) { 4224 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4225 if (result.isInvalid()) return ExprError(); 4226 Fn = result.take(); 4227 } 4228 4229 Expr *NakedFn = Fn->IgnoreParens(); 4230 4231 NamedDecl *NDecl = 0; 4232 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) 4233 if (UnOp->getOpcode() == UO_AddrOf) 4234 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 4235 4236 if (isa<DeclRefExpr>(NakedFn)) 4237 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 4238 else if (isa<MemberExpr>(NakedFn)) 4239 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 4240 4241 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 4242 ExecConfig, IsExecConfig); 4243 } 4244 4245 ExprResult 4246 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 4247 MultiExprArg ExecConfig, SourceLocation GGGLoc) { 4248 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl(); 4249 if (!ConfigDecl) 4250 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use) 4251 << "cudaConfigureCall"); 4252 QualType ConfigQTy = ConfigDecl->getType(); 4253 4254 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr( 4255 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc); 4256 MarkFunctionReferenced(LLLLoc, ConfigDecl); 4257 4258 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0, 4259 /*IsExecConfig=*/true); 4260 } 4261 4262 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 4263 /// 4264 /// __builtin_astype( value, dst type ) 4265 /// 4266 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 4267 SourceLocation BuiltinLoc, 4268 SourceLocation RParenLoc) { 4269 ExprValueKind VK = VK_RValue; 4270 ExprObjectKind OK = OK_Ordinary; 4271 QualType DstTy = GetTypeFromParser(ParsedDestTy); 4272 QualType SrcTy = E->getType(); 4273 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 4274 return ExprError(Diag(BuiltinLoc, 4275 diag::err_invalid_astype_of_different_size) 4276 << DstTy 4277 << SrcTy 4278 << E->getSourceRange()); 4279 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, 4280 RParenLoc)); 4281 } 4282 4283 /// BuildResolvedCallExpr - Build a call to a resolved expression, 4284 /// i.e. an expression not of \p OverloadTy. The expression should 4285 /// unary-convert to an expression of function-pointer or 4286 /// block-pointer type. 4287 /// 4288 /// \param NDecl the declaration being called, if available 4289 ExprResult 4290 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 4291 SourceLocation LParenLoc, 4292 ArrayRef<Expr *> Args, 4293 SourceLocation RParenLoc, 4294 Expr *Config, bool IsExecConfig) { 4295 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 4296 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 4297 4298 // Promote the function operand. 4299 // We special-case function promotion here because we only allow promoting 4300 // builtin functions to function pointers in the callee of a call. 4301 ExprResult Result; 4302 if (BuiltinID && 4303 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 4304 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 4305 CK_BuiltinFnToFnPtr).take(); 4306 } else { 4307 Result = UsualUnaryConversions(Fn); 4308 } 4309 if (Result.isInvalid()) 4310 return ExprError(); 4311 Fn = Result.take(); 4312 4313 // Make the call expr early, before semantic checks. This guarantees cleanup 4314 // of arguments and function on error. 4315 CallExpr *TheCall; 4316 if (Config) 4317 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 4318 cast<CallExpr>(Config), Args, 4319 Context.BoolTy, VK_RValue, 4320 RParenLoc); 4321 else 4322 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 4323 VK_RValue, RParenLoc); 4324 4325 // Bail out early if calling a builtin with custom typechecking. 4326 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 4327 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 4328 4329 retry: 4330 const FunctionType *FuncT; 4331 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 4332 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 4333 // have type pointer to function". 4334 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 4335 if (FuncT == 0) 4336 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4337 << Fn->getType() << Fn->getSourceRange()); 4338 } else if (const BlockPointerType *BPT = 4339 Fn->getType()->getAs<BlockPointerType>()) { 4340 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 4341 } else { 4342 // Handle calls to expressions of unknown-any type. 4343 if (Fn->getType() == Context.UnknownAnyTy) { 4344 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 4345 if (rewrite.isInvalid()) return ExprError(); 4346 Fn = rewrite.take(); 4347 TheCall->setCallee(Fn); 4348 goto retry; 4349 } 4350 4351 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4352 << Fn->getType() << Fn->getSourceRange()); 4353 } 4354 4355 if (getLangOpts().CUDA) { 4356 if (Config) { 4357 // CUDA: Kernel calls must be to global functions 4358 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 4359 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 4360 << FDecl->getName() << Fn->getSourceRange()); 4361 4362 // CUDA: Kernel function must have 'void' return type 4363 if (!FuncT->getResultType()->isVoidType()) 4364 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 4365 << Fn->getType() << Fn->getSourceRange()); 4366 } else { 4367 // CUDA: Calls to global functions must be configured 4368 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 4369 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 4370 << FDecl->getName() << Fn->getSourceRange()); 4371 } 4372 } 4373 4374 // Check for a valid return type 4375 if (CheckCallReturnType(FuncT->getResultType(), 4376 Fn->getLocStart(), TheCall, 4377 FDecl)) 4378 return ExprError(); 4379 4380 // We know the result type of the call, set it. 4381 TheCall->setType(FuncT->getCallResultType(Context)); 4382 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType())); 4383 4384 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 4385 if (Proto) { 4386 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 4387 IsExecConfig)) 4388 return ExprError(); 4389 } else { 4390 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 4391 4392 if (FDecl) { 4393 // Check if we have too few/too many template arguments, based 4394 // on our knowledge of the function definition. 4395 const FunctionDecl *Def = 0; 4396 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 4397 Proto = Def->getType()->getAs<FunctionProtoType>(); 4398 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 4399 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 4400 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 4401 } 4402 4403 // If the function we're calling isn't a function prototype, but we have 4404 // a function prototype from a prior declaratiom, use that prototype. 4405 if (!FDecl->hasPrototype()) 4406 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 4407 } 4408 4409 // Promote the arguments (C99 6.5.2.2p6). 4410 for (unsigned i = 0, e = Args.size(); i != e; i++) { 4411 Expr *Arg = Args[i]; 4412 4413 if (Proto && i < Proto->getNumArgs()) { 4414 InitializedEntity Entity 4415 = InitializedEntity::InitializeParameter(Context, 4416 Proto->getArgType(i), 4417 Proto->isArgConsumed(i)); 4418 ExprResult ArgE = PerformCopyInitialization(Entity, 4419 SourceLocation(), 4420 Owned(Arg)); 4421 if (ArgE.isInvalid()) 4422 return true; 4423 4424 Arg = ArgE.takeAs<Expr>(); 4425 4426 } else { 4427 ExprResult ArgE = DefaultArgumentPromotion(Arg); 4428 4429 if (ArgE.isInvalid()) 4430 return true; 4431 4432 Arg = ArgE.takeAs<Expr>(); 4433 } 4434 4435 if (RequireCompleteType(Arg->getLocStart(), 4436 Arg->getType(), 4437 diag::err_call_incomplete_argument, Arg)) 4438 return ExprError(); 4439 4440 TheCall->setArg(i, Arg); 4441 } 4442 } 4443 4444 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4445 if (!Method->isStatic()) 4446 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 4447 << Fn->getSourceRange()); 4448 4449 // Check for sentinels 4450 if (NDecl) 4451 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 4452 4453 // Do special checking on direct calls to functions. 4454 if (FDecl) { 4455 if (CheckFunctionCall(FDecl, TheCall, Proto)) 4456 return ExprError(); 4457 4458 if (BuiltinID) 4459 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 4460 } else if (NDecl) { 4461 if (CheckBlockCall(NDecl, TheCall, Proto)) 4462 return ExprError(); 4463 } 4464 4465 return MaybeBindToTemporary(TheCall); 4466 } 4467 4468 ExprResult 4469 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 4470 SourceLocation RParenLoc, Expr *InitExpr) { 4471 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type"); 4472 // FIXME: put back this assert when initializers are worked out. 4473 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 4474 4475 TypeSourceInfo *TInfo; 4476 QualType literalType = GetTypeFromParser(Ty, &TInfo); 4477 if (!TInfo) 4478 TInfo = Context.getTrivialTypeSourceInfo(literalType); 4479 4480 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 4481 } 4482 4483 ExprResult 4484 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 4485 SourceLocation RParenLoc, Expr *LiteralExpr) { 4486 QualType literalType = TInfo->getType(); 4487 4488 if (literalType->isArrayType()) { 4489 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 4490 diag::err_illegal_decl_array_incomplete_type, 4491 SourceRange(LParenLoc, 4492 LiteralExpr->getSourceRange().getEnd()))) 4493 return ExprError(); 4494 if (literalType->isVariableArrayType()) 4495 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 4496 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 4497 } else if (!literalType->isDependentType() && 4498 RequireCompleteType(LParenLoc, literalType, 4499 diag::err_typecheck_decl_incomplete_type, 4500 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 4501 return ExprError(); 4502 4503 InitializedEntity Entity 4504 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 4505 InitializationKind Kind 4506 = InitializationKind::CreateCStyleCast(LParenLoc, 4507 SourceRange(LParenLoc, RParenLoc), 4508 /*InitList=*/true); 4509 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 4510 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 4511 &literalType); 4512 if (Result.isInvalid()) 4513 return ExprError(); 4514 LiteralExpr = Result.get(); 4515 4516 bool isFileScope = getCurFunctionOrMethodDecl() == 0; 4517 if (isFileScope) { // 6.5.2.5p3 4518 if (CheckForConstantInitializer(LiteralExpr, literalType)) 4519 return ExprError(); 4520 } 4521 4522 // In C, compound literals are l-values for some reason. 4523 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 4524 4525 return MaybeBindToTemporary( 4526 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 4527 VK, LiteralExpr, isFileScope)); 4528 } 4529 4530 ExprResult 4531 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 4532 SourceLocation RBraceLoc) { 4533 // Immediately handle non-overload placeholders. Overloads can be 4534 // resolved contextually, but everything else here can't. 4535 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 4536 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 4537 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 4538 4539 // Ignore failures; dropping the entire initializer list because 4540 // of one failure would be terrible for indexing/etc. 4541 if (result.isInvalid()) continue; 4542 4543 InitArgList[I] = result.take(); 4544 } 4545 } 4546 4547 // Semantic analysis for initializers is done by ActOnDeclarator() and 4548 // CheckInitializer() - it requires knowledge of the object being intialized. 4549 4550 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 4551 RBraceLoc); 4552 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 4553 return Owned(E); 4554 } 4555 4556 /// Do an explicit extend of the given block pointer if we're in ARC. 4557 static void maybeExtendBlockObject(Sema &S, ExprResult &E) { 4558 assert(E.get()->getType()->isBlockPointerType()); 4559 assert(E.get()->isRValue()); 4560 4561 // Only do this in an r-value context. 4562 if (!S.getLangOpts().ObjCAutoRefCount) return; 4563 4564 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), 4565 CK_ARCExtendBlockObject, E.get(), 4566 /*base path*/ 0, VK_RValue); 4567 S.ExprNeedsCleanups = true; 4568 } 4569 4570 /// Prepare a conversion of the given expression to an ObjC object 4571 /// pointer type. 4572 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 4573 QualType type = E.get()->getType(); 4574 if (type->isObjCObjectPointerType()) { 4575 return CK_BitCast; 4576 } else if (type->isBlockPointerType()) { 4577 maybeExtendBlockObject(*this, E); 4578 return CK_BlockPointerToObjCPointerCast; 4579 } else { 4580 assert(type->isPointerType()); 4581 return CK_CPointerToObjCPointerCast; 4582 } 4583 } 4584 4585 /// Prepares for a scalar cast, performing all the necessary stages 4586 /// except the final cast and returning the kind required. 4587 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 4588 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 4589 // Also, callers should have filtered out the invalid cases with 4590 // pointers. Everything else should be possible. 4591 4592 QualType SrcTy = Src.get()->getType(); 4593 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 4594 return CK_NoOp; 4595 4596 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 4597 case Type::STK_MemberPointer: 4598 llvm_unreachable("member pointer type in C"); 4599 4600 case Type::STK_CPointer: 4601 case Type::STK_BlockPointer: 4602 case Type::STK_ObjCObjectPointer: 4603 switch (DestTy->getScalarTypeKind()) { 4604 case Type::STK_CPointer: 4605 return CK_BitCast; 4606 case Type::STK_BlockPointer: 4607 return (SrcKind == Type::STK_BlockPointer 4608 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 4609 case Type::STK_ObjCObjectPointer: 4610 if (SrcKind == Type::STK_ObjCObjectPointer) 4611 return CK_BitCast; 4612 if (SrcKind == Type::STK_CPointer) 4613 return CK_CPointerToObjCPointerCast; 4614 maybeExtendBlockObject(*this, Src); 4615 return CK_BlockPointerToObjCPointerCast; 4616 case Type::STK_Bool: 4617 return CK_PointerToBoolean; 4618 case Type::STK_Integral: 4619 return CK_PointerToIntegral; 4620 case Type::STK_Floating: 4621 case Type::STK_FloatingComplex: 4622 case Type::STK_IntegralComplex: 4623 case Type::STK_MemberPointer: 4624 llvm_unreachable("illegal cast from pointer"); 4625 } 4626 llvm_unreachable("Should have returned before this"); 4627 4628 case Type::STK_Bool: // casting from bool is like casting from an integer 4629 case Type::STK_Integral: 4630 switch (DestTy->getScalarTypeKind()) { 4631 case Type::STK_CPointer: 4632 case Type::STK_ObjCObjectPointer: 4633 case Type::STK_BlockPointer: 4634 if (Src.get()->isNullPointerConstant(Context, 4635 Expr::NPC_ValueDependentIsNull)) 4636 return CK_NullToPointer; 4637 return CK_IntegralToPointer; 4638 case Type::STK_Bool: 4639 return CK_IntegralToBoolean; 4640 case Type::STK_Integral: 4641 return CK_IntegralCast; 4642 case Type::STK_Floating: 4643 return CK_IntegralToFloating; 4644 case Type::STK_IntegralComplex: 4645 Src = ImpCastExprToType(Src.take(), 4646 DestTy->castAs<ComplexType>()->getElementType(), 4647 CK_IntegralCast); 4648 return CK_IntegralRealToComplex; 4649 case Type::STK_FloatingComplex: 4650 Src = ImpCastExprToType(Src.take(), 4651 DestTy->castAs<ComplexType>()->getElementType(), 4652 CK_IntegralToFloating); 4653 return CK_FloatingRealToComplex; 4654 case Type::STK_MemberPointer: 4655 llvm_unreachable("member pointer type in C"); 4656 } 4657 llvm_unreachable("Should have returned before this"); 4658 4659 case Type::STK_Floating: 4660 switch (DestTy->getScalarTypeKind()) { 4661 case Type::STK_Floating: 4662 return CK_FloatingCast; 4663 case Type::STK_Bool: 4664 return CK_FloatingToBoolean; 4665 case Type::STK_Integral: 4666 return CK_FloatingToIntegral; 4667 case Type::STK_FloatingComplex: 4668 Src = ImpCastExprToType(Src.take(), 4669 DestTy->castAs<ComplexType>()->getElementType(), 4670 CK_FloatingCast); 4671 return CK_FloatingRealToComplex; 4672 case Type::STK_IntegralComplex: 4673 Src = ImpCastExprToType(Src.take(), 4674 DestTy->castAs<ComplexType>()->getElementType(), 4675 CK_FloatingToIntegral); 4676 return CK_IntegralRealToComplex; 4677 case Type::STK_CPointer: 4678 case Type::STK_ObjCObjectPointer: 4679 case Type::STK_BlockPointer: 4680 llvm_unreachable("valid float->pointer cast?"); 4681 case Type::STK_MemberPointer: 4682 llvm_unreachable("member pointer type in C"); 4683 } 4684 llvm_unreachable("Should have returned before this"); 4685 4686 case Type::STK_FloatingComplex: 4687 switch (DestTy->getScalarTypeKind()) { 4688 case Type::STK_FloatingComplex: 4689 return CK_FloatingComplexCast; 4690 case Type::STK_IntegralComplex: 4691 return CK_FloatingComplexToIntegralComplex; 4692 case Type::STK_Floating: { 4693 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 4694 if (Context.hasSameType(ET, DestTy)) 4695 return CK_FloatingComplexToReal; 4696 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal); 4697 return CK_FloatingCast; 4698 } 4699 case Type::STK_Bool: 4700 return CK_FloatingComplexToBoolean; 4701 case Type::STK_Integral: 4702 Src = ImpCastExprToType(Src.take(), 4703 SrcTy->castAs<ComplexType>()->getElementType(), 4704 CK_FloatingComplexToReal); 4705 return CK_FloatingToIntegral; 4706 case Type::STK_CPointer: 4707 case Type::STK_ObjCObjectPointer: 4708 case Type::STK_BlockPointer: 4709 llvm_unreachable("valid complex float->pointer cast?"); 4710 case Type::STK_MemberPointer: 4711 llvm_unreachable("member pointer type in C"); 4712 } 4713 llvm_unreachable("Should have returned before this"); 4714 4715 case Type::STK_IntegralComplex: 4716 switch (DestTy->getScalarTypeKind()) { 4717 case Type::STK_FloatingComplex: 4718 return CK_IntegralComplexToFloatingComplex; 4719 case Type::STK_IntegralComplex: 4720 return CK_IntegralComplexCast; 4721 case Type::STK_Integral: { 4722 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 4723 if (Context.hasSameType(ET, DestTy)) 4724 return CK_IntegralComplexToReal; 4725 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal); 4726 return CK_IntegralCast; 4727 } 4728 case Type::STK_Bool: 4729 return CK_IntegralComplexToBoolean; 4730 case Type::STK_Floating: 4731 Src = ImpCastExprToType(Src.take(), 4732 SrcTy->castAs<ComplexType>()->getElementType(), 4733 CK_IntegralComplexToReal); 4734 return CK_IntegralToFloating; 4735 case Type::STK_CPointer: 4736 case Type::STK_ObjCObjectPointer: 4737 case Type::STK_BlockPointer: 4738 llvm_unreachable("valid complex int->pointer cast?"); 4739 case Type::STK_MemberPointer: 4740 llvm_unreachable("member pointer type in C"); 4741 } 4742 llvm_unreachable("Should have returned before this"); 4743 } 4744 4745 llvm_unreachable("Unhandled scalar cast"); 4746 } 4747 4748 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 4749 CastKind &Kind) { 4750 assert(VectorTy->isVectorType() && "Not a vector type!"); 4751 4752 if (Ty->isVectorType() || Ty->isIntegerType()) { 4753 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty)) 4754 return Diag(R.getBegin(), 4755 Ty->isVectorType() ? 4756 diag::err_invalid_conversion_between_vectors : 4757 diag::err_invalid_conversion_between_vector_and_integer) 4758 << VectorTy << Ty << R; 4759 } else 4760 return Diag(R.getBegin(), 4761 diag::err_invalid_conversion_between_vector_and_scalar) 4762 << VectorTy << Ty << R; 4763 4764 Kind = CK_BitCast; 4765 return false; 4766 } 4767 4768 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 4769 Expr *CastExpr, CastKind &Kind) { 4770 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 4771 4772 QualType SrcTy = CastExpr->getType(); 4773 4774 // If SrcTy is a VectorType, the total size must match to explicitly cast to 4775 // an ExtVectorType. 4776 // In OpenCL, casts between vectors of different types are not allowed. 4777 // (See OpenCL 6.2). 4778 if (SrcTy->isVectorType()) { 4779 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy) 4780 || (getLangOpts().OpenCL && 4781 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 4782 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 4783 << DestTy << SrcTy << R; 4784 return ExprError(); 4785 } 4786 Kind = CK_BitCast; 4787 return Owned(CastExpr); 4788 } 4789 4790 // All non-pointer scalars can be cast to ExtVector type. The appropriate 4791 // conversion will take place first from scalar to elt type, and then 4792 // splat from elt type to vector. 4793 if (SrcTy->isPointerType()) 4794 return Diag(R.getBegin(), 4795 diag::err_invalid_conversion_between_vector_and_scalar) 4796 << DestTy << SrcTy << R; 4797 4798 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType(); 4799 ExprResult CastExprRes = Owned(CastExpr); 4800 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy); 4801 if (CastExprRes.isInvalid()) 4802 return ExprError(); 4803 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take(); 4804 4805 Kind = CK_VectorSplat; 4806 return Owned(CastExpr); 4807 } 4808 4809 ExprResult 4810 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 4811 Declarator &D, ParsedType &Ty, 4812 SourceLocation RParenLoc, Expr *CastExpr) { 4813 assert(!D.isInvalidType() && (CastExpr != 0) && 4814 "ActOnCastExpr(): missing type or expr"); 4815 4816 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 4817 if (D.isInvalidType()) 4818 return ExprError(); 4819 4820 if (getLangOpts().CPlusPlus) { 4821 // Check that there are no default arguments (C++ only). 4822 CheckExtraCXXDefaultArguments(D); 4823 } 4824 4825 checkUnusedDeclAttributes(D); 4826 4827 QualType castType = castTInfo->getType(); 4828 Ty = CreateParsedType(castType, castTInfo); 4829 4830 bool isVectorLiteral = false; 4831 4832 // Check for an altivec or OpenCL literal, 4833 // i.e. all the elements are integer constants. 4834 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 4835 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 4836 if ((getLangOpts().AltiVec || getLangOpts().OpenCL) 4837 && castType->isVectorType() && (PE || PLE)) { 4838 if (PLE && PLE->getNumExprs() == 0) { 4839 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 4840 return ExprError(); 4841 } 4842 if (PE || PLE->getNumExprs() == 1) { 4843 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 4844 if (!E->getType()->isVectorType()) 4845 isVectorLiteral = true; 4846 } 4847 else 4848 isVectorLiteral = true; 4849 } 4850 4851 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 4852 // then handle it as such. 4853 if (isVectorLiteral) 4854 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 4855 4856 // If the Expr being casted is a ParenListExpr, handle it specially. 4857 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 4858 // sequence of BinOp comma operators. 4859 if (isa<ParenListExpr>(CastExpr)) { 4860 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 4861 if (Result.isInvalid()) return ExprError(); 4862 CastExpr = Result.take(); 4863 } 4864 4865 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 4866 } 4867 4868 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 4869 SourceLocation RParenLoc, Expr *E, 4870 TypeSourceInfo *TInfo) { 4871 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 4872 "Expected paren or paren list expression"); 4873 4874 Expr **exprs; 4875 unsigned numExprs; 4876 Expr *subExpr; 4877 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 4878 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 4879 LiteralLParenLoc = PE->getLParenLoc(); 4880 LiteralRParenLoc = PE->getRParenLoc(); 4881 exprs = PE->getExprs(); 4882 numExprs = PE->getNumExprs(); 4883 } else { // isa<ParenExpr> by assertion at function entrance 4884 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 4885 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 4886 subExpr = cast<ParenExpr>(E)->getSubExpr(); 4887 exprs = &subExpr; 4888 numExprs = 1; 4889 } 4890 4891 QualType Ty = TInfo->getType(); 4892 assert(Ty->isVectorType() && "Expected vector type"); 4893 4894 SmallVector<Expr *, 8> initExprs; 4895 const VectorType *VTy = Ty->getAs<VectorType>(); 4896 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 4897 4898 // '(...)' form of vector initialization in AltiVec: the number of 4899 // initializers must be one or must match the size of the vector. 4900 // If a single value is specified in the initializer then it will be 4901 // replicated to all the components of the vector 4902 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 4903 // The number of initializers must be one or must match the size of the 4904 // vector. If a single value is specified in the initializer then it will 4905 // be replicated to all the components of the vector 4906 if (numExprs == 1) { 4907 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 4908 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 4909 if (Literal.isInvalid()) 4910 return ExprError(); 4911 Literal = ImpCastExprToType(Literal.take(), ElemTy, 4912 PrepareScalarCast(Literal, ElemTy)); 4913 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 4914 } 4915 else if (numExprs < numElems) { 4916 Diag(E->getExprLoc(), 4917 diag::err_incorrect_number_of_vector_initializers); 4918 return ExprError(); 4919 } 4920 else 4921 initExprs.append(exprs, exprs + numExprs); 4922 } 4923 else { 4924 // For OpenCL, when the number of initializers is a single value, 4925 // it will be replicated to all components of the vector. 4926 if (getLangOpts().OpenCL && 4927 VTy->getVectorKind() == VectorType::GenericVector && 4928 numExprs == 1) { 4929 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 4930 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 4931 if (Literal.isInvalid()) 4932 return ExprError(); 4933 Literal = ImpCastExprToType(Literal.take(), ElemTy, 4934 PrepareScalarCast(Literal, ElemTy)); 4935 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 4936 } 4937 4938 initExprs.append(exprs, exprs + numExprs); 4939 } 4940 // FIXME: This means that pretty-printing the final AST will produce curly 4941 // braces instead of the original commas. 4942 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 4943 initExprs, LiteralRParenLoc); 4944 initE->setType(Ty); 4945 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 4946 } 4947 4948 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 4949 /// the ParenListExpr into a sequence of comma binary operators. 4950 ExprResult 4951 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 4952 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 4953 if (!E) 4954 return Owned(OrigExpr); 4955 4956 ExprResult Result(E->getExpr(0)); 4957 4958 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 4959 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 4960 E->getExpr(i)); 4961 4962 if (Result.isInvalid()) return ExprError(); 4963 4964 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 4965 } 4966 4967 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 4968 SourceLocation R, 4969 MultiExprArg Val) { 4970 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 4971 return Owned(expr); 4972 } 4973 4974 /// \brief Emit a specialized diagnostic when one expression is a null pointer 4975 /// constant and the other is not a pointer. Returns true if a diagnostic is 4976 /// emitted. 4977 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 4978 SourceLocation QuestionLoc) { 4979 Expr *NullExpr = LHSExpr; 4980 Expr *NonPointerExpr = RHSExpr; 4981 Expr::NullPointerConstantKind NullKind = 4982 NullExpr->isNullPointerConstant(Context, 4983 Expr::NPC_ValueDependentIsNotNull); 4984 4985 if (NullKind == Expr::NPCK_NotNull) { 4986 NullExpr = RHSExpr; 4987 NonPointerExpr = LHSExpr; 4988 NullKind = 4989 NullExpr->isNullPointerConstant(Context, 4990 Expr::NPC_ValueDependentIsNotNull); 4991 } 4992 4993 if (NullKind == Expr::NPCK_NotNull) 4994 return false; 4995 4996 if (NullKind == Expr::NPCK_ZeroExpression) 4997 return false; 4998 4999 if (NullKind == Expr::NPCK_ZeroLiteral) { 5000 // In this case, check to make sure that we got here from a "NULL" 5001 // string in the source code. 5002 NullExpr = NullExpr->IgnoreParenImpCasts(); 5003 SourceLocation loc = NullExpr->getExprLoc(); 5004 if (!findMacroSpelling(loc, "NULL")) 5005 return false; 5006 } 5007 5008 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 5009 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 5010 << NonPointerExpr->getType() << DiagType 5011 << NonPointerExpr->getSourceRange(); 5012 return true; 5013 } 5014 5015 /// \brief Return false if the condition expression is valid, true otherwise. 5016 static bool checkCondition(Sema &S, Expr *Cond) { 5017 QualType CondTy = Cond->getType(); 5018 5019 // C99 6.5.15p2 5020 if (CondTy->isScalarType()) return false; 5021 5022 // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar. 5023 if (S.getLangOpts().OpenCL && CondTy->isVectorType()) 5024 return false; 5025 5026 // Emit the proper error message. 5027 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ? 5028 diag::err_typecheck_cond_expect_scalar : 5029 diag::err_typecheck_cond_expect_scalar_or_vector) 5030 << CondTy; 5031 return true; 5032 } 5033 5034 /// \brief Return false if the two expressions can be converted to a vector, 5035 /// true otherwise 5036 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS, 5037 ExprResult &RHS, 5038 QualType CondTy) { 5039 // Both operands should be of scalar type. 5040 if (!LHS.get()->getType()->isScalarType()) { 5041 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 5042 << CondTy; 5043 return true; 5044 } 5045 if (!RHS.get()->getType()->isScalarType()) { 5046 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 5047 << CondTy; 5048 return true; 5049 } 5050 5051 // Implicity convert these scalars to the type of the condition. 5052 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast); 5053 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast); 5054 return false; 5055 } 5056 5057 /// \brief Handle when one or both operands are void type. 5058 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 5059 ExprResult &RHS) { 5060 Expr *LHSExpr = LHS.get(); 5061 Expr *RHSExpr = RHS.get(); 5062 5063 if (!LHSExpr->getType()->isVoidType()) 5064 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5065 << RHSExpr->getSourceRange(); 5066 if (!RHSExpr->getType()->isVoidType()) 5067 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5068 << LHSExpr->getSourceRange(); 5069 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid); 5070 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid); 5071 return S.Context.VoidTy; 5072 } 5073 5074 /// \brief Return false if the NullExpr can be promoted to PointerTy, 5075 /// true otherwise. 5076 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 5077 QualType PointerTy) { 5078 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 5079 !NullExpr.get()->isNullPointerConstant(S.Context, 5080 Expr::NPC_ValueDependentIsNull)) 5081 return true; 5082 5083 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer); 5084 return false; 5085 } 5086 5087 /// \brief Checks compatibility between two pointers and return the resulting 5088 /// type. 5089 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 5090 ExprResult &RHS, 5091 SourceLocation Loc) { 5092 QualType LHSTy = LHS.get()->getType(); 5093 QualType RHSTy = RHS.get()->getType(); 5094 5095 if (S.Context.hasSameType(LHSTy, RHSTy)) { 5096 // Two identical pointers types are always compatible. 5097 return LHSTy; 5098 } 5099 5100 QualType lhptee, rhptee; 5101 5102 // Get the pointee types. 5103 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 5104 lhptee = LHSBTy->getPointeeType(); 5105 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 5106 } else { 5107 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 5108 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 5109 } 5110 5111 // C99 6.5.15p6: If both operands are pointers to compatible types or to 5112 // differently qualified versions of compatible types, the result type is 5113 // a pointer to an appropriately qualified version of the composite 5114 // type. 5115 5116 // Only CVR-qualifiers exist in the standard, and the differently-qualified 5117 // clause doesn't make sense for our extensions. E.g. address space 2 should 5118 // be incompatible with address space 3: they may live on different devices or 5119 // anything. 5120 Qualifiers lhQual = lhptee.getQualifiers(); 5121 Qualifiers rhQual = rhptee.getQualifiers(); 5122 5123 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 5124 lhQual.removeCVRQualifiers(); 5125 rhQual.removeCVRQualifiers(); 5126 5127 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 5128 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 5129 5130 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 5131 5132 if (CompositeTy.isNull()) { 5133 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers) 5134 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5135 << RHS.get()->getSourceRange(); 5136 // In this situation, we assume void* type. No especially good 5137 // reason, but this is what gcc does, and we do have to pick 5138 // to get a consistent AST. 5139 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy); 5140 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 5141 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 5142 return incompatTy; 5143 } 5144 5145 // The pointer types are compatible. 5146 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 5147 ResultTy = S.Context.getPointerType(ResultTy); 5148 5149 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast); 5150 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast); 5151 return ResultTy; 5152 } 5153 5154 /// \brief Return the resulting type when the operands are both block pointers. 5155 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 5156 ExprResult &LHS, 5157 ExprResult &RHS, 5158 SourceLocation Loc) { 5159 QualType LHSTy = LHS.get()->getType(); 5160 QualType RHSTy = RHS.get()->getType(); 5161 5162 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 5163 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 5164 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 5165 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5166 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5167 return destType; 5168 } 5169 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 5170 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5171 << RHS.get()->getSourceRange(); 5172 return QualType(); 5173 } 5174 5175 // We have 2 block pointer types. 5176 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 5177 } 5178 5179 /// \brief Return the resulting type when the operands are both pointers. 5180 static QualType 5181 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 5182 ExprResult &RHS, 5183 SourceLocation Loc) { 5184 // get the pointer types 5185 QualType LHSTy = LHS.get()->getType(); 5186 QualType RHSTy = RHS.get()->getType(); 5187 5188 // get the "pointed to" types 5189 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5190 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5191 5192 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 5193 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 5194 // Figure out necessary qualifiers (C99 6.5.15p6) 5195 QualType destPointee 5196 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5197 QualType destType = S.Context.getPointerType(destPointee); 5198 // Add qualifiers if necessary. 5199 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp); 5200 // Promote to void*. 5201 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5202 return destType; 5203 } 5204 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 5205 QualType destPointee 5206 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5207 QualType destType = S.Context.getPointerType(destPointee); 5208 // Add qualifiers if necessary. 5209 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp); 5210 // Promote to void*. 5211 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5212 return destType; 5213 } 5214 5215 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 5216 } 5217 5218 /// \brief Return false if the first expression is not an integer and the second 5219 /// expression is not a pointer, true otherwise. 5220 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 5221 Expr* PointerExpr, SourceLocation Loc, 5222 bool IsIntFirstExpr) { 5223 if (!PointerExpr->getType()->isPointerType() || 5224 !Int.get()->getType()->isIntegerType()) 5225 return false; 5226 5227 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 5228 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 5229 5230 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch) 5231 << Expr1->getType() << Expr2->getType() 5232 << Expr1->getSourceRange() << Expr2->getSourceRange(); 5233 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(), 5234 CK_IntegralToPointer); 5235 return true; 5236 } 5237 5238 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 5239 /// In that case, LHS = cond. 5240 /// C99 6.5.15 5241 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 5242 ExprResult &RHS, ExprValueKind &VK, 5243 ExprObjectKind &OK, 5244 SourceLocation QuestionLoc) { 5245 5246 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 5247 if (!LHSResult.isUsable()) return QualType(); 5248 LHS = LHSResult; 5249 5250 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 5251 if (!RHSResult.isUsable()) return QualType(); 5252 RHS = RHSResult; 5253 5254 // C++ is sufficiently different to merit its own checker. 5255 if (getLangOpts().CPlusPlus) 5256 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 5257 5258 VK = VK_RValue; 5259 OK = OK_Ordinary; 5260 5261 Cond = UsualUnaryConversions(Cond.take()); 5262 if (Cond.isInvalid()) 5263 return QualType(); 5264 LHS = UsualUnaryConversions(LHS.take()); 5265 if (LHS.isInvalid()) 5266 return QualType(); 5267 RHS = UsualUnaryConversions(RHS.take()); 5268 if (RHS.isInvalid()) 5269 return QualType(); 5270 5271 QualType CondTy = Cond.get()->getType(); 5272 QualType LHSTy = LHS.get()->getType(); 5273 QualType RHSTy = RHS.get()->getType(); 5274 5275 // first, check the condition. 5276 if (checkCondition(*this, Cond.get())) 5277 return QualType(); 5278 5279 // Now check the two expressions. 5280 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 5281 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false); 5282 5283 // If the condition is a vector, and both operands are scalar, 5284 // attempt to implicity convert them to the vector type to act like the 5285 // built in select. (OpenCL v1.1 s6.3.i) 5286 if (getLangOpts().OpenCL && CondTy->isVectorType()) 5287 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy)) 5288 return QualType(); 5289 5290 // If both operands have arithmetic type, do the usual arithmetic conversions 5291 // to find a common type: C99 6.5.15p3,5. 5292 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 5293 UsualArithmeticConversions(LHS, RHS); 5294 if (LHS.isInvalid() || RHS.isInvalid()) 5295 return QualType(); 5296 return LHS.get()->getType(); 5297 } 5298 5299 // If both operands are the same structure or union type, the result is that 5300 // type. 5301 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 5302 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 5303 if (LHSRT->getDecl() == RHSRT->getDecl()) 5304 // "If both the operands have structure or union type, the result has 5305 // that type." This implies that CV qualifiers are dropped. 5306 return LHSTy.getUnqualifiedType(); 5307 // FIXME: Type of conditional expression must be complete in C mode. 5308 } 5309 5310 // C99 6.5.15p5: "If both operands have void type, the result has void type." 5311 // The following || allows only one side to be void (a GCC-ism). 5312 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 5313 return checkConditionalVoidType(*this, LHS, RHS); 5314 } 5315 5316 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 5317 // the type of the other operand." 5318 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 5319 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 5320 5321 // All objective-c pointer type analysis is done here. 5322 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 5323 QuestionLoc); 5324 if (LHS.isInvalid() || RHS.isInvalid()) 5325 return QualType(); 5326 if (!compositeType.isNull()) 5327 return compositeType; 5328 5329 5330 // Handle block pointer types. 5331 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 5332 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 5333 QuestionLoc); 5334 5335 // Check constraints for C object pointers types (C99 6.5.15p3,6). 5336 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 5337 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 5338 QuestionLoc); 5339 5340 // GCC compatibility: soften pointer/integer mismatch. Note that 5341 // null pointers have been filtered out by this point. 5342 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 5343 /*isIntFirstExpr=*/true)) 5344 return RHSTy; 5345 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 5346 /*isIntFirstExpr=*/false)) 5347 return LHSTy; 5348 5349 // Emit a better diagnostic if one of the expressions is a null pointer 5350 // constant and the other is not a pointer type. In this case, the user most 5351 // likely forgot to take the address of the other expression. 5352 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 5353 return QualType(); 5354 5355 // Otherwise, the operands are not compatible. 5356 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 5357 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5358 << RHS.get()->getSourceRange(); 5359 return QualType(); 5360 } 5361 5362 /// FindCompositeObjCPointerType - Helper method to find composite type of 5363 /// two objective-c pointer types of the two input expressions. 5364 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 5365 SourceLocation QuestionLoc) { 5366 QualType LHSTy = LHS.get()->getType(); 5367 QualType RHSTy = RHS.get()->getType(); 5368 5369 // Handle things like Class and struct objc_class*. Here we case the result 5370 // to the pseudo-builtin, because that will be implicitly cast back to the 5371 // redefinition type if an attempt is made to access its fields. 5372 if (LHSTy->isObjCClassType() && 5373 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 5374 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 5375 return LHSTy; 5376 } 5377 if (RHSTy->isObjCClassType() && 5378 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 5379 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 5380 return RHSTy; 5381 } 5382 // And the same for struct objc_object* / id 5383 if (LHSTy->isObjCIdType() && 5384 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 5385 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 5386 return LHSTy; 5387 } 5388 if (RHSTy->isObjCIdType() && 5389 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 5390 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 5391 return RHSTy; 5392 } 5393 // And the same for struct objc_selector* / SEL 5394 if (Context.isObjCSelType(LHSTy) && 5395 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 5396 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast); 5397 return LHSTy; 5398 } 5399 if (Context.isObjCSelType(RHSTy) && 5400 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 5401 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast); 5402 return RHSTy; 5403 } 5404 // Check constraints for Objective-C object pointers types. 5405 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 5406 5407 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 5408 // Two identical object pointer types are always compatible. 5409 return LHSTy; 5410 } 5411 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 5412 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 5413 QualType compositeType = LHSTy; 5414 5415 // If both operands are interfaces and either operand can be 5416 // assigned to the other, use that type as the composite 5417 // type. This allows 5418 // xxx ? (A*) a : (B*) b 5419 // where B is a subclass of A. 5420 // 5421 // Additionally, as for assignment, if either type is 'id' 5422 // allow silent coercion. Finally, if the types are 5423 // incompatible then make sure to use 'id' as the composite 5424 // type so the result is acceptable for sending messages to. 5425 5426 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 5427 // It could return the composite type. 5428 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 5429 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 5430 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 5431 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 5432 } else if ((LHSTy->isObjCQualifiedIdType() || 5433 RHSTy->isObjCQualifiedIdType()) && 5434 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 5435 // Need to handle "id<xx>" explicitly. 5436 // GCC allows qualified id and any Objective-C type to devolve to 5437 // id. Currently localizing to here until clear this should be 5438 // part of ObjCQualifiedIdTypesAreCompatible. 5439 compositeType = Context.getObjCIdType(); 5440 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 5441 compositeType = Context.getObjCIdType(); 5442 } else if (!(compositeType = 5443 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) 5444 ; 5445 else { 5446 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 5447 << LHSTy << RHSTy 5448 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5449 QualType incompatTy = Context.getObjCIdType(); 5450 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 5451 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 5452 return incompatTy; 5453 } 5454 // The object pointer types are compatible. 5455 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast); 5456 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast); 5457 return compositeType; 5458 } 5459 // Check Objective-C object pointer types and 'void *' 5460 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 5461 if (getLangOpts().ObjCAutoRefCount) { 5462 // ARC forbids the implicit conversion of object pointers to 'void *', 5463 // so these types are not compatible. 5464 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 5465 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5466 LHS = RHS = true; 5467 return QualType(); 5468 } 5469 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5470 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5471 QualType destPointee 5472 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5473 QualType destType = Context.getPointerType(destPointee); 5474 // Add qualifiers if necessary. 5475 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp); 5476 // Promote to void*. 5477 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5478 return destType; 5479 } 5480 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 5481 if (getLangOpts().ObjCAutoRefCount) { 5482 // ARC forbids the implicit conversion of object pointers to 'void *', 5483 // so these types are not compatible. 5484 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 5485 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5486 LHS = RHS = true; 5487 return QualType(); 5488 } 5489 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5490 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5491 QualType destPointee 5492 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5493 QualType destType = Context.getPointerType(destPointee); 5494 // Add qualifiers if necessary. 5495 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp); 5496 // Promote to void*. 5497 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5498 return destType; 5499 } 5500 return QualType(); 5501 } 5502 5503 /// SuggestParentheses - Emit a note with a fixit hint that wraps 5504 /// ParenRange in parentheses. 5505 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 5506 const PartialDiagnostic &Note, 5507 SourceRange ParenRange) { 5508 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd()); 5509 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 5510 EndLoc.isValid()) { 5511 Self.Diag(Loc, Note) 5512 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 5513 << FixItHint::CreateInsertion(EndLoc, ")"); 5514 } else { 5515 // We can't display the parentheses, so just show the bare note. 5516 Self.Diag(Loc, Note) << ParenRange; 5517 } 5518 } 5519 5520 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 5521 return Opc >= BO_Mul && Opc <= BO_Shr; 5522 } 5523 5524 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 5525 /// expression, either using a built-in or overloaded operator, 5526 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 5527 /// expression. 5528 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 5529 Expr **RHSExprs) { 5530 // Don't strip parenthesis: we should not warn if E is in parenthesis. 5531 E = E->IgnoreImpCasts(); 5532 E = E->IgnoreConversionOperator(); 5533 E = E->IgnoreImpCasts(); 5534 5535 // Built-in binary operator. 5536 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 5537 if (IsArithmeticOp(OP->getOpcode())) { 5538 *Opcode = OP->getOpcode(); 5539 *RHSExprs = OP->getRHS(); 5540 return true; 5541 } 5542 } 5543 5544 // Overloaded operator. 5545 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 5546 if (Call->getNumArgs() != 2) 5547 return false; 5548 5549 // Make sure this is really a binary operator that is safe to pass into 5550 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 5551 OverloadedOperatorKind OO = Call->getOperator(); 5552 if (OO < OO_Plus || OO > OO_Arrow || 5553 OO == OO_PlusPlus || OO == OO_MinusMinus) 5554 return false; 5555 5556 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 5557 if (IsArithmeticOp(OpKind)) { 5558 *Opcode = OpKind; 5559 *RHSExprs = Call->getArg(1); 5560 return true; 5561 } 5562 } 5563 5564 return false; 5565 } 5566 5567 static bool IsLogicOp(BinaryOperatorKind Opc) { 5568 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr); 5569 } 5570 5571 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 5572 /// or is a logical expression such as (x==y) which has int type, but is 5573 /// commonly interpreted as boolean. 5574 static bool ExprLooksBoolean(Expr *E) { 5575 E = E->IgnoreParenImpCasts(); 5576 5577 if (E->getType()->isBooleanType()) 5578 return true; 5579 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 5580 return IsLogicOp(OP->getOpcode()); 5581 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 5582 return OP->getOpcode() == UO_LNot; 5583 5584 return false; 5585 } 5586 5587 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 5588 /// and binary operator are mixed in a way that suggests the programmer assumed 5589 /// the conditional operator has higher precedence, for example: 5590 /// "int x = a + someBinaryCondition ? 1 : 2". 5591 static void DiagnoseConditionalPrecedence(Sema &Self, 5592 SourceLocation OpLoc, 5593 Expr *Condition, 5594 Expr *LHSExpr, 5595 Expr *RHSExpr) { 5596 BinaryOperatorKind CondOpcode; 5597 Expr *CondRHS; 5598 5599 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 5600 return; 5601 if (!ExprLooksBoolean(CondRHS)) 5602 return; 5603 5604 // The condition is an arithmetic binary expression, with a right- 5605 // hand side that looks boolean, so warn. 5606 5607 Self.Diag(OpLoc, diag::warn_precedence_conditional) 5608 << Condition->getSourceRange() 5609 << BinaryOperator::getOpcodeStr(CondOpcode); 5610 5611 SuggestParentheses(Self, OpLoc, 5612 Self.PDiag(diag::note_precedence_silence) 5613 << BinaryOperator::getOpcodeStr(CondOpcode), 5614 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 5615 5616 SuggestParentheses(Self, OpLoc, 5617 Self.PDiag(diag::note_precedence_conditional_first), 5618 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 5619 } 5620 5621 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 5622 /// in the case of a the GNU conditional expr extension. 5623 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 5624 SourceLocation ColonLoc, 5625 Expr *CondExpr, Expr *LHSExpr, 5626 Expr *RHSExpr) { 5627 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 5628 // was the condition. 5629 OpaqueValueExpr *opaqueValue = 0; 5630 Expr *commonExpr = 0; 5631 if (LHSExpr == 0) { 5632 commonExpr = CondExpr; 5633 5634 // We usually want to apply unary conversions *before* saving, except 5635 // in the special case of a C++ l-value conditional. 5636 if (!(getLangOpts().CPlusPlus 5637 && !commonExpr->isTypeDependent() 5638 && commonExpr->getValueKind() == RHSExpr->getValueKind() 5639 && commonExpr->isGLValue() 5640 && commonExpr->isOrdinaryOrBitFieldObject() 5641 && RHSExpr->isOrdinaryOrBitFieldObject() 5642 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 5643 ExprResult commonRes = UsualUnaryConversions(commonExpr); 5644 if (commonRes.isInvalid()) 5645 return ExprError(); 5646 commonExpr = commonRes.take(); 5647 } 5648 5649 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 5650 commonExpr->getType(), 5651 commonExpr->getValueKind(), 5652 commonExpr->getObjectKind(), 5653 commonExpr); 5654 LHSExpr = CondExpr = opaqueValue; 5655 } 5656 5657 ExprValueKind VK = VK_RValue; 5658 ExprObjectKind OK = OK_Ordinary; 5659 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 5660 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 5661 VK, OK, QuestionLoc); 5662 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 5663 RHS.isInvalid()) 5664 return ExprError(); 5665 5666 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 5667 RHS.get()); 5668 5669 if (!commonExpr) 5670 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc, 5671 LHS.take(), ColonLoc, 5672 RHS.take(), result, VK, OK)); 5673 5674 return Owned(new (Context) 5675 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(), 5676 RHS.take(), QuestionLoc, ColonLoc, result, VK, 5677 OK)); 5678 } 5679 5680 // checkPointerTypesForAssignment - This is a very tricky routine (despite 5681 // being closely modeled after the C99 spec:-). The odd characteristic of this 5682 // routine is it effectively iqnores the qualifiers on the top level pointee. 5683 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 5684 // FIXME: add a couple examples in this comment. 5685 static Sema::AssignConvertType 5686 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 5687 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 5688 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 5689 5690 // get the "pointed to" type (ignoring qualifiers at the top level) 5691 const Type *lhptee, *rhptee; 5692 Qualifiers lhq, rhq; 5693 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split(); 5694 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split(); 5695 5696 Sema::AssignConvertType ConvTy = Sema::Compatible; 5697 5698 // C99 6.5.16.1p1: This following citation is common to constraints 5699 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 5700 // qualifiers of the type *pointed to* by the right; 5701 Qualifiers lq; 5702 5703 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 5704 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 5705 lhq.compatiblyIncludesObjCLifetime(rhq)) { 5706 // Ignore lifetime for further calculation. 5707 lhq.removeObjCLifetime(); 5708 rhq.removeObjCLifetime(); 5709 } 5710 5711 if (!lhq.compatiblyIncludes(rhq)) { 5712 // Treat address-space mismatches as fatal. TODO: address subspaces 5713 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 5714 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 5715 5716 // It's okay to add or remove GC or lifetime qualifiers when converting to 5717 // and from void*. 5718 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 5719 .compatiblyIncludes( 5720 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 5721 && (lhptee->isVoidType() || rhptee->isVoidType())) 5722 ; // keep old 5723 5724 // Treat lifetime mismatches as fatal. 5725 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 5726 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 5727 5728 // For GCC compatibility, other qualifier mismatches are treated 5729 // as still compatible in C. 5730 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 5731 } 5732 5733 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 5734 // incomplete type and the other is a pointer to a qualified or unqualified 5735 // version of void... 5736 if (lhptee->isVoidType()) { 5737 if (rhptee->isIncompleteOrObjectType()) 5738 return ConvTy; 5739 5740 // As an extension, we allow cast to/from void* to function pointer. 5741 assert(rhptee->isFunctionType()); 5742 return Sema::FunctionVoidPointer; 5743 } 5744 5745 if (rhptee->isVoidType()) { 5746 if (lhptee->isIncompleteOrObjectType()) 5747 return ConvTy; 5748 5749 // As an extension, we allow cast to/from void* to function pointer. 5750 assert(lhptee->isFunctionType()); 5751 return Sema::FunctionVoidPointer; 5752 } 5753 5754 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 5755 // unqualified versions of compatible types, ... 5756 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 5757 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 5758 // Check if the pointee types are compatible ignoring the sign. 5759 // We explicitly check for char so that we catch "char" vs 5760 // "unsigned char" on systems where "char" is unsigned. 5761 if (lhptee->isCharType()) 5762 ltrans = S.Context.UnsignedCharTy; 5763 else if (lhptee->hasSignedIntegerRepresentation()) 5764 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 5765 5766 if (rhptee->isCharType()) 5767 rtrans = S.Context.UnsignedCharTy; 5768 else if (rhptee->hasSignedIntegerRepresentation()) 5769 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 5770 5771 if (ltrans == rtrans) { 5772 // Types are compatible ignoring the sign. Qualifier incompatibility 5773 // takes priority over sign incompatibility because the sign 5774 // warning can be disabled. 5775 if (ConvTy != Sema::Compatible) 5776 return ConvTy; 5777 5778 return Sema::IncompatiblePointerSign; 5779 } 5780 5781 // If we are a multi-level pointer, it's possible that our issue is simply 5782 // one of qualification - e.g. char ** -> const char ** is not allowed. If 5783 // the eventual target type is the same and the pointers have the same 5784 // level of indirection, this must be the issue. 5785 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 5786 do { 5787 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 5788 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 5789 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 5790 5791 if (lhptee == rhptee) 5792 return Sema::IncompatibleNestedPointerQualifiers; 5793 } 5794 5795 // General pointer incompatibility takes priority over qualifiers. 5796 return Sema::IncompatiblePointer; 5797 } 5798 if (!S.getLangOpts().CPlusPlus && 5799 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 5800 return Sema::IncompatiblePointer; 5801 return ConvTy; 5802 } 5803 5804 /// checkBlockPointerTypesForAssignment - This routine determines whether two 5805 /// block pointer types are compatible or whether a block and normal pointer 5806 /// are compatible. It is more restrict than comparing two function pointer 5807 // types. 5808 static Sema::AssignConvertType 5809 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 5810 QualType RHSType) { 5811 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 5812 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 5813 5814 QualType lhptee, rhptee; 5815 5816 // get the "pointed to" type (ignoring qualifiers at the top level) 5817 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 5818 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 5819 5820 // In C++, the types have to match exactly. 5821 if (S.getLangOpts().CPlusPlus) 5822 return Sema::IncompatibleBlockPointer; 5823 5824 Sema::AssignConvertType ConvTy = Sema::Compatible; 5825 5826 // For blocks we enforce that qualifiers are identical. 5827 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 5828 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 5829 5830 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 5831 return Sema::IncompatibleBlockPointer; 5832 5833 return ConvTy; 5834 } 5835 5836 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 5837 /// for assignment compatibility. 5838 static Sema::AssignConvertType 5839 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 5840 QualType RHSType) { 5841 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 5842 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 5843 5844 if (LHSType->isObjCBuiltinType()) { 5845 // Class is not compatible with ObjC object pointers. 5846 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 5847 !RHSType->isObjCQualifiedClassType()) 5848 return Sema::IncompatiblePointer; 5849 return Sema::Compatible; 5850 } 5851 if (RHSType->isObjCBuiltinType()) { 5852 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 5853 !LHSType->isObjCQualifiedClassType()) 5854 return Sema::IncompatiblePointer; 5855 return Sema::Compatible; 5856 } 5857 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 5858 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 5859 5860 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 5861 // make an exception for id<P> 5862 !LHSType->isObjCQualifiedIdType()) 5863 return Sema::CompatiblePointerDiscardsQualifiers; 5864 5865 if (S.Context.typesAreCompatible(LHSType, RHSType)) 5866 return Sema::Compatible; 5867 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 5868 return Sema::IncompatibleObjCQualifiedId; 5869 return Sema::IncompatiblePointer; 5870 } 5871 5872 Sema::AssignConvertType 5873 Sema::CheckAssignmentConstraints(SourceLocation Loc, 5874 QualType LHSType, QualType RHSType) { 5875 // Fake up an opaque expression. We don't actually care about what 5876 // cast operations are required, so if CheckAssignmentConstraints 5877 // adds casts to this they'll be wasted, but fortunately that doesn't 5878 // usually happen on valid code. 5879 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 5880 ExprResult RHSPtr = &RHSExpr; 5881 CastKind K = CK_Invalid; 5882 5883 return CheckAssignmentConstraints(LHSType, RHSPtr, K); 5884 } 5885 5886 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 5887 /// has code to accommodate several GCC extensions when type checking 5888 /// pointers. Here are some objectionable examples that GCC considers warnings: 5889 /// 5890 /// int a, *pint; 5891 /// short *pshort; 5892 /// struct foo *pfoo; 5893 /// 5894 /// pint = pshort; // warning: assignment from incompatible pointer type 5895 /// a = pint; // warning: assignment makes integer from pointer without a cast 5896 /// pint = a; // warning: assignment makes pointer from integer without a cast 5897 /// pint = pfoo; // warning: assignment from incompatible pointer type 5898 /// 5899 /// As a result, the code for dealing with pointers is more complex than the 5900 /// C99 spec dictates. 5901 /// 5902 /// Sets 'Kind' for any result kind except Incompatible. 5903 Sema::AssignConvertType 5904 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 5905 CastKind &Kind) { 5906 QualType RHSType = RHS.get()->getType(); 5907 QualType OrigLHSType = LHSType; 5908 5909 // Get canonical types. We're not formatting these types, just comparing 5910 // them. 5911 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 5912 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 5913 5914 // Common case: no conversion required. 5915 if (LHSType == RHSType) { 5916 Kind = CK_NoOp; 5917 return Compatible; 5918 } 5919 5920 // If we have an atomic type, try a non-atomic assignment, then just add an 5921 // atomic qualification step. 5922 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 5923 Sema::AssignConvertType result = 5924 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 5925 if (result != Compatible) 5926 return result; 5927 if (Kind != CK_NoOp) 5928 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind); 5929 Kind = CK_NonAtomicToAtomic; 5930 return Compatible; 5931 } 5932 5933 // If the left-hand side is a reference type, then we are in a 5934 // (rare!) case where we've allowed the use of references in C, 5935 // e.g., as a parameter type in a built-in function. In this case, 5936 // just make sure that the type referenced is compatible with the 5937 // right-hand side type. The caller is responsible for adjusting 5938 // LHSType so that the resulting expression does not have reference 5939 // type. 5940 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 5941 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 5942 Kind = CK_LValueBitCast; 5943 return Compatible; 5944 } 5945 return Incompatible; 5946 } 5947 5948 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 5949 // to the same ExtVector type. 5950 if (LHSType->isExtVectorType()) { 5951 if (RHSType->isExtVectorType()) 5952 return Incompatible; 5953 if (RHSType->isArithmeticType()) { 5954 // CK_VectorSplat does T -> vector T, so first cast to the 5955 // element type. 5956 QualType elType = cast<ExtVectorType>(LHSType)->getElementType(); 5957 if (elType != RHSType) { 5958 Kind = PrepareScalarCast(RHS, elType); 5959 RHS = ImpCastExprToType(RHS.take(), elType, Kind); 5960 } 5961 Kind = CK_VectorSplat; 5962 return Compatible; 5963 } 5964 } 5965 5966 // Conversions to or from vector type. 5967 if (LHSType->isVectorType() || RHSType->isVectorType()) { 5968 if (LHSType->isVectorType() && RHSType->isVectorType()) { 5969 // Allow assignments of an AltiVec vector type to an equivalent GCC 5970 // vector type and vice versa 5971 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 5972 Kind = CK_BitCast; 5973 return Compatible; 5974 } 5975 5976 // If we are allowing lax vector conversions, and LHS and RHS are both 5977 // vectors, the total size only needs to be the same. This is a bitcast; 5978 // no bits are changed but the result type is different. 5979 if (getLangOpts().LaxVectorConversions && 5980 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) { 5981 Kind = CK_BitCast; 5982 return IncompatibleVectors; 5983 } 5984 } 5985 return Incompatible; 5986 } 5987 5988 // Arithmetic conversions. 5989 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 5990 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 5991 Kind = PrepareScalarCast(RHS, LHSType); 5992 return Compatible; 5993 } 5994 5995 // Conversions to normal pointers. 5996 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 5997 // U* -> T* 5998 if (isa<PointerType>(RHSType)) { 5999 Kind = CK_BitCast; 6000 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 6001 } 6002 6003 // int -> T* 6004 if (RHSType->isIntegerType()) { 6005 Kind = CK_IntegralToPointer; // FIXME: null? 6006 return IntToPointer; 6007 } 6008 6009 // C pointers are not compatible with ObjC object pointers, 6010 // with two exceptions: 6011 if (isa<ObjCObjectPointerType>(RHSType)) { 6012 // - conversions to void* 6013 if (LHSPointer->getPointeeType()->isVoidType()) { 6014 Kind = CK_BitCast; 6015 return Compatible; 6016 } 6017 6018 // - conversions from 'Class' to the redefinition type 6019 if (RHSType->isObjCClassType() && 6020 Context.hasSameType(LHSType, 6021 Context.getObjCClassRedefinitionType())) { 6022 Kind = CK_BitCast; 6023 return Compatible; 6024 } 6025 6026 Kind = CK_BitCast; 6027 return IncompatiblePointer; 6028 } 6029 6030 // U^ -> void* 6031 if (RHSType->getAs<BlockPointerType>()) { 6032 if (LHSPointer->getPointeeType()->isVoidType()) { 6033 Kind = CK_BitCast; 6034 return Compatible; 6035 } 6036 } 6037 6038 return Incompatible; 6039 } 6040 6041 // Conversions to block pointers. 6042 if (isa<BlockPointerType>(LHSType)) { 6043 // U^ -> T^ 6044 if (RHSType->isBlockPointerType()) { 6045 Kind = CK_BitCast; 6046 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 6047 } 6048 6049 // int or null -> T^ 6050 if (RHSType->isIntegerType()) { 6051 Kind = CK_IntegralToPointer; // FIXME: null 6052 return IntToBlockPointer; 6053 } 6054 6055 // id -> T^ 6056 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 6057 Kind = CK_AnyPointerToBlockPointerCast; 6058 return Compatible; 6059 } 6060 6061 // void* -> T^ 6062 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 6063 if (RHSPT->getPointeeType()->isVoidType()) { 6064 Kind = CK_AnyPointerToBlockPointerCast; 6065 return Compatible; 6066 } 6067 6068 return Incompatible; 6069 } 6070 6071 // Conversions to Objective-C pointers. 6072 if (isa<ObjCObjectPointerType>(LHSType)) { 6073 // A* -> B* 6074 if (RHSType->isObjCObjectPointerType()) { 6075 Kind = CK_BitCast; 6076 Sema::AssignConvertType result = 6077 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 6078 if (getLangOpts().ObjCAutoRefCount && 6079 result == Compatible && 6080 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 6081 result = IncompatibleObjCWeakRef; 6082 return result; 6083 } 6084 6085 // int or null -> A* 6086 if (RHSType->isIntegerType()) { 6087 Kind = CK_IntegralToPointer; // FIXME: null 6088 return IntToPointer; 6089 } 6090 6091 // In general, C pointers are not compatible with ObjC object pointers, 6092 // with two exceptions: 6093 if (isa<PointerType>(RHSType)) { 6094 Kind = CK_CPointerToObjCPointerCast; 6095 6096 // - conversions from 'void*' 6097 if (RHSType->isVoidPointerType()) { 6098 return Compatible; 6099 } 6100 6101 // - conversions to 'Class' from its redefinition type 6102 if (LHSType->isObjCClassType() && 6103 Context.hasSameType(RHSType, 6104 Context.getObjCClassRedefinitionType())) { 6105 return Compatible; 6106 } 6107 6108 return IncompatiblePointer; 6109 } 6110 6111 // T^ -> A* 6112 if (RHSType->isBlockPointerType()) { 6113 maybeExtendBlockObject(*this, RHS); 6114 Kind = CK_BlockPointerToObjCPointerCast; 6115 return Compatible; 6116 } 6117 6118 return Incompatible; 6119 } 6120 6121 // Conversions from pointers that are not covered by the above. 6122 if (isa<PointerType>(RHSType)) { 6123 // T* -> _Bool 6124 if (LHSType == Context.BoolTy) { 6125 Kind = CK_PointerToBoolean; 6126 return Compatible; 6127 } 6128 6129 // T* -> int 6130 if (LHSType->isIntegerType()) { 6131 Kind = CK_PointerToIntegral; 6132 return PointerToInt; 6133 } 6134 6135 return Incompatible; 6136 } 6137 6138 // Conversions from Objective-C pointers that are not covered by the above. 6139 if (isa<ObjCObjectPointerType>(RHSType)) { 6140 // T* -> _Bool 6141 if (LHSType == Context.BoolTy) { 6142 Kind = CK_PointerToBoolean; 6143 return Compatible; 6144 } 6145 6146 // T* -> int 6147 if (LHSType->isIntegerType()) { 6148 Kind = CK_PointerToIntegral; 6149 return PointerToInt; 6150 } 6151 6152 return Incompatible; 6153 } 6154 6155 // struct A -> struct B 6156 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 6157 if (Context.typesAreCompatible(LHSType, RHSType)) { 6158 Kind = CK_NoOp; 6159 return Compatible; 6160 } 6161 } 6162 6163 return Incompatible; 6164 } 6165 6166 /// \brief Constructs a transparent union from an expression that is 6167 /// used to initialize the transparent union. 6168 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 6169 ExprResult &EResult, QualType UnionType, 6170 FieldDecl *Field) { 6171 // Build an initializer list that designates the appropriate member 6172 // of the transparent union. 6173 Expr *E = EResult.take(); 6174 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 6175 E, SourceLocation()); 6176 Initializer->setType(UnionType); 6177 Initializer->setInitializedFieldInUnion(Field); 6178 6179 // Build a compound literal constructing a value of the transparent 6180 // union type from this initializer list. 6181 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 6182 EResult = S.Owned( 6183 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 6184 VK_RValue, Initializer, false)); 6185 } 6186 6187 Sema::AssignConvertType 6188 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 6189 ExprResult &RHS) { 6190 QualType RHSType = RHS.get()->getType(); 6191 6192 // If the ArgType is a Union type, we want to handle a potential 6193 // transparent_union GCC extension. 6194 const RecordType *UT = ArgType->getAsUnionType(); 6195 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 6196 return Incompatible; 6197 6198 // The field to initialize within the transparent union. 6199 RecordDecl *UD = UT->getDecl(); 6200 FieldDecl *InitField = 0; 6201 // It's compatible if the expression matches any of the fields. 6202 for (RecordDecl::field_iterator it = UD->field_begin(), 6203 itend = UD->field_end(); 6204 it != itend; ++it) { 6205 if (it->getType()->isPointerType()) { 6206 // If the transparent union contains a pointer type, we allow: 6207 // 1) void pointer 6208 // 2) null pointer constant 6209 if (RHSType->isPointerType()) 6210 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 6211 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast); 6212 InitField = *it; 6213 break; 6214 } 6215 6216 if (RHS.get()->isNullPointerConstant(Context, 6217 Expr::NPC_ValueDependentIsNull)) { 6218 RHS = ImpCastExprToType(RHS.take(), it->getType(), 6219 CK_NullToPointer); 6220 InitField = *it; 6221 break; 6222 } 6223 } 6224 6225 CastKind Kind = CK_Invalid; 6226 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 6227 == Compatible) { 6228 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind); 6229 InitField = *it; 6230 break; 6231 } 6232 } 6233 6234 if (!InitField) 6235 return Incompatible; 6236 6237 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 6238 return Compatible; 6239 } 6240 6241 Sema::AssignConvertType 6242 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, 6243 bool Diagnose) { 6244 if (getLangOpts().CPlusPlus) { 6245 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 6246 // C++ 5.17p3: If the left operand is not of class type, the 6247 // expression is implicitly converted (C++ 4) to the 6248 // cv-unqualified type of the left operand. 6249 ExprResult Res; 6250 if (Diagnose) { 6251 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6252 AA_Assigning); 6253 } else { 6254 ImplicitConversionSequence ICS = 6255 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6256 /*SuppressUserConversions=*/false, 6257 /*AllowExplicit=*/false, 6258 /*InOverloadResolution=*/false, 6259 /*CStyle=*/false, 6260 /*AllowObjCWritebackConversion=*/false); 6261 if (ICS.isFailure()) 6262 return Incompatible; 6263 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6264 ICS, AA_Assigning); 6265 } 6266 if (Res.isInvalid()) 6267 return Incompatible; 6268 Sema::AssignConvertType result = Compatible; 6269 if (getLangOpts().ObjCAutoRefCount && 6270 !CheckObjCARCUnavailableWeakConversion(LHSType, 6271 RHS.get()->getType())) 6272 result = IncompatibleObjCWeakRef; 6273 RHS = Res; 6274 return result; 6275 } 6276 6277 // FIXME: Currently, we fall through and treat C++ classes like C 6278 // structures. 6279 // FIXME: We also fall through for atomics; not sure what should 6280 // happen there, though. 6281 } 6282 6283 // C99 6.5.16.1p1: the left operand is a pointer and the right is 6284 // a null pointer constant. 6285 if ((LHSType->isPointerType() || 6286 LHSType->isObjCObjectPointerType() || 6287 LHSType->isBlockPointerType()) 6288 && RHS.get()->isNullPointerConstant(Context, 6289 Expr::NPC_ValueDependentIsNull)) { 6290 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer); 6291 return Compatible; 6292 } 6293 6294 // This check seems unnatural, however it is necessary to ensure the proper 6295 // conversion of functions/arrays. If the conversion were done for all 6296 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 6297 // expressions that suppress this implicit conversion (&, sizeof). 6298 // 6299 // Suppress this for references: C++ 8.5.3p5. 6300 if (!LHSType->isReferenceType()) { 6301 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 6302 if (RHS.isInvalid()) 6303 return Incompatible; 6304 } 6305 6306 CastKind Kind = CK_Invalid; 6307 Sema::AssignConvertType result = 6308 CheckAssignmentConstraints(LHSType, RHS, Kind); 6309 6310 // C99 6.5.16.1p2: The value of the right operand is converted to the 6311 // type of the assignment expression. 6312 // CheckAssignmentConstraints allows the left-hand side to be a reference, 6313 // so that we can use references in built-in functions even in C. 6314 // The getNonReferenceType() call makes sure that the resulting expression 6315 // does not have reference type. 6316 if (result != Incompatible && RHS.get()->getType() != LHSType) 6317 RHS = ImpCastExprToType(RHS.take(), 6318 LHSType.getNonLValueExprType(Context), Kind); 6319 return result; 6320 } 6321 6322 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 6323 ExprResult &RHS) { 6324 Diag(Loc, diag::err_typecheck_invalid_operands) 6325 << LHS.get()->getType() << RHS.get()->getType() 6326 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6327 return QualType(); 6328 } 6329 6330 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 6331 SourceLocation Loc, bool IsCompAssign) { 6332 if (!IsCompAssign) { 6333 LHS = DefaultFunctionArrayLvalueConversion(LHS.take()); 6334 if (LHS.isInvalid()) 6335 return QualType(); 6336 } 6337 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 6338 if (RHS.isInvalid()) 6339 return QualType(); 6340 6341 // For conversion purposes, we ignore any qualifiers. 6342 // For example, "const float" and "float" are equivalent. 6343 QualType LHSType = 6344 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6345 QualType RHSType = 6346 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6347 6348 // If the vector types are identical, return. 6349 if (LHSType == RHSType) 6350 return LHSType; 6351 6352 // Handle the case of equivalent AltiVec and GCC vector types 6353 if (LHSType->isVectorType() && RHSType->isVectorType() && 6354 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 6355 if (LHSType->isExtVectorType()) { 6356 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6357 return LHSType; 6358 } 6359 6360 if (!IsCompAssign) 6361 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 6362 return RHSType; 6363 } 6364 6365 if (getLangOpts().LaxVectorConversions && 6366 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) { 6367 // If we are allowing lax vector conversions, and LHS and RHS are both 6368 // vectors, the total size only needs to be the same. This is a 6369 // bitcast; no bits are changed but the result type is different. 6370 // FIXME: Should we really be allowing this? 6371 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6372 return LHSType; 6373 } 6374 6375 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can 6376 // swap back (so that we don't reverse the inputs to a subtract, for instance. 6377 bool swapped = false; 6378 if (RHSType->isExtVectorType() && !IsCompAssign) { 6379 swapped = true; 6380 std::swap(RHS, LHS); 6381 std::swap(RHSType, LHSType); 6382 } 6383 6384 // Handle the case of an ext vector and scalar. 6385 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) { 6386 QualType EltTy = LV->getElementType(); 6387 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) { 6388 int order = Context.getIntegerTypeOrder(EltTy, RHSType); 6389 if (order > 0) 6390 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast); 6391 if (order >= 0) { 6392 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat); 6393 if (swapped) std::swap(RHS, LHS); 6394 return LHSType; 6395 } 6396 } 6397 if (EltTy->isRealFloatingType() && RHSType->isScalarType() && 6398 RHSType->isRealFloatingType()) { 6399 int order = Context.getFloatingTypeOrder(EltTy, RHSType); 6400 if (order > 0) 6401 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast); 6402 if (order >= 0) { 6403 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat); 6404 if (swapped) std::swap(RHS, LHS); 6405 return LHSType; 6406 } 6407 } 6408 } 6409 6410 // Vectors of different size or scalar and non-ext-vector are errors. 6411 if (swapped) std::swap(RHS, LHS); 6412 Diag(Loc, diag::err_typecheck_vector_not_convertable) 6413 << LHS.get()->getType() << RHS.get()->getType() 6414 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6415 return QualType(); 6416 } 6417 6418 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 6419 // expression. These are mainly cases where the null pointer is used as an 6420 // integer instead of a pointer. 6421 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 6422 SourceLocation Loc, bool IsCompare) { 6423 // The canonical way to check for a GNU null is with isNullPointerConstant, 6424 // but we use a bit of a hack here for speed; this is a relatively 6425 // hot path, and isNullPointerConstant is slow. 6426 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 6427 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 6428 6429 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 6430 6431 // Avoid analyzing cases where the result will either be invalid (and 6432 // diagnosed as such) or entirely valid and not something to warn about. 6433 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 6434 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 6435 return; 6436 6437 // Comparison operations would not make sense with a null pointer no matter 6438 // what the other expression is. 6439 if (!IsCompare) { 6440 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 6441 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 6442 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 6443 return; 6444 } 6445 6446 // The rest of the operations only make sense with a null pointer 6447 // if the other expression is a pointer. 6448 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 6449 NonNullType->canDecayToPointerType()) 6450 return; 6451 6452 S.Diag(Loc, diag::warn_null_in_comparison_operation) 6453 << LHSNull /* LHS is NULL */ << NonNullType 6454 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6455 } 6456 6457 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 6458 SourceLocation Loc, 6459 bool IsCompAssign, bool IsDiv) { 6460 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6461 6462 if (LHS.get()->getType()->isVectorType() || 6463 RHS.get()->getType()->isVectorType()) 6464 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6465 6466 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 6467 if (LHS.isInvalid() || RHS.isInvalid()) 6468 return QualType(); 6469 6470 6471 if (compType.isNull() || !compType->isArithmeticType()) 6472 return InvalidOperands(Loc, LHS, RHS); 6473 6474 // Check for division by zero. 6475 if (IsDiv && 6476 RHS.get()->isNullPointerConstant(Context, 6477 Expr::NPC_ValueDependentIsNotNull)) 6478 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero) 6479 << RHS.get()->getSourceRange()); 6480 6481 return compType; 6482 } 6483 6484 QualType Sema::CheckRemainderOperands( 6485 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 6486 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6487 6488 if (LHS.get()->getType()->isVectorType() || 6489 RHS.get()->getType()->isVectorType()) { 6490 if (LHS.get()->getType()->hasIntegerRepresentation() && 6491 RHS.get()->getType()->hasIntegerRepresentation()) 6492 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6493 return InvalidOperands(Loc, LHS, RHS); 6494 } 6495 6496 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 6497 if (LHS.isInvalid() || RHS.isInvalid()) 6498 return QualType(); 6499 6500 if (compType.isNull() || !compType->isIntegerType()) 6501 return InvalidOperands(Loc, LHS, RHS); 6502 6503 // Check for remainder by zero. 6504 if (RHS.get()->isNullPointerConstant(Context, 6505 Expr::NPC_ValueDependentIsNotNull)) 6506 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero) 6507 << RHS.get()->getSourceRange()); 6508 6509 return compType; 6510 } 6511 6512 /// \brief Diagnose invalid arithmetic on two void pointers. 6513 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 6514 Expr *LHSExpr, Expr *RHSExpr) { 6515 S.Diag(Loc, S.getLangOpts().CPlusPlus 6516 ? diag::err_typecheck_pointer_arith_void_type 6517 : diag::ext_gnu_void_ptr) 6518 << 1 /* two pointers */ << LHSExpr->getSourceRange() 6519 << RHSExpr->getSourceRange(); 6520 } 6521 6522 /// \brief Diagnose invalid arithmetic on a void pointer. 6523 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 6524 Expr *Pointer) { 6525 S.Diag(Loc, S.getLangOpts().CPlusPlus 6526 ? diag::err_typecheck_pointer_arith_void_type 6527 : diag::ext_gnu_void_ptr) 6528 << 0 /* one pointer */ << Pointer->getSourceRange(); 6529 } 6530 6531 /// \brief Diagnose invalid arithmetic on two function pointers. 6532 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 6533 Expr *LHS, Expr *RHS) { 6534 assert(LHS->getType()->isAnyPointerType()); 6535 assert(RHS->getType()->isAnyPointerType()); 6536 S.Diag(Loc, S.getLangOpts().CPlusPlus 6537 ? diag::err_typecheck_pointer_arith_function_type 6538 : diag::ext_gnu_ptr_func_arith) 6539 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 6540 // We only show the second type if it differs from the first. 6541 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 6542 RHS->getType()) 6543 << RHS->getType()->getPointeeType() 6544 << LHS->getSourceRange() << RHS->getSourceRange(); 6545 } 6546 6547 /// \brief Diagnose invalid arithmetic on a function pointer. 6548 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 6549 Expr *Pointer) { 6550 assert(Pointer->getType()->isAnyPointerType()); 6551 S.Diag(Loc, S.getLangOpts().CPlusPlus 6552 ? diag::err_typecheck_pointer_arith_function_type 6553 : diag::ext_gnu_ptr_func_arith) 6554 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 6555 << 0 /* one pointer, so only one type */ 6556 << Pointer->getSourceRange(); 6557 } 6558 6559 /// \brief Emit error if Operand is incomplete pointer type 6560 /// 6561 /// \returns True if pointer has incomplete type 6562 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 6563 Expr *Operand) { 6564 assert(Operand->getType()->isAnyPointerType() && 6565 !Operand->getType()->isDependentType()); 6566 QualType PointeeTy = Operand->getType()->getPointeeType(); 6567 return S.RequireCompleteType(Loc, PointeeTy, 6568 diag::err_typecheck_arithmetic_incomplete_type, 6569 PointeeTy, Operand->getSourceRange()); 6570 } 6571 6572 /// \brief Check the validity of an arithmetic pointer operand. 6573 /// 6574 /// If the operand has pointer type, this code will check for pointer types 6575 /// which are invalid in arithmetic operations. These will be diagnosed 6576 /// appropriately, including whether or not the use is supported as an 6577 /// extension. 6578 /// 6579 /// \returns True when the operand is valid to use (even if as an extension). 6580 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 6581 Expr *Operand) { 6582 if (!Operand->getType()->isAnyPointerType()) return true; 6583 6584 QualType PointeeTy = Operand->getType()->getPointeeType(); 6585 if (PointeeTy->isVoidType()) { 6586 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 6587 return !S.getLangOpts().CPlusPlus; 6588 } 6589 if (PointeeTy->isFunctionType()) { 6590 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 6591 return !S.getLangOpts().CPlusPlus; 6592 } 6593 6594 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 6595 6596 return true; 6597 } 6598 6599 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 6600 /// operands. 6601 /// 6602 /// This routine will diagnose any invalid arithmetic on pointer operands much 6603 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 6604 /// for emitting a single diagnostic even for operations where both LHS and RHS 6605 /// are (potentially problematic) pointers. 6606 /// 6607 /// \returns True when the operand is valid to use (even if as an extension). 6608 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 6609 Expr *LHSExpr, Expr *RHSExpr) { 6610 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 6611 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 6612 if (!isLHSPointer && !isRHSPointer) return true; 6613 6614 QualType LHSPointeeTy, RHSPointeeTy; 6615 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 6616 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 6617 6618 // Check for arithmetic on pointers to incomplete types. 6619 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 6620 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 6621 if (isLHSVoidPtr || isRHSVoidPtr) { 6622 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 6623 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 6624 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 6625 6626 return !S.getLangOpts().CPlusPlus; 6627 } 6628 6629 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 6630 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 6631 if (isLHSFuncPtr || isRHSFuncPtr) { 6632 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 6633 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 6634 RHSExpr); 6635 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 6636 6637 return !S.getLangOpts().CPlusPlus; 6638 } 6639 6640 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 6641 return false; 6642 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 6643 return false; 6644 6645 return true; 6646 } 6647 6648 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 6649 /// literal. 6650 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 6651 Expr *LHSExpr, Expr *RHSExpr) { 6652 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 6653 Expr* IndexExpr = RHSExpr; 6654 if (!StrExpr) { 6655 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 6656 IndexExpr = LHSExpr; 6657 } 6658 6659 bool IsStringPlusInt = StrExpr && 6660 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 6661 if (!IsStringPlusInt) 6662 return; 6663 6664 llvm::APSInt index; 6665 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 6666 unsigned StrLenWithNull = StrExpr->getLength() + 1; 6667 if (index.isNonNegative() && 6668 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 6669 index.isUnsigned())) 6670 return; 6671 } 6672 6673 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 6674 Self.Diag(OpLoc, diag::warn_string_plus_int) 6675 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 6676 6677 // Only print a fixit for "str" + int, not for int + "str". 6678 if (IndexExpr == RHSExpr) { 6679 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 6680 Self.Diag(OpLoc, diag::note_string_plus_int_silence) 6681 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 6682 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 6683 << FixItHint::CreateInsertion(EndLoc, "]"); 6684 } else 6685 Self.Diag(OpLoc, diag::note_string_plus_int_silence); 6686 } 6687 6688 /// \brief Emit error when two pointers are incompatible. 6689 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 6690 Expr *LHSExpr, Expr *RHSExpr) { 6691 assert(LHSExpr->getType()->isAnyPointerType()); 6692 assert(RHSExpr->getType()->isAnyPointerType()); 6693 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 6694 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 6695 << RHSExpr->getSourceRange(); 6696 } 6697 6698 QualType Sema::CheckAdditionOperands( // C99 6.5.6 6699 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 6700 QualType* CompLHSTy) { 6701 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6702 6703 if (LHS.get()->getType()->isVectorType() || 6704 RHS.get()->getType()->isVectorType()) { 6705 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 6706 if (CompLHSTy) *CompLHSTy = compType; 6707 return compType; 6708 } 6709 6710 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 6711 if (LHS.isInvalid() || RHS.isInvalid()) 6712 return QualType(); 6713 6714 // Diagnose "string literal" '+' int. 6715 if (Opc == BO_Add) 6716 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 6717 6718 // handle the common case first (both operands are arithmetic). 6719 if (!compType.isNull() && compType->isArithmeticType()) { 6720 if (CompLHSTy) *CompLHSTy = compType; 6721 return compType; 6722 } 6723 6724 // Type-checking. Ultimately the pointer's going to be in PExp; 6725 // note that we bias towards the LHS being the pointer. 6726 Expr *PExp = LHS.get(), *IExp = RHS.get(); 6727 6728 bool isObjCPointer; 6729 if (PExp->getType()->isPointerType()) { 6730 isObjCPointer = false; 6731 } else if (PExp->getType()->isObjCObjectPointerType()) { 6732 isObjCPointer = true; 6733 } else { 6734 std::swap(PExp, IExp); 6735 if (PExp->getType()->isPointerType()) { 6736 isObjCPointer = false; 6737 } else if (PExp->getType()->isObjCObjectPointerType()) { 6738 isObjCPointer = true; 6739 } else { 6740 return InvalidOperands(Loc, LHS, RHS); 6741 } 6742 } 6743 assert(PExp->getType()->isAnyPointerType()); 6744 6745 if (!IExp->getType()->isIntegerType()) 6746 return InvalidOperands(Loc, LHS, RHS); 6747 6748 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 6749 return QualType(); 6750 6751 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 6752 return QualType(); 6753 6754 // Check array bounds for pointer arithemtic 6755 CheckArrayAccess(PExp, IExp); 6756 6757 if (CompLHSTy) { 6758 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 6759 if (LHSTy.isNull()) { 6760 LHSTy = LHS.get()->getType(); 6761 if (LHSTy->isPromotableIntegerType()) 6762 LHSTy = Context.getPromotedIntegerType(LHSTy); 6763 } 6764 *CompLHSTy = LHSTy; 6765 } 6766 6767 return PExp->getType(); 6768 } 6769 6770 // C99 6.5.6 6771 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 6772 SourceLocation Loc, 6773 QualType* CompLHSTy) { 6774 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6775 6776 if (LHS.get()->getType()->isVectorType() || 6777 RHS.get()->getType()->isVectorType()) { 6778 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 6779 if (CompLHSTy) *CompLHSTy = compType; 6780 return compType; 6781 } 6782 6783 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 6784 if (LHS.isInvalid() || RHS.isInvalid()) 6785 return QualType(); 6786 6787 // Enforce type constraints: C99 6.5.6p3. 6788 6789 // Handle the common case first (both operands are arithmetic). 6790 if (!compType.isNull() && compType->isArithmeticType()) { 6791 if (CompLHSTy) *CompLHSTy = compType; 6792 return compType; 6793 } 6794 6795 // Either ptr - int or ptr - ptr. 6796 if (LHS.get()->getType()->isAnyPointerType()) { 6797 QualType lpointee = LHS.get()->getType()->getPointeeType(); 6798 6799 // Diagnose bad cases where we step over interface counts. 6800 if (LHS.get()->getType()->isObjCObjectPointerType() && 6801 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 6802 return QualType(); 6803 6804 // The result type of a pointer-int computation is the pointer type. 6805 if (RHS.get()->getType()->isIntegerType()) { 6806 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 6807 return QualType(); 6808 6809 // Check array bounds for pointer arithemtic 6810 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0, 6811 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 6812 6813 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 6814 return LHS.get()->getType(); 6815 } 6816 6817 // Handle pointer-pointer subtractions. 6818 if (const PointerType *RHSPTy 6819 = RHS.get()->getType()->getAs<PointerType>()) { 6820 QualType rpointee = RHSPTy->getPointeeType(); 6821 6822 if (getLangOpts().CPlusPlus) { 6823 // Pointee types must be the same: C++ [expr.add] 6824 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 6825 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 6826 } 6827 } else { 6828 // Pointee types must be compatible C99 6.5.6p3 6829 if (!Context.typesAreCompatible( 6830 Context.getCanonicalType(lpointee).getUnqualifiedType(), 6831 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 6832 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 6833 return QualType(); 6834 } 6835 } 6836 6837 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 6838 LHS.get(), RHS.get())) 6839 return QualType(); 6840 6841 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 6842 return Context.getPointerDiffType(); 6843 } 6844 } 6845 6846 return InvalidOperands(Loc, LHS, RHS); 6847 } 6848 6849 static bool isScopedEnumerationType(QualType T) { 6850 if (const EnumType *ET = dyn_cast<EnumType>(T)) 6851 return ET->getDecl()->isScoped(); 6852 return false; 6853 } 6854 6855 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 6856 SourceLocation Loc, unsigned Opc, 6857 QualType LHSType) { 6858 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 6859 // so skip remaining warnings as we don't want to modify values within Sema. 6860 if (S.getLangOpts().OpenCL) 6861 return; 6862 6863 llvm::APSInt Right; 6864 // Check right/shifter operand 6865 if (RHS.get()->isValueDependent() || 6866 !RHS.get()->isIntegerConstantExpr(Right, S.Context)) 6867 return; 6868 6869 if (Right.isNegative()) { 6870 S.DiagRuntimeBehavior(Loc, RHS.get(), 6871 S.PDiag(diag::warn_shift_negative) 6872 << RHS.get()->getSourceRange()); 6873 return; 6874 } 6875 llvm::APInt LeftBits(Right.getBitWidth(), 6876 S.Context.getTypeSize(LHS.get()->getType())); 6877 if (Right.uge(LeftBits)) { 6878 S.DiagRuntimeBehavior(Loc, RHS.get(), 6879 S.PDiag(diag::warn_shift_gt_typewidth) 6880 << RHS.get()->getSourceRange()); 6881 return; 6882 } 6883 if (Opc != BO_Shl) 6884 return; 6885 6886 // When left shifting an ICE which is signed, we can check for overflow which 6887 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 6888 // integers have defined behavior modulo one more than the maximum value 6889 // representable in the result type, so never warn for those. 6890 llvm::APSInt Left; 6891 if (LHS.get()->isValueDependent() || 6892 !LHS.get()->isIntegerConstantExpr(Left, S.Context) || 6893 LHSType->hasUnsignedIntegerRepresentation()) 6894 return; 6895 llvm::APInt ResultBits = 6896 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 6897 if (LeftBits.uge(ResultBits)) 6898 return; 6899 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 6900 Result = Result.shl(Right); 6901 6902 // Print the bit representation of the signed integer as an unsigned 6903 // hexadecimal number. 6904 SmallString<40> HexResult; 6905 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 6906 6907 // If we are only missing a sign bit, this is less likely to result in actual 6908 // bugs -- if the result is cast back to an unsigned type, it will have the 6909 // expected value. Thus we place this behind a different warning that can be 6910 // turned off separately if needed. 6911 if (LeftBits == ResultBits - 1) { 6912 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 6913 << HexResult.str() << LHSType 6914 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6915 return; 6916 } 6917 6918 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 6919 << HexResult.str() << Result.getMinSignedBits() << LHSType 6920 << Left.getBitWidth() << LHS.get()->getSourceRange() 6921 << RHS.get()->getSourceRange(); 6922 } 6923 6924 // C99 6.5.7 6925 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 6926 SourceLocation Loc, unsigned Opc, 6927 bool IsCompAssign) { 6928 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6929 6930 // Vector shifts promote their scalar inputs to vector type. 6931 if (LHS.get()->getType()->isVectorType() || 6932 RHS.get()->getType()->isVectorType()) 6933 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6934 6935 // Shifts don't perform usual arithmetic conversions, they just do integer 6936 // promotions on each operand. C99 6.5.7p3 6937 6938 // For the LHS, do usual unary conversions, but then reset them away 6939 // if this is a compound assignment. 6940 ExprResult OldLHS = LHS; 6941 LHS = UsualUnaryConversions(LHS.take()); 6942 if (LHS.isInvalid()) 6943 return QualType(); 6944 QualType LHSType = LHS.get()->getType(); 6945 if (IsCompAssign) LHS = OldLHS; 6946 6947 // The RHS is simpler. 6948 RHS = UsualUnaryConversions(RHS.take()); 6949 if (RHS.isInvalid()) 6950 return QualType(); 6951 QualType RHSType = RHS.get()->getType(); 6952 6953 // C99 6.5.7p2: Each of the operands shall have integer type. 6954 if (!LHSType->hasIntegerRepresentation() || 6955 !RHSType->hasIntegerRepresentation()) 6956 return InvalidOperands(Loc, LHS, RHS); 6957 6958 // C++0x: Don't allow scoped enums. FIXME: Use something better than 6959 // hasIntegerRepresentation() above instead of this. 6960 if (isScopedEnumerationType(LHSType) || 6961 isScopedEnumerationType(RHSType)) { 6962 return InvalidOperands(Loc, LHS, RHS); 6963 } 6964 // Sanity-check shift operands 6965 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 6966 6967 // "The type of the result is that of the promoted left operand." 6968 return LHSType; 6969 } 6970 6971 static bool IsWithinTemplateSpecialization(Decl *D) { 6972 if (DeclContext *DC = D->getDeclContext()) { 6973 if (isa<ClassTemplateSpecializationDecl>(DC)) 6974 return true; 6975 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 6976 return FD->isFunctionTemplateSpecialization(); 6977 } 6978 return false; 6979 } 6980 6981 /// If two different enums are compared, raise a warning. 6982 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 6983 Expr *RHS) { 6984 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 6985 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 6986 6987 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 6988 if (!LHSEnumType) 6989 return; 6990 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 6991 if (!RHSEnumType) 6992 return; 6993 6994 // Ignore anonymous enums. 6995 if (!LHSEnumType->getDecl()->getIdentifier()) 6996 return; 6997 if (!RHSEnumType->getDecl()->getIdentifier()) 6998 return; 6999 7000 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 7001 return; 7002 7003 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 7004 << LHSStrippedType << RHSStrippedType 7005 << LHS->getSourceRange() << RHS->getSourceRange(); 7006 } 7007 7008 /// \brief Diagnose bad pointer comparisons. 7009 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 7010 ExprResult &LHS, ExprResult &RHS, 7011 bool IsError) { 7012 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 7013 : diag::ext_typecheck_comparison_of_distinct_pointers) 7014 << LHS.get()->getType() << RHS.get()->getType() 7015 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7016 } 7017 7018 /// \brief Returns false if the pointers are converted to a composite type, 7019 /// true otherwise. 7020 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 7021 ExprResult &LHS, ExprResult &RHS) { 7022 // C++ [expr.rel]p2: 7023 // [...] Pointer conversions (4.10) and qualification 7024 // conversions (4.4) are performed on pointer operands (or on 7025 // a pointer operand and a null pointer constant) to bring 7026 // them to their composite pointer type. [...] 7027 // 7028 // C++ [expr.eq]p1 uses the same notion for (in)equality 7029 // comparisons of pointers. 7030 7031 // C++ [expr.eq]p2: 7032 // In addition, pointers to members can be compared, or a pointer to 7033 // member and a null pointer constant. Pointer to member conversions 7034 // (4.11) and qualification conversions (4.4) are performed to bring 7035 // them to a common type. If one operand is a null pointer constant, 7036 // the common type is the type of the other operand. Otherwise, the 7037 // common type is a pointer to member type similar (4.4) to the type 7038 // of one of the operands, with a cv-qualification signature (4.4) 7039 // that is the union of the cv-qualification signatures of the operand 7040 // types. 7041 7042 QualType LHSType = LHS.get()->getType(); 7043 QualType RHSType = RHS.get()->getType(); 7044 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 7045 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 7046 7047 bool NonStandardCompositeType = false; 7048 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType; 7049 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 7050 if (T.isNull()) { 7051 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 7052 return true; 7053 } 7054 7055 if (NonStandardCompositeType) 7056 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 7057 << LHSType << RHSType << T << LHS.get()->getSourceRange() 7058 << RHS.get()->getSourceRange(); 7059 7060 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast); 7061 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast); 7062 return false; 7063 } 7064 7065 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 7066 ExprResult &LHS, 7067 ExprResult &RHS, 7068 bool IsError) { 7069 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 7070 : diag::ext_typecheck_comparison_of_fptr_to_void) 7071 << LHS.get()->getType() << RHS.get()->getType() 7072 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7073 } 7074 7075 static bool isObjCObjectLiteral(ExprResult &E) { 7076 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 7077 case Stmt::ObjCArrayLiteralClass: 7078 case Stmt::ObjCDictionaryLiteralClass: 7079 case Stmt::ObjCStringLiteralClass: 7080 case Stmt::ObjCBoxedExprClass: 7081 return true; 7082 default: 7083 // Note that ObjCBoolLiteral is NOT an object literal! 7084 return false; 7085 } 7086 } 7087 7088 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 7089 const ObjCObjectPointerType *Type = 7090 LHS->getType()->getAs<ObjCObjectPointerType>(); 7091 7092 // If this is not actually an Objective-C object, bail out. 7093 if (!Type) 7094 return false; 7095 7096 // Get the LHS object's interface type. 7097 QualType InterfaceType = Type->getPointeeType(); 7098 if (const ObjCObjectType *iQFaceTy = 7099 InterfaceType->getAsObjCQualifiedInterfaceType()) 7100 InterfaceType = iQFaceTy->getBaseType(); 7101 7102 // If the RHS isn't an Objective-C object, bail out. 7103 if (!RHS->getType()->isObjCObjectPointerType()) 7104 return false; 7105 7106 // Try to find the -isEqual: method. 7107 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 7108 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 7109 InterfaceType, 7110 /*instance=*/true); 7111 if (!Method) { 7112 if (Type->isObjCIdType()) { 7113 // For 'id', just check the global pool. 7114 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 7115 /*receiverId=*/true, 7116 /*warn=*/false); 7117 } else { 7118 // Check protocols. 7119 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 7120 /*instance=*/true); 7121 } 7122 } 7123 7124 if (!Method) 7125 return false; 7126 7127 QualType T = Method->param_begin()[0]->getType(); 7128 if (!T->isObjCObjectPointerType()) 7129 return false; 7130 7131 QualType R = Method->getResultType(); 7132 if (!R->isScalarType()) 7133 return false; 7134 7135 return true; 7136 } 7137 7138 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 7139 FromE = FromE->IgnoreParenImpCasts(); 7140 switch (FromE->getStmtClass()) { 7141 default: 7142 break; 7143 case Stmt::ObjCStringLiteralClass: 7144 // "string literal" 7145 return LK_String; 7146 case Stmt::ObjCArrayLiteralClass: 7147 // "array literal" 7148 return LK_Array; 7149 case Stmt::ObjCDictionaryLiteralClass: 7150 // "dictionary literal" 7151 return LK_Dictionary; 7152 case Stmt::BlockExprClass: 7153 return LK_Block; 7154 case Stmt::ObjCBoxedExprClass: { 7155 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 7156 switch (Inner->getStmtClass()) { 7157 case Stmt::IntegerLiteralClass: 7158 case Stmt::FloatingLiteralClass: 7159 case Stmt::CharacterLiteralClass: 7160 case Stmt::ObjCBoolLiteralExprClass: 7161 case Stmt::CXXBoolLiteralExprClass: 7162 // "numeric literal" 7163 return LK_Numeric; 7164 case Stmt::ImplicitCastExprClass: { 7165 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 7166 // Boolean literals can be represented by implicit casts. 7167 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 7168 return LK_Numeric; 7169 break; 7170 } 7171 default: 7172 break; 7173 } 7174 return LK_Boxed; 7175 } 7176 } 7177 return LK_None; 7178 } 7179 7180 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 7181 ExprResult &LHS, ExprResult &RHS, 7182 BinaryOperator::Opcode Opc){ 7183 Expr *Literal; 7184 Expr *Other; 7185 if (isObjCObjectLiteral(LHS)) { 7186 Literal = LHS.get(); 7187 Other = RHS.get(); 7188 } else { 7189 Literal = RHS.get(); 7190 Other = LHS.get(); 7191 } 7192 7193 // Don't warn on comparisons against nil. 7194 Other = Other->IgnoreParenCasts(); 7195 if (Other->isNullPointerConstant(S.getASTContext(), 7196 Expr::NPC_ValueDependentIsNotNull)) 7197 return; 7198 7199 // This should be kept in sync with warn_objc_literal_comparison. 7200 // LK_String should always be after the other literals, since it has its own 7201 // warning flag. 7202 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 7203 assert(LiteralKind != Sema::LK_Block); 7204 if (LiteralKind == Sema::LK_None) { 7205 llvm_unreachable("Unknown Objective-C object literal kind"); 7206 } 7207 7208 if (LiteralKind == Sema::LK_String) 7209 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 7210 << Literal->getSourceRange(); 7211 else 7212 S.Diag(Loc, diag::warn_objc_literal_comparison) 7213 << LiteralKind << Literal->getSourceRange(); 7214 7215 if (BinaryOperator::isEqualityOp(Opc) && 7216 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 7217 SourceLocation Start = LHS.get()->getLocStart(); 7218 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 7219 CharSourceRange OpRange = 7220 CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc)); 7221 7222 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 7223 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 7224 << FixItHint::CreateReplacement(OpRange, " isEqual:") 7225 << FixItHint::CreateInsertion(End, "]"); 7226 } 7227 } 7228 7229 // C99 6.5.8, C++ [expr.rel] 7230 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 7231 SourceLocation Loc, unsigned OpaqueOpc, 7232 bool IsRelational) { 7233 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 7234 7235 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc; 7236 7237 // Handle vector comparisons separately. 7238 if (LHS.get()->getType()->isVectorType() || 7239 RHS.get()->getType()->isVectorType()) 7240 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 7241 7242 QualType LHSType = LHS.get()->getType(); 7243 QualType RHSType = RHS.get()->getType(); 7244 7245 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 7246 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 7247 7248 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 7249 7250 if (!LHSType->hasFloatingRepresentation() && 7251 !(LHSType->isBlockPointerType() && IsRelational) && 7252 !LHS.get()->getLocStart().isMacroID() && 7253 !RHS.get()->getLocStart().isMacroID()) { 7254 // For non-floating point types, check for self-comparisons of the form 7255 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 7256 // often indicate logic errors in the program. 7257 // 7258 // NOTE: Don't warn about comparison expressions resulting from macro 7259 // expansion. Also don't warn about comparisons which are only self 7260 // comparisons within a template specialization. The warnings should catch 7261 // obvious cases in the definition of the template anyways. The idea is to 7262 // warn when the typed comparison operator will always evaluate to the same 7263 // result. 7264 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) { 7265 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) { 7266 if (DRL->getDecl() == DRR->getDecl() && 7267 !IsWithinTemplateSpecialization(DRL->getDecl())) { 7268 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 7269 << 0 // self- 7270 << (Opc == BO_EQ 7271 || Opc == BO_LE 7272 || Opc == BO_GE)); 7273 } else if (LHSType->isArrayType() && RHSType->isArrayType() && 7274 !DRL->getDecl()->getType()->isReferenceType() && 7275 !DRR->getDecl()->getType()->isReferenceType()) { 7276 // what is it always going to eval to? 7277 char always_evals_to; 7278 switch(Opc) { 7279 case BO_EQ: // e.g. array1 == array2 7280 always_evals_to = 0; // false 7281 break; 7282 case BO_NE: // e.g. array1 != array2 7283 always_evals_to = 1; // true 7284 break; 7285 default: 7286 // best we can say is 'a constant' 7287 always_evals_to = 2; // e.g. array1 <= array2 7288 break; 7289 } 7290 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 7291 << 1 // array 7292 << always_evals_to); 7293 } 7294 } 7295 } 7296 7297 if (isa<CastExpr>(LHSStripped)) 7298 LHSStripped = LHSStripped->IgnoreParenCasts(); 7299 if (isa<CastExpr>(RHSStripped)) 7300 RHSStripped = RHSStripped->IgnoreParenCasts(); 7301 7302 // Warn about comparisons against a string constant (unless the other 7303 // operand is null), the user probably wants strcmp. 7304 Expr *literalString = 0; 7305 Expr *literalStringStripped = 0; 7306 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 7307 !RHSStripped->isNullPointerConstant(Context, 7308 Expr::NPC_ValueDependentIsNull)) { 7309 literalString = LHS.get(); 7310 literalStringStripped = LHSStripped; 7311 } else if ((isa<StringLiteral>(RHSStripped) || 7312 isa<ObjCEncodeExpr>(RHSStripped)) && 7313 !LHSStripped->isNullPointerConstant(Context, 7314 Expr::NPC_ValueDependentIsNull)) { 7315 literalString = RHS.get(); 7316 literalStringStripped = RHSStripped; 7317 } 7318 7319 if (literalString) { 7320 DiagRuntimeBehavior(Loc, 0, 7321 PDiag(diag::warn_stringcompare) 7322 << isa<ObjCEncodeExpr>(literalStringStripped) 7323 << literalString->getSourceRange()); 7324 } 7325 } 7326 7327 // C99 6.5.8p3 / C99 6.5.9p4 7328 if (LHS.get()->getType()->isArithmeticType() && 7329 RHS.get()->getType()->isArithmeticType()) { 7330 UsualArithmeticConversions(LHS, RHS); 7331 if (LHS.isInvalid() || RHS.isInvalid()) 7332 return QualType(); 7333 } 7334 else { 7335 LHS = UsualUnaryConversions(LHS.take()); 7336 if (LHS.isInvalid()) 7337 return QualType(); 7338 7339 RHS = UsualUnaryConversions(RHS.take()); 7340 if (RHS.isInvalid()) 7341 return QualType(); 7342 } 7343 7344 LHSType = LHS.get()->getType(); 7345 RHSType = RHS.get()->getType(); 7346 7347 // The result of comparisons is 'bool' in C++, 'int' in C. 7348 QualType ResultTy = Context.getLogicalOperationType(); 7349 7350 if (IsRelational) { 7351 if (LHSType->isRealType() && RHSType->isRealType()) 7352 return ResultTy; 7353 } else { 7354 // Check for comparisons of floating point operands using != and ==. 7355 if (LHSType->hasFloatingRepresentation()) 7356 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 7357 7358 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 7359 return ResultTy; 7360 } 7361 7362 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context, 7363 Expr::NPC_ValueDependentIsNull); 7364 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context, 7365 Expr::NPC_ValueDependentIsNull); 7366 7367 // All of the following pointer-related warnings are GCC extensions, except 7368 // when handling null pointer constants. 7369 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 7370 QualType LCanPointeeTy = 7371 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 7372 QualType RCanPointeeTy = 7373 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 7374 7375 if (getLangOpts().CPlusPlus) { 7376 if (LCanPointeeTy == RCanPointeeTy) 7377 return ResultTy; 7378 if (!IsRelational && 7379 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 7380 // Valid unless comparison between non-null pointer and function pointer 7381 // This is a gcc extension compatibility comparison. 7382 // In a SFINAE context, we treat this as a hard error to maintain 7383 // conformance with the C++ standard. 7384 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 7385 && !LHSIsNull && !RHSIsNull) { 7386 diagnoseFunctionPointerToVoidComparison( 7387 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 7388 7389 if (isSFINAEContext()) 7390 return QualType(); 7391 7392 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7393 return ResultTy; 7394 } 7395 } 7396 7397 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 7398 return QualType(); 7399 else 7400 return ResultTy; 7401 } 7402 // C99 6.5.9p2 and C99 6.5.8p2 7403 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 7404 RCanPointeeTy.getUnqualifiedType())) { 7405 // Valid unless a relational comparison of function pointers 7406 if (IsRelational && LCanPointeeTy->isFunctionType()) { 7407 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 7408 << LHSType << RHSType << LHS.get()->getSourceRange() 7409 << RHS.get()->getSourceRange(); 7410 } 7411 } else if (!IsRelational && 7412 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 7413 // Valid unless comparison between non-null pointer and function pointer 7414 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 7415 && !LHSIsNull && !RHSIsNull) 7416 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 7417 /*isError*/false); 7418 } else { 7419 // Invalid 7420 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 7421 } 7422 if (LCanPointeeTy != RCanPointeeTy) { 7423 if (LHSIsNull && !RHSIsNull) 7424 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 7425 else 7426 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7427 } 7428 return ResultTy; 7429 } 7430 7431 if (getLangOpts().CPlusPlus) { 7432 // Comparison of nullptr_t with itself. 7433 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 7434 return ResultTy; 7435 7436 // Comparison of pointers with null pointer constants and equality 7437 // comparisons of member pointers to null pointer constants. 7438 if (RHSIsNull && 7439 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 7440 (!IsRelational && 7441 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 7442 RHS = ImpCastExprToType(RHS.take(), LHSType, 7443 LHSType->isMemberPointerType() 7444 ? CK_NullToMemberPointer 7445 : CK_NullToPointer); 7446 return ResultTy; 7447 } 7448 if (LHSIsNull && 7449 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 7450 (!IsRelational && 7451 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 7452 LHS = ImpCastExprToType(LHS.take(), RHSType, 7453 RHSType->isMemberPointerType() 7454 ? CK_NullToMemberPointer 7455 : CK_NullToPointer); 7456 return ResultTy; 7457 } 7458 7459 // Comparison of member pointers. 7460 if (!IsRelational && 7461 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 7462 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 7463 return QualType(); 7464 else 7465 return ResultTy; 7466 } 7467 7468 // Handle scoped enumeration types specifically, since they don't promote 7469 // to integers. 7470 if (LHS.get()->getType()->isEnumeralType() && 7471 Context.hasSameUnqualifiedType(LHS.get()->getType(), 7472 RHS.get()->getType())) 7473 return ResultTy; 7474 } 7475 7476 // Handle block pointer types. 7477 if (!IsRelational && LHSType->isBlockPointerType() && 7478 RHSType->isBlockPointerType()) { 7479 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 7480 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 7481 7482 if (!LHSIsNull && !RHSIsNull && 7483 !Context.typesAreCompatible(lpointee, rpointee)) { 7484 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 7485 << LHSType << RHSType << LHS.get()->getSourceRange() 7486 << RHS.get()->getSourceRange(); 7487 } 7488 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7489 return ResultTy; 7490 } 7491 7492 // Allow block pointers to be compared with null pointer constants. 7493 if (!IsRelational 7494 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 7495 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 7496 if (!LHSIsNull && !RHSIsNull) { 7497 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 7498 ->getPointeeType()->isVoidType()) 7499 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 7500 ->getPointeeType()->isVoidType()))) 7501 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 7502 << LHSType << RHSType << LHS.get()->getSourceRange() 7503 << RHS.get()->getSourceRange(); 7504 } 7505 if (LHSIsNull && !RHSIsNull) 7506 LHS = ImpCastExprToType(LHS.take(), RHSType, 7507 RHSType->isPointerType() ? CK_BitCast 7508 : CK_AnyPointerToBlockPointerCast); 7509 else 7510 RHS = ImpCastExprToType(RHS.take(), LHSType, 7511 LHSType->isPointerType() ? CK_BitCast 7512 : CK_AnyPointerToBlockPointerCast); 7513 return ResultTy; 7514 } 7515 7516 if (LHSType->isObjCObjectPointerType() || 7517 RHSType->isObjCObjectPointerType()) { 7518 const PointerType *LPT = LHSType->getAs<PointerType>(); 7519 const PointerType *RPT = RHSType->getAs<PointerType>(); 7520 if (LPT || RPT) { 7521 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 7522 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 7523 7524 if (!LPtrToVoid && !RPtrToVoid && 7525 !Context.typesAreCompatible(LHSType, RHSType)) { 7526 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 7527 /*isError*/false); 7528 } 7529 if (LHSIsNull && !RHSIsNull) 7530 LHS = ImpCastExprToType(LHS.take(), RHSType, 7531 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 7532 else 7533 RHS = ImpCastExprToType(RHS.take(), LHSType, 7534 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 7535 return ResultTy; 7536 } 7537 if (LHSType->isObjCObjectPointerType() && 7538 RHSType->isObjCObjectPointerType()) { 7539 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 7540 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 7541 /*isError*/false); 7542 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 7543 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 7544 7545 if (LHSIsNull && !RHSIsNull) 7546 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 7547 else 7548 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7549 return ResultTy; 7550 } 7551 } 7552 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 7553 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 7554 unsigned DiagID = 0; 7555 bool isError = false; 7556 if (LangOpts.DebuggerSupport) { 7557 // Under a debugger, allow the comparison of pointers to integers, 7558 // since users tend to want to compare addresses. 7559 } else if ((LHSIsNull && LHSType->isIntegerType()) || 7560 (RHSIsNull && RHSType->isIntegerType())) { 7561 if (IsRelational && !getLangOpts().CPlusPlus) 7562 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 7563 } else if (IsRelational && !getLangOpts().CPlusPlus) 7564 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 7565 else if (getLangOpts().CPlusPlus) { 7566 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 7567 isError = true; 7568 } else 7569 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 7570 7571 if (DiagID) { 7572 Diag(Loc, DiagID) 7573 << LHSType << RHSType << LHS.get()->getSourceRange() 7574 << RHS.get()->getSourceRange(); 7575 if (isError) 7576 return QualType(); 7577 } 7578 7579 if (LHSType->isIntegerType()) 7580 LHS = ImpCastExprToType(LHS.take(), RHSType, 7581 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 7582 else 7583 RHS = ImpCastExprToType(RHS.take(), LHSType, 7584 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 7585 return ResultTy; 7586 } 7587 7588 // Handle block pointers. 7589 if (!IsRelational && RHSIsNull 7590 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 7591 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer); 7592 return ResultTy; 7593 } 7594 if (!IsRelational && LHSIsNull 7595 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 7596 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer); 7597 return ResultTy; 7598 } 7599 7600 return InvalidOperands(Loc, LHS, RHS); 7601 } 7602 7603 7604 // Return a signed type that is of identical size and number of elements. 7605 // For floating point vectors, return an integer type of identical size 7606 // and number of elements. 7607 QualType Sema::GetSignedVectorType(QualType V) { 7608 const VectorType *VTy = V->getAs<VectorType>(); 7609 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 7610 if (TypeSize == Context.getTypeSize(Context.CharTy)) 7611 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 7612 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 7613 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 7614 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 7615 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 7616 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 7617 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 7618 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 7619 "Unhandled vector element size in vector compare"); 7620 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 7621 } 7622 7623 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 7624 /// operates on extended vector types. Instead of producing an IntTy result, 7625 /// like a scalar comparison, a vector comparison produces a vector of integer 7626 /// types. 7627 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 7628 SourceLocation Loc, 7629 bool IsRelational) { 7630 // Check to make sure we're operating on vectors of the same type and width, 7631 // Allowing one side to be a scalar of element type. 7632 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false); 7633 if (vType.isNull()) 7634 return vType; 7635 7636 QualType LHSType = LHS.get()->getType(); 7637 7638 // If AltiVec, the comparison results in a numeric type, i.e. 7639 // bool for C++, int for C 7640 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 7641 return Context.getLogicalOperationType(); 7642 7643 // For non-floating point types, check for self-comparisons of the form 7644 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 7645 // often indicate logic errors in the program. 7646 if (!LHSType->hasFloatingRepresentation()) { 7647 if (DeclRefExpr* DRL 7648 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 7649 if (DeclRefExpr* DRR 7650 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 7651 if (DRL->getDecl() == DRR->getDecl()) 7652 DiagRuntimeBehavior(Loc, 0, 7653 PDiag(diag::warn_comparison_always) 7654 << 0 // self- 7655 << 2 // "a constant" 7656 ); 7657 } 7658 7659 // Check for comparisons of floating point operands using != and ==. 7660 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 7661 assert (RHS.get()->getType()->hasFloatingRepresentation()); 7662 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 7663 } 7664 7665 // Return a signed type for the vector. 7666 return GetSignedVectorType(LHSType); 7667 } 7668 7669 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 7670 SourceLocation Loc) { 7671 // Ensure that either both operands are of the same vector type, or 7672 // one operand is of a vector type and the other is of its element type. 7673 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false); 7674 if (vType.isNull()) 7675 return InvalidOperands(Loc, LHS, RHS); 7676 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 7677 vType->hasFloatingRepresentation()) 7678 return InvalidOperands(Loc, LHS, RHS); 7679 7680 return GetSignedVectorType(LHS.get()->getType()); 7681 } 7682 7683 inline QualType Sema::CheckBitwiseOperands( 7684 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 7685 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7686 7687 if (LHS.get()->getType()->isVectorType() || 7688 RHS.get()->getType()->isVectorType()) { 7689 if (LHS.get()->getType()->hasIntegerRepresentation() && 7690 RHS.get()->getType()->hasIntegerRepresentation()) 7691 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 7692 7693 return InvalidOperands(Loc, LHS, RHS); 7694 } 7695 7696 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS); 7697 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 7698 IsCompAssign); 7699 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 7700 return QualType(); 7701 LHS = LHSResult.take(); 7702 RHS = RHSResult.take(); 7703 7704 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 7705 return compType; 7706 return InvalidOperands(Loc, LHS, RHS); 7707 } 7708 7709 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 7710 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) { 7711 7712 // Check vector operands differently. 7713 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 7714 return CheckVectorLogicalOperands(LHS, RHS, Loc); 7715 7716 // Diagnose cases where the user write a logical and/or but probably meant a 7717 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 7718 // is a constant. 7719 if (LHS.get()->getType()->isIntegerType() && 7720 !LHS.get()->getType()->isBooleanType() && 7721 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 7722 // Don't warn in macros or template instantiations. 7723 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 7724 // If the RHS can be constant folded, and if it constant folds to something 7725 // that isn't 0 or 1 (which indicate a potential logical operation that 7726 // happened to fold to true/false) then warn. 7727 // Parens on the RHS are ignored. 7728 llvm::APSInt Result; 7729 if (RHS.get()->EvaluateAsInt(Result, Context)) 7730 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) || 7731 (Result != 0 && Result != 1)) { 7732 Diag(Loc, diag::warn_logical_instead_of_bitwise) 7733 << RHS.get()->getSourceRange() 7734 << (Opc == BO_LAnd ? "&&" : "||"); 7735 // Suggest replacing the logical operator with the bitwise version 7736 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 7737 << (Opc == BO_LAnd ? "&" : "|") 7738 << FixItHint::CreateReplacement(SourceRange( 7739 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(), 7740 getLangOpts())), 7741 Opc == BO_LAnd ? "&" : "|"); 7742 if (Opc == BO_LAnd) 7743 // Suggest replacing "Foo() && kNonZero" with "Foo()" 7744 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 7745 << FixItHint::CreateRemoval( 7746 SourceRange( 7747 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(), 7748 0, getSourceManager(), 7749 getLangOpts()), 7750 RHS.get()->getLocEnd())); 7751 } 7752 } 7753 7754 if (!Context.getLangOpts().CPlusPlus) { 7755 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 7756 // not operate on the built-in scalar and vector float types. 7757 if (Context.getLangOpts().OpenCL && 7758 Context.getLangOpts().OpenCLVersion < 120) { 7759 if (LHS.get()->getType()->isFloatingType() || 7760 RHS.get()->getType()->isFloatingType()) 7761 return InvalidOperands(Loc, LHS, RHS); 7762 } 7763 7764 LHS = UsualUnaryConversions(LHS.take()); 7765 if (LHS.isInvalid()) 7766 return QualType(); 7767 7768 RHS = UsualUnaryConversions(RHS.take()); 7769 if (RHS.isInvalid()) 7770 return QualType(); 7771 7772 if (!LHS.get()->getType()->isScalarType() || 7773 !RHS.get()->getType()->isScalarType()) 7774 return InvalidOperands(Loc, LHS, RHS); 7775 7776 return Context.IntTy; 7777 } 7778 7779 // The following is safe because we only use this method for 7780 // non-overloadable operands. 7781 7782 // C++ [expr.log.and]p1 7783 // C++ [expr.log.or]p1 7784 // The operands are both contextually converted to type bool. 7785 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 7786 if (LHSRes.isInvalid()) 7787 return InvalidOperands(Loc, LHS, RHS); 7788 LHS = LHSRes; 7789 7790 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 7791 if (RHSRes.isInvalid()) 7792 return InvalidOperands(Loc, LHS, RHS); 7793 RHS = RHSRes; 7794 7795 // C++ [expr.log.and]p2 7796 // C++ [expr.log.or]p2 7797 // The result is a bool. 7798 return Context.BoolTy; 7799 } 7800 7801 /// IsReadonlyProperty - Verify that otherwise a valid l-value expression 7802 /// is a read-only property; return true if so. A readonly property expression 7803 /// depends on various declarations and thus must be treated specially. 7804 /// 7805 static bool IsReadonlyProperty(Expr *E, Sema &S) { 7806 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E); 7807 if (!PropExpr) return false; 7808 if (PropExpr->isImplicitProperty()) return false; 7809 7810 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty(); 7811 QualType BaseType = PropExpr->isSuperReceiver() ? 7812 PropExpr->getSuperReceiverType() : 7813 PropExpr->getBase()->getType(); 7814 7815 if (const ObjCObjectPointerType *OPT = 7816 BaseType->getAsObjCInterfacePointerType()) 7817 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl()) 7818 if (S.isPropertyReadonly(PDecl, IFace)) 7819 return true; 7820 return false; 7821 } 7822 7823 static bool IsReadonlyMessage(Expr *E, Sema &S) { 7824 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 7825 if (!ME) return false; 7826 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 7827 ObjCMessageExpr *Base = 7828 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 7829 if (!Base) return false; 7830 return Base->getMethodDecl() != 0; 7831 } 7832 7833 /// Is the given expression (which must be 'const') a reference to a 7834 /// variable which was originally non-const, but which has become 7835 /// 'const' due to being captured within a block? 7836 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 7837 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 7838 assert(E->isLValue() && E->getType().isConstQualified()); 7839 E = E->IgnoreParens(); 7840 7841 // Must be a reference to a declaration from an enclosing scope. 7842 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 7843 if (!DRE) return NCCK_None; 7844 if (!DRE->refersToEnclosingLocal()) return NCCK_None; 7845 7846 // The declaration must be a variable which is not declared 'const'. 7847 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 7848 if (!var) return NCCK_None; 7849 if (var->getType().isConstQualified()) return NCCK_None; 7850 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 7851 7852 // Decide whether the first capture was for a block or a lambda. 7853 DeclContext *DC = S.CurContext; 7854 while (DC->getParent() != var->getDeclContext()) 7855 DC = DC->getParent(); 7856 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 7857 } 7858 7859 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 7860 /// emit an error and return true. If so, return false. 7861 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 7862 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 7863 SourceLocation OrigLoc = Loc; 7864 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 7865 &Loc); 7866 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S)) 7867 IsLV = Expr::MLV_ReadonlyProperty; 7868 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 7869 IsLV = Expr::MLV_InvalidMessageExpression; 7870 if (IsLV == Expr::MLV_Valid) 7871 return false; 7872 7873 unsigned Diag = 0; 7874 bool NeedType = false; 7875 switch (IsLV) { // C99 6.5.16p2 7876 case Expr::MLV_ConstQualified: 7877 Diag = diag::err_typecheck_assign_const; 7878 7879 // Use a specialized diagnostic when we're assigning to an object 7880 // from an enclosing function or block. 7881 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 7882 if (NCCK == NCCK_Block) 7883 Diag = diag::err_block_decl_ref_not_modifiable_lvalue; 7884 else 7885 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue; 7886 break; 7887 } 7888 7889 // In ARC, use some specialized diagnostics for occasions where we 7890 // infer 'const'. These are always pseudo-strong variables. 7891 if (S.getLangOpts().ObjCAutoRefCount) { 7892 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 7893 if (declRef && isa<VarDecl>(declRef->getDecl())) { 7894 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 7895 7896 // Use the normal diagnostic if it's pseudo-__strong but the 7897 // user actually wrote 'const'. 7898 if (var->isARCPseudoStrong() && 7899 (!var->getTypeSourceInfo() || 7900 !var->getTypeSourceInfo()->getType().isConstQualified())) { 7901 // There are two pseudo-strong cases: 7902 // - self 7903 ObjCMethodDecl *method = S.getCurMethodDecl(); 7904 if (method && var == method->getSelfDecl()) 7905 Diag = method->isClassMethod() 7906 ? diag::err_typecheck_arc_assign_self_class_method 7907 : diag::err_typecheck_arc_assign_self; 7908 7909 // - fast enumeration variables 7910 else 7911 Diag = diag::err_typecheck_arr_assign_enumeration; 7912 7913 SourceRange Assign; 7914 if (Loc != OrigLoc) 7915 Assign = SourceRange(OrigLoc, OrigLoc); 7916 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 7917 // We need to preserve the AST regardless, so migration tool 7918 // can do its job. 7919 return false; 7920 } 7921 } 7922 } 7923 7924 break; 7925 case Expr::MLV_ArrayType: 7926 case Expr::MLV_ArrayTemporary: 7927 Diag = diag::err_typecheck_array_not_modifiable_lvalue; 7928 NeedType = true; 7929 break; 7930 case Expr::MLV_NotObjectType: 7931 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue; 7932 NeedType = true; 7933 break; 7934 case Expr::MLV_LValueCast: 7935 Diag = diag::err_typecheck_lvalue_casts_not_supported; 7936 break; 7937 case Expr::MLV_Valid: 7938 llvm_unreachable("did not take early return for MLV_Valid"); 7939 case Expr::MLV_InvalidExpression: 7940 case Expr::MLV_MemberFunction: 7941 case Expr::MLV_ClassTemporary: 7942 Diag = diag::err_typecheck_expression_not_modifiable_lvalue; 7943 break; 7944 case Expr::MLV_IncompleteType: 7945 case Expr::MLV_IncompleteVoidType: 7946 return S.RequireCompleteType(Loc, E->getType(), 7947 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 7948 case Expr::MLV_DuplicateVectorComponents: 7949 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 7950 break; 7951 case Expr::MLV_ReadonlyProperty: 7952 case Expr::MLV_NoSetterProperty: 7953 llvm_unreachable("readonly properties should be processed differently"); 7954 case Expr::MLV_InvalidMessageExpression: 7955 Diag = diag::error_readonly_message_assignment; 7956 break; 7957 case Expr::MLV_SubObjCPropertySetting: 7958 Diag = diag::error_no_subobject_property_setting; 7959 break; 7960 } 7961 7962 SourceRange Assign; 7963 if (Loc != OrigLoc) 7964 Assign = SourceRange(OrigLoc, OrigLoc); 7965 if (NeedType) 7966 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign; 7967 else 7968 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 7969 return true; 7970 } 7971 7972 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 7973 SourceLocation Loc, 7974 Sema &Sema) { 7975 // C / C++ fields 7976 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 7977 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 7978 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 7979 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 7980 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 7981 } 7982 7983 // Objective-C instance variables 7984 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 7985 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 7986 if (OL && OR && OL->getDecl() == OR->getDecl()) { 7987 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 7988 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 7989 if (RL && RR && RL->getDecl() == RR->getDecl()) 7990 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 7991 } 7992 } 7993 7994 // C99 6.5.16.1 7995 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 7996 SourceLocation Loc, 7997 QualType CompoundType) { 7998 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 7999 8000 // Verify that LHS is a modifiable lvalue, and emit error if not. 8001 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 8002 return QualType(); 8003 8004 QualType LHSType = LHSExpr->getType(); 8005 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 8006 CompoundType; 8007 AssignConvertType ConvTy; 8008 if (CompoundType.isNull()) { 8009 Expr *RHSCheck = RHS.get(); 8010 8011 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 8012 8013 QualType LHSTy(LHSType); 8014 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 8015 if (RHS.isInvalid()) 8016 return QualType(); 8017 // Special case of NSObject attributes on c-style pointer types. 8018 if (ConvTy == IncompatiblePointer && 8019 ((Context.isObjCNSObjectType(LHSType) && 8020 RHSType->isObjCObjectPointerType()) || 8021 (Context.isObjCNSObjectType(RHSType) && 8022 LHSType->isObjCObjectPointerType()))) 8023 ConvTy = Compatible; 8024 8025 if (ConvTy == Compatible && 8026 LHSType->isObjCObjectType()) 8027 Diag(Loc, diag::err_objc_object_assignment) 8028 << LHSType; 8029 8030 // If the RHS is a unary plus or minus, check to see if they = and + are 8031 // right next to each other. If so, the user may have typo'd "x =+ 4" 8032 // instead of "x += 4". 8033 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 8034 RHSCheck = ICE->getSubExpr(); 8035 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 8036 if ((UO->getOpcode() == UO_Plus || 8037 UO->getOpcode() == UO_Minus) && 8038 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 8039 // Only if the two operators are exactly adjacent. 8040 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 8041 // And there is a space or other character before the subexpr of the 8042 // unary +/-. We don't want to warn on "x=-1". 8043 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 8044 UO->getSubExpr()->getLocStart().isFileID()) { 8045 Diag(Loc, diag::warn_not_compound_assign) 8046 << (UO->getOpcode() == UO_Plus ? "+" : "-") 8047 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 8048 } 8049 } 8050 8051 if (ConvTy == Compatible) { 8052 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 8053 // Warn about retain cycles where a block captures the LHS, but 8054 // not if the LHS is a simple variable into which the block is 8055 // being stored...unless that variable can be captured by reference! 8056 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 8057 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 8058 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 8059 checkRetainCycles(LHSExpr, RHS.get()); 8060 8061 // It is safe to assign a weak reference into a strong variable. 8062 // Although this code can still have problems: 8063 // id x = self.weakProp; 8064 // id y = self.weakProp; 8065 // we do not warn to warn spuriously when 'x' and 'y' are on separate 8066 // paths through the function. This should be revisited if 8067 // -Wrepeated-use-of-weak is made flow-sensitive. 8068 DiagnosticsEngine::Level Level = 8069 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 8070 RHS.get()->getLocStart()); 8071 if (Level != DiagnosticsEngine::Ignored) 8072 getCurFunction()->markSafeWeakUse(RHS.get()); 8073 8074 } else if (getLangOpts().ObjCAutoRefCount) { 8075 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 8076 } 8077 } 8078 } else { 8079 // Compound assignment "x += y" 8080 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 8081 } 8082 8083 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 8084 RHS.get(), AA_Assigning)) 8085 return QualType(); 8086 8087 CheckForNullPointerDereference(*this, LHSExpr); 8088 8089 // C99 6.5.16p3: The type of an assignment expression is the type of the 8090 // left operand unless the left operand has qualified type, in which case 8091 // it is the unqualified version of the type of the left operand. 8092 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 8093 // is converted to the type of the assignment expression (above). 8094 // C++ 5.17p1: the type of the assignment expression is that of its left 8095 // operand. 8096 return (getLangOpts().CPlusPlus 8097 ? LHSType : LHSType.getUnqualifiedType()); 8098 } 8099 8100 // C99 6.5.17 8101 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 8102 SourceLocation Loc) { 8103 LHS = S.CheckPlaceholderExpr(LHS.take()); 8104 RHS = S.CheckPlaceholderExpr(RHS.take()); 8105 if (LHS.isInvalid() || RHS.isInvalid()) 8106 return QualType(); 8107 8108 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 8109 // operands, but not unary promotions. 8110 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 8111 8112 // So we treat the LHS as a ignored value, and in C++ we allow the 8113 // containing site to determine what should be done with the RHS. 8114 LHS = S.IgnoredValueConversions(LHS.take()); 8115 if (LHS.isInvalid()) 8116 return QualType(); 8117 8118 S.DiagnoseUnusedExprResult(LHS.get()); 8119 8120 if (!S.getLangOpts().CPlusPlus) { 8121 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take()); 8122 if (RHS.isInvalid()) 8123 return QualType(); 8124 if (!RHS.get()->getType()->isVoidType()) 8125 S.RequireCompleteType(Loc, RHS.get()->getType(), 8126 diag::err_incomplete_type); 8127 } 8128 8129 return RHS.get()->getType(); 8130 } 8131 8132 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 8133 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 8134 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 8135 ExprValueKind &VK, 8136 SourceLocation OpLoc, 8137 bool IsInc, bool IsPrefix) { 8138 if (Op->isTypeDependent()) 8139 return S.Context.DependentTy; 8140 8141 QualType ResType = Op->getType(); 8142 // Atomic types can be used for increment / decrement where the non-atomic 8143 // versions can, so ignore the _Atomic() specifier for the purpose of 8144 // checking. 8145 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8146 ResType = ResAtomicType->getValueType(); 8147 8148 assert(!ResType.isNull() && "no type for increment/decrement expression"); 8149 8150 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 8151 // Decrement of bool is not allowed. 8152 if (!IsInc) { 8153 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 8154 return QualType(); 8155 } 8156 // Increment of bool sets it to true, but is deprecated. 8157 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); 8158 } else if (ResType->isRealType()) { 8159 // OK! 8160 } else if (ResType->isPointerType()) { 8161 // C99 6.5.2.4p2, 6.5.6p2 8162 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 8163 return QualType(); 8164 } else if (ResType->isObjCObjectPointerType()) { 8165 // On modern runtimes, ObjC pointer arithmetic is forbidden. 8166 // Otherwise, we just need a complete type. 8167 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 8168 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 8169 return QualType(); 8170 } else if (ResType->isAnyComplexType()) { 8171 // C99 does not support ++/-- on complex types, we allow as an extension. 8172 S.Diag(OpLoc, diag::ext_integer_increment_complex) 8173 << ResType << Op->getSourceRange(); 8174 } else if (ResType->isPlaceholderType()) { 8175 ExprResult PR = S.CheckPlaceholderExpr(Op); 8176 if (PR.isInvalid()) return QualType(); 8177 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc, 8178 IsInc, IsPrefix); 8179 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 8180 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 8181 } else { 8182 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 8183 << ResType << int(IsInc) << Op->getSourceRange(); 8184 return QualType(); 8185 } 8186 // At this point, we know we have a real, complex or pointer type. 8187 // Now make sure the operand is a modifiable lvalue. 8188 if (CheckForModifiableLvalue(Op, OpLoc, S)) 8189 return QualType(); 8190 // In C++, a prefix increment is the same type as the operand. Otherwise 8191 // (in C or with postfix), the increment is the unqualified type of the 8192 // operand. 8193 if (IsPrefix && S.getLangOpts().CPlusPlus) { 8194 VK = VK_LValue; 8195 return ResType; 8196 } else { 8197 VK = VK_RValue; 8198 return ResType.getUnqualifiedType(); 8199 } 8200 } 8201 8202 8203 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 8204 /// This routine allows us to typecheck complex/recursive expressions 8205 /// where the declaration is needed for type checking. We only need to 8206 /// handle cases when the expression references a function designator 8207 /// or is an lvalue. Here are some examples: 8208 /// - &(x) => x 8209 /// - &*****f => f for f a function designator. 8210 /// - &s.xx => s 8211 /// - &s.zz[1].yy -> s, if zz is an array 8212 /// - *(x + 1) -> x, if x is an array 8213 /// - &"123"[2] -> 0 8214 /// - & __real__ x -> x 8215 static ValueDecl *getPrimaryDecl(Expr *E) { 8216 switch (E->getStmtClass()) { 8217 case Stmt::DeclRefExprClass: 8218 return cast<DeclRefExpr>(E)->getDecl(); 8219 case Stmt::MemberExprClass: 8220 // If this is an arrow operator, the address is an offset from 8221 // the base's value, so the object the base refers to is 8222 // irrelevant. 8223 if (cast<MemberExpr>(E)->isArrow()) 8224 return 0; 8225 // Otherwise, the expression refers to a part of the base 8226 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 8227 case Stmt::ArraySubscriptExprClass: { 8228 // FIXME: This code shouldn't be necessary! We should catch the implicit 8229 // promotion of register arrays earlier. 8230 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 8231 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 8232 if (ICE->getSubExpr()->getType()->isArrayType()) 8233 return getPrimaryDecl(ICE->getSubExpr()); 8234 } 8235 return 0; 8236 } 8237 case Stmt::UnaryOperatorClass: { 8238 UnaryOperator *UO = cast<UnaryOperator>(E); 8239 8240 switch(UO->getOpcode()) { 8241 case UO_Real: 8242 case UO_Imag: 8243 case UO_Extension: 8244 return getPrimaryDecl(UO->getSubExpr()); 8245 default: 8246 return 0; 8247 } 8248 } 8249 case Stmt::ParenExprClass: 8250 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 8251 case Stmt::ImplicitCastExprClass: 8252 // If the result of an implicit cast is an l-value, we care about 8253 // the sub-expression; otherwise, the result here doesn't matter. 8254 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 8255 default: 8256 return 0; 8257 } 8258 } 8259 8260 namespace { 8261 enum { 8262 AO_Bit_Field = 0, 8263 AO_Vector_Element = 1, 8264 AO_Property_Expansion = 2, 8265 AO_Register_Variable = 3, 8266 AO_No_Error = 4 8267 }; 8268 } 8269 /// \brief Diagnose invalid operand for address of operations. 8270 /// 8271 /// \param Type The type of operand which cannot have its address taken. 8272 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 8273 Expr *E, unsigned Type) { 8274 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 8275 } 8276 8277 /// CheckAddressOfOperand - The operand of & must be either a function 8278 /// designator or an lvalue designating an object. If it is an lvalue, the 8279 /// object cannot be declared with storage class register or be a bit field. 8280 /// Note: The usual conversions are *not* applied to the operand of the & 8281 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 8282 /// In C++, the operand might be an overloaded function name, in which case 8283 /// we allow the '&' but retain the overloaded-function type. 8284 static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp, 8285 SourceLocation OpLoc) { 8286 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 8287 if (PTy->getKind() == BuiltinType::Overload) { 8288 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) { 8289 assert(cast<UnaryOperator>(OrigOp.get()->IgnoreParens())->getOpcode() 8290 == UO_AddrOf); 8291 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 8292 << OrigOp.get()->getSourceRange(); 8293 return QualType(); 8294 } 8295 8296 return S.Context.OverloadTy; 8297 } 8298 8299 if (PTy->getKind() == BuiltinType::UnknownAny) 8300 return S.Context.UnknownAnyTy; 8301 8302 if (PTy->getKind() == BuiltinType::BoundMember) { 8303 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8304 << OrigOp.get()->getSourceRange(); 8305 return QualType(); 8306 } 8307 8308 OrigOp = S.CheckPlaceholderExpr(OrigOp.take()); 8309 if (OrigOp.isInvalid()) return QualType(); 8310 } 8311 8312 if (OrigOp.get()->isTypeDependent()) 8313 return S.Context.DependentTy; 8314 8315 assert(!OrigOp.get()->getType()->isPlaceholderType()); 8316 8317 // Make sure to ignore parentheses in subsequent checks 8318 Expr *op = OrigOp.get()->IgnoreParens(); 8319 8320 if (S.getLangOpts().C99) { 8321 // Implement C99-only parts of addressof rules. 8322 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 8323 if (uOp->getOpcode() == UO_Deref) 8324 // Per C99 6.5.3.2, the address of a deref always returns a valid result 8325 // (assuming the deref expression is valid). 8326 return uOp->getSubExpr()->getType(); 8327 } 8328 // Technically, there should be a check for array subscript 8329 // expressions here, but the result of one is always an lvalue anyway. 8330 } 8331 ValueDecl *dcl = getPrimaryDecl(op); 8332 Expr::LValueClassification lval = op->ClassifyLValue(S.Context); 8333 unsigned AddressOfError = AO_No_Error; 8334 8335 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 8336 bool sfinae = (bool)S.isSFINAEContext(); 8337 S.Diag(OpLoc, S.isSFINAEContext() ? diag::err_typecheck_addrof_temporary 8338 : diag::ext_typecheck_addrof_temporary) 8339 << op->getType() << op->getSourceRange(); 8340 if (sfinae) 8341 return QualType(); 8342 // Materialize the temporary as an lvalue so that we can take its address. 8343 OrigOp = op = new (S.Context) 8344 MaterializeTemporaryExpr(op->getType(), OrigOp.take(), true); 8345 } else if (isa<ObjCSelectorExpr>(op)) { 8346 return S.Context.getPointerType(op->getType()); 8347 } else if (lval == Expr::LV_MemberFunction) { 8348 // If it's an instance method, make a member pointer. 8349 // The expression must have exactly the form &A::foo. 8350 8351 // If the underlying expression isn't a decl ref, give up. 8352 if (!isa<DeclRefExpr>(op)) { 8353 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8354 << OrigOp.get()->getSourceRange(); 8355 return QualType(); 8356 } 8357 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 8358 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 8359 8360 // The id-expression was parenthesized. 8361 if (OrigOp.get() != DRE) { 8362 S.Diag(OpLoc, diag::err_parens_pointer_member_function) 8363 << OrigOp.get()->getSourceRange(); 8364 8365 // The method was named without a qualifier. 8366 } else if (!DRE->getQualifier()) { 8367 if (MD->getParent()->getName().empty()) 8368 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function) 8369 << op->getSourceRange(); 8370 else { 8371 SmallString<32> Str; 8372 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 8373 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function) 8374 << op->getSourceRange() 8375 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 8376 } 8377 } 8378 8379 return S.Context.getMemberPointerType(op->getType(), 8380 S.Context.getTypeDeclType(MD->getParent()).getTypePtr()); 8381 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 8382 // C99 6.5.3.2p1 8383 // The operand must be either an l-value or a function designator 8384 if (!op->getType()->isFunctionType()) { 8385 // Use a special diagnostic for loads from property references. 8386 if (isa<PseudoObjectExpr>(op)) { 8387 AddressOfError = AO_Property_Expansion; 8388 } else { 8389 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 8390 << op->getType() << op->getSourceRange(); 8391 return QualType(); 8392 } 8393 } 8394 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 8395 // The operand cannot be a bit-field 8396 AddressOfError = AO_Bit_Field; 8397 } else if (op->getObjectKind() == OK_VectorComponent) { 8398 // The operand cannot be an element of a vector 8399 AddressOfError = AO_Vector_Element; 8400 } else if (dcl) { // C99 6.5.3.2p1 8401 // We have an lvalue with a decl. Make sure the decl is not declared 8402 // with the register storage-class specifier. 8403 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 8404 // in C++ it is not error to take address of a register 8405 // variable (c++03 7.1.1P3) 8406 if (vd->getStorageClass() == SC_Register && 8407 !S.getLangOpts().CPlusPlus) { 8408 AddressOfError = AO_Register_Variable; 8409 } 8410 } else if (isa<FunctionTemplateDecl>(dcl)) { 8411 return S.Context.OverloadTy; 8412 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 8413 // Okay: we can take the address of a field. 8414 // Could be a pointer to member, though, if there is an explicit 8415 // scope qualifier for the class. 8416 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 8417 DeclContext *Ctx = dcl->getDeclContext(); 8418 if (Ctx && Ctx->isRecord()) { 8419 if (dcl->getType()->isReferenceType()) { 8420 S.Diag(OpLoc, 8421 diag::err_cannot_form_pointer_to_member_of_reference_type) 8422 << dcl->getDeclName() << dcl->getType(); 8423 return QualType(); 8424 } 8425 8426 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 8427 Ctx = Ctx->getParent(); 8428 return S.Context.getMemberPointerType(op->getType(), 8429 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 8430 } 8431 } 8432 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl)) 8433 llvm_unreachable("Unknown/unexpected decl type"); 8434 } 8435 8436 if (AddressOfError != AO_No_Error) { 8437 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError); 8438 return QualType(); 8439 } 8440 8441 if (lval == Expr::LV_IncompleteVoidType) { 8442 // Taking the address of a void variable is technically illegal, but we 8443 // allow it in cases which are otherwise valid. 8444 // Example: "extern void x; void* y = &x;". 8445 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 8446 } 8447 8448 // If the operand has type "type", the result has type "pointer to type". 8449 if (op->getType()->isObjCObjectType()) 8450 return S.Context.getObjCObjectPointerType(op->getType()); 8451 return S.Context.getPointerType(op->getType()); 8452 } 8453 8454 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 8455 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 8456 SourceLocation OpLoc) { 8457 if (Op->isTypeDependent()) 8458 return S.Context.DependentTy; 8459 8460 ExprResult ConvResult = S.UsualUnaryConversions(Op); 8461 if (ConvResult.isInvalid()) 8462 return QualType(); 8463 Op = ConvResult.take(); 8464 QualType OpTy = Op->getType(); 8465 QualType Result; 8466 8467 if (isa<CXXReinterpretCastExpr>(Op)) { 8468 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 8469 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 8470 Op->getSourceRange()); 8471 } 8472 8473 // Note that per both C89 and C99, indirection is always legal, even if OpTy 8474 // is an incomplete type or void. It would be possible to warn about 8475 // dereferencing a void pointer, but it's completely well-defined, and such a 8476 // warning is unlikely to catch any mistakes. 8477 if (const PointerType *PT = OpTy->getAs<PointerType>()) 8478 Result = PT->getPointeeType(); 8479 else if (const ObjCObjectPointerType *OPT = 8480 OpTy->getAs<ObjCObjectPointerType>()) 8481 Result = OPT->getPointeeType(); 8482 else { 8483 ExprResult PR = S.CheckPlaceholderExpr(Op); 8484 if (PR.isInvalid()) return QualType(); 8485 if (PR.take() != Op) 8486 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc); 8487 } 8488 8489 if (Result.isNull()) { 8490 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 8491 << OpTy << Op->getSourceRange(); 8492 return QualType(); 8493 } 8494 8495 // Dereferences are usually l-values... 8496 VK = VK_LValue; 8497 8498 // ...except that certain expressions are never l-values in C. 8499 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 8500 VK = VK_RValue; 8501 8502 return Result; 8503 } 8504 8505 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode( 8506 tok::TokenKind Kind) { 8507 BinaryOperatorKind Opc; 8508 switch (Kind) { 8509 default: llvm_unreachable("Unknown binop!"); 8510 case tok::periodstar: Opc = BO_PtrMemD; break; 8511 case tok::arrowstar: Opc = BO_PtrMemI; break; 8512 case tok::star: Opc = BO_Mul; break; 8513 case tok::slash: Opc = BO_Div; break; 8514 case tok::percent: Opc = BO_Rem; break; 8515 case tok::plus: Opc = BO_Add; break; 8516 case tok::minus: Opc = BO_Sub; break; 8517 case tok::lessless: Opc = BO_Shl; break; 8518 case tok::greatergreater: Opc = BO_Shr; break; 8519 case tok::lessequal: Opc = BO_LE; break; 8520 case tok::less: Opc = BO_LT; break; 8521 case tok::greaterequal: Opc = BO_GE; break; 8522 case tok::greater: Opc = BO_GT; break; 8523 case tok::exclaimequal: Opc = BO_NE; break; 8524 case tok::equalequal: Opc = BO_EQ; break; 8525 case tok::amp: Opc = BO_And; break; 8526 case tok::caret: Opc = BO_Xor; break; 8527 case tok::pipe: Opc = BO_Or; break; 8528 case tok::ampamp: Opc = BO_LAnd; break; 8529 case tok::pipepipe: Opc = BO_LOr; break; 8530 case tok::equal: Opc = BO_Assign; break; 8531 case tok::starequal: Opc = BO_MulAssign; break; 8532 case tok::slashequal: Opc = BO_DivAssign; break; 8533 case tok::percentequal: Opc = BO_RemAssign; break; 8534 case tok::plusequal: Opc = BO_AddAssign; break; 8535 case tok::minusequal: Opc = BO_SubAssign; break; 8536 case tok::lesslessequal: Opc = BO_ShlAssign; break; 8537 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 8538 case tok::ampequal: Opc = BO_AndAssign; break; 8539 case tok::caretequal: Opc = BO_XorAssign; break; 8540 case tok::pipeequal: Opc = BO_OrAssign; break; 8541 case tok::comma: Opc = BO_Comma; break; 8542 } 8543 return Opc; 8544 } 8545 8546 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 8547 tok::TokenKind Kind) { 8548 UnaryOperatorKind Opc; 8549 switch (Kind) { 8550 default: llvm_unreachable("Unknown unary op!"); 8551 case tok::plusplus: Opc = UO_PreInc; break; 8552 case tok::minusminus: Opc = UO_PreDec; break; 8553 case tok::amp: Opc = UO_AddrOf; break; 8554 case tok::star: Opc = UO_Deref; break; 8555 case tok::plus: Opc = UO_Plus; break; 8556 case tok::minus: Opc = UO_Minus; break; 8557 case tok::tilde: Opc = UO_Not; break; 8558 case tok::exclaim: Opc = UO_LNot; break; 8559 case tok::kw___real: Opc = UO_Real; break; 8560 case tok::kw___imag: Opc = UO_Imag; break; 8561 case tok::kw___extension__: Opc = UO_Extension; break; 8562 } 8563 return Opc; 8564 } 8565 8566 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 8567 /// This warning is only emitted for builtin assignment operations. It is also 8568 /// suppressed in the event of macro expansions. 8569 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 8570 SourceLocation OpLoc) { 8571 if (!S.ActiveTemplateInstantiations.empty()) 8572 return; 8573 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 8574 return; 8575 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 8576 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 8577 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 8578 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 8579 if (!LHSDeclRef || !RHSDeclRef || 8580 LHSDeclRef->getLocation().isMacroID() || 8581 RHSDeclRef->getLocation().isMacroID()) 8582 return; 8583 const ValueDecl *LHSDecl = 8584 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 8585 const ValueDecl *RHSDecl = 8586 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 8587 if (LHSDecl != RHSDecl) 8588 return; 8589 if (LHSDecl->getType().isVolatileQualified()) 8590 return; 8591 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 8592 if (RefTy->getPointeeType().isVolatileQualified()) 8593 return; 8594 8595 S.Diag(OpLoc, diag::warn_self_assignment) 8596 << LHSDeclRef->getType() 8597 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8598 } 8599 8600 /// Check if a bitwise-& is performed on an Objective-C pointer. This 8601 /// is usually indicative of introspection within the Objective-C pointer. 8602 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 8603 SourceLocation OpLoc) { 8604 if (!S.getLangOpts().ObjC1) 8605 return; 8606 8607 const Expr *ObjCPointerExpr = 0, *OtherExpr = 0; 8608 const Expr *LHS = L.get(); 8609 const Expr *RHS = R.get(); 8610 8611 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 8612 ObjCPointerExpr = LHS; 8613 OtherExpr = RHS; 8614 } 8615 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 8616 ObjCPointerExpr = RHS; 8617 OtherExpr = LHS; 8618 } 8619 8620 // This warning is deliberately made very specific to reduce false 8621 // positives with logic that uses '&' for hashing. This logic mainly 8622 // looks for code trying to introspect into tagged pointers, which 8623 // code should generally never do. 8624 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 8625 S.Diag(OpLoc, diag::warn_objc_pointer_masking) 8626 << ObjCPointerExpr->getSourceRange(); 8627 } 8628 } 8629 8630 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 8631 /// operator @p Opc at location @c TokLoc. This routine only supports 8632 /// built-in operations; ActOnBinOp handles overloaded operators. 8633 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 8634 BinaryOperatorKind Opc, 8635 Expr *LHSExpr, Expr *RHSExpr) { 8636 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 8637 // The syntax only allows initializer lists on the RHS of assignment, 8638 // so we don't need to worry about accepting invalid code for 8639 // non-assignment operators. 8640 // C++11 5.17p9: 8641 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 8642 // of x = {} is x = T(). 8643 InitializationKind Kind = 8644 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 8645 InitializedEntity Entity = 8646 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 8647 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 8648 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 8649 if (Init.isInvalid()) 8650 return Init; 8651 RHSExpr = Init.take(); 8652 } 8653 8654 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 8655 QualType ResultTy; // Result type of the binary operator. 8656 // The following two variables are used for compound assignment operators 8657 QualType CompLHSTy; // Type of LHS after promotions for computation 8658 QualType CompResultTy; // Type of computation result 8659 ExprValueKind VK = VK_RValue; 8660 ExprObjectKind OK = OK_Ordinary; 8661 8662 switch (Opc) { 8663 case BO_Assign: 8664 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 8665 if (getLangOpts().CPlusPlus && 8666 LHS.get()->getObjectKind() != OK_ObjCProperty) { 8667 VK = LHS.get()->getValueKind(); 8668 OK = LHS.get()->getObjectKind(); 8669 } 8670 if (!ResultTy.isNull()) 8671 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 8672 break; 8673 case BO_PtrMemD: 8674 case BO_PtrMemI: 8675 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 8676 Opc == BO_PtrMemI); 8677 break; 8678 case BO_Mul: 8679 case BO_Div: 8680 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 8681 Opc == BO_Div); 8682 break; 8683 case BO_Rem: 8684 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 8685 break; 8686 case BO_Add: 8687 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 8688 break; 8689 case BO_Sub: 8690 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 8691 break; 8692 case BO_Shl: 8693 case BO_Shr: 8694 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 8695 break; 8696 case BO_LE: 8697 case BO_LT: 8698 case BO_GE: 8699 case BO_GT: 8700 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 8701 break; 8702 case BO_EQ: 8703 case BO_NE: 8704 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 8705 break; 8706 case BO_And: 8707 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 8708 case BO_Xor: 8709 case BO_Or: 8710 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 8711 break; 8712 case BO_LAnd: 8713 case BO_LOr: 8714 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 8715 break; 8716 case BO_MulAssign: 8717 case BO_DivAssign: 8718 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 8719 Opc == BO_DivAssign); 8720 CompLHSTy = CompResultTy; 8721 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8722 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8723 break; 8724 case BO_RemAssign: 8725 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 8726 CompLHSTy = CompResultTy; 8727 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8728 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8729 break; 8730 case BO_AddAssign: 8731 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 8732 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8733 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8734 break; 8735 case BO_SubAssign: 8736 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 8737 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8738 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8739 break; 8740 case BO_ShlAssign: 8741 case BO_ShrAssign: 8742 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 8743 CompLHSTy = CompResultTy; 8744 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8745 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8746 break; 8747 case BO_AndAssign: 8748 case BO_XorAssign: 8749 case BO_OrAssign: 8750 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 8751 CompLHSTy = CompResultTy; 8752 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8753 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8754 break; 8755 case BO_Comma: 8756 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 8757 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 8758 VK = RHS.get()->getValueKind(); 8759 OK = RHS.get()->getObjectKind(); 8760 } 8761 break; 8762 } 8763 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 8764 return ExprError(); 8765 8766 // Check for array bounds violations for both sides of the BinaryOperator 8767 CheckArrayAccess(LHS.get()); 8768 CheckArrayAccess(RHS.get()); 8769 8770 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 8771 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 8772 &Context.Idents.get("object_setClass"), 8773 SourceLocation(), LookupOrdinaryName); 8774 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 8775 SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 8776 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 8777 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 8778 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 8779 FixItHint::CreateInsertion(RHSLocEnd, ")"); 8780 } 8781 else 8782 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 8783 } 8784 else if (const ObjCIvarRefExpr *OIRE = 8785 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 8786 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 8787 8788 if (CompResultTy.isNull()) 8789 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc, 8790 ResultTy, VK, OK, OpLoc, 8791 FPFeatures.fp_contract)); 8792 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 8793 OK_ObjCProperty) { 8794 VK = VK_LValue; 8795 OK = LHS.get()->getObjectKind(); 8796 } 8797 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc, 8798 ResultTy, VK, OK, CompLHSTy, 8799 CompResultTy, OpLoc, 8800 FPFeatures.fp_contract)); 8801 } 8802 8803 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 8804 /// operators are mixed in a way that suggests that the programmer forgot that 8805 /// comparison operators have higher precedence. The most typical example of 8806 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 8807 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 8808 SourceLocation OpLoc, Expr *LHSExpr, 8809 Expr *RHSExpr) { 8810 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 8811 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 8812 8813 // Check that one of the sides is a comparison operator. 8814 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 8815 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 8816 if (!isLeftComp && !isRightComp) 8817 return; 8818 8819 // Bitwise operations are sometimes used as eager logical ops. 8820 // Don't diagnose this. 8821 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 8822 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 8823 if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise)) 8824 return; 8825 8826 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 8827 OpLoc) 8828 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 8829 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 8830 SourceRange ParensRange = isLeftComp ? 8831 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 8832 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart()); 8833 8834 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 8835 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 8836 SuggestParentheses(Self, OpLoc, 8837 Self.PDiag(diag::note_precedence_silence) << OpStr, 8838 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 8839 SuggestParentheses(Self, OpLoc, 8840 Self.PDiag(diag::note_precedence_bitwise_first) 8841 << BinaryOperator::getOpcodeStr(Opc), 8842 ParensRange); 8843 } 8844 8845 /// \brief It accepts a '&' expr that is inside a '|' one. 8846 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression 8847 /// in parentheses. 8848 static void 8849 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc, 8850 BinaryOperator *Bop) { 8851 assert(Bop->getOpcode() == BO_And); 8852 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or) 8853 << Bop->getSourceRange() << OpLoc; 8854 SuggestParentheses(Self, Bop->getOperatorLoc(), 8855 Self.PDiag(diag::note_precedence_silence) 8856 << Bop->getOpcodeStr(), 8857 Bop->getSourceRange()); 8858 } 8859 8860 /// \brief It accepts a '&&' expr that is inside a '||' one. 8861 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 8862 /// in parentheses. 8863 static void 8864 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 8865 BinaryOperator *Bop) { 8866 assert(Bop->getOpcode() == BO_LAnd); 8867 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 8868 << Bop->getSourceRange() << OpLoc; 8869 SuggestParentheses(Self, Bop->getOperatorLoc(), 8870 Self.PDiag(diag::note_precedence_silence) 8871 << Bop->getOpcodeStr(), 8872 Bop->getSourceRange()); 8873 } 8874 8875 /// \brief Returns true if the given expression can be evaluated as a constant 8876 /// 'true'. 8877 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 8878 bool Res; 8879 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 8880 } 8881 8882 /// \brief Returns true if the given expression can be evaluated as a constant 8883 /// 'false'. 8884 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 8885 bool Res; 8886 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 8887 } 8888 8889 /// \brief Look for '&&' in the left hand of a '||' expr. 8890 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 8891 Expr *LHSExpr, Expr *RHSExpr) { 8892 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 8893 if (Bop->getOpcode() == BO_LAnd) { 8894 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 8895 if (EvaluatesAsFalse(S, RHSExpr)) 8896 return; 8897 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 8898 if (!EvaluatesAsTrue(S, Bop->getLHS())) 8899 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 8900 } else if (Bop->getOpcode() == BO_LOr) { 8901 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 8902 // If it's "a || b && 1 || c" we didn't warn earlier for 8903 // "a || b && 1", but warn now. 8904 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 8905 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 8906 } 8907 } 8908 } 8909 } 8910 8911 /// \brief Look for '&&' in the right hand of a '||' expr. 8912 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 8913 Expr *LHSExpr, Expr *RHSExpr) { 8914 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 8915 if (Bop->getOpcode() == BO_LAnd) { 8916 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 8917 if (EvaluatesAsFalse(S, LHSExpr)) 8918 return; 8919 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 8920 if (!EvaluatesAsTrue(S, Bop->getRHS())) 8921 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 8922 } 8923 } 8924 } 8925 8926 /// \brief Look for '&' in the left or right hand of a '|' expr. 8927 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc, 8928 Expr *OrArg) { 8929 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) { 8930 if (Bop->getOpcode() == BO_And) 8931 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop); 8932 } 8933 } 8934 8935 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 8936 Expr *SubExpr, StringRef Shift) { 8937 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 8938 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 8939 StringRef Op = Bop->getOpcodeStr(); 8940 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 8941 << Bop->getSourceRange() << OpLoc << Shift << Op; 8942 SuggestParentheses(S, Bop->getOperatorLoc(), 8943 S.PDiag(diag::note_precedence_silence) << Op, 8944 Bop->getSourceRange()); 8945 } 8946 } 8947 } 8948 8949 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 8950 Expr *LHSExpr, Expr *RHSExpr) { 8951 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 8952 if (!OCE) 8953 return; 8954 8955 FunctionDecl *FD = OCE->getDirectCallee(); 8956 if (!FD || !FD->isOverloadedOperator()) 8957 return; 8958 8959 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 8960 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 8961 return; 8962 8963 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 8964 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 8965 << (Kind == OO_LessLess); 8966 SuggestParentheses(S, OCE->getOperatorLoc(), 8967 S.PDiag(diag::note_precedence_silence) 8968 << (Kind == OO_LessLess ? "<<" : ">>"), 8969 OCE->getSourceRange()); 8970 SuggestParentheses(S, OpLoc, 8971 S.PDiag(diag::note_evaluate_comparison_first), 8972 SourceRange(OCE->getArg(1)->getLocStart(), 8973 RHSExpr->getLocEnd())); 8974 } 8975 8976 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 8977 /// precedence. 8978 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 8979 SourceLocation OpLoc, Expr *LHSExpr, 8980 Expr *RHSExpr){ 8981 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 8982 if (BinaryOperator::isBitwiseOp(Opc)) 8983 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 8984 8985 // Diagnose "arg1 & arg2 | arg3" 8986 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) { 8987 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr); 8988 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr); 8989 } 8990 8991 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 8992 // We don't warn for 'assert(a || b && "bad")' since this is safe. 8993 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 8994 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 8995 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 8996 } 8997 8998 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 8999 || Opc == BO_Shr) { 9000 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 9001 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 9002 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 9003 } 9004 9005 // Warn on overloaded shift operators and comparisons, such as: 9006 // cout << 5 == 4; 9007 if (BinaryOperator::isComparisonOp(Opc)) 9008 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 9009 } 9010 9011 // Binary Operators. 'Tok' is the token for the operator. 9012 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 9013 tok::TokenKind Kind, 9014 Expr *LHSExpr, Expr *RHSExpr) { 9015 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 9016 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression"); 9017 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression"); 9018 9019 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 9020 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 9021 9022 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 9023 } 9024 9025 /// Build an overloaded binary operator expression in the given scope. 9026 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 9027 BinaryOperatorKind Opc, 9028 Expr *LHS, Expr *RHS) { 9029 // Find all of the overloaded operators visible from this 9030 // point. We perform both an operator-name lookup from the local 9031 // scope and an argument-dependent lookup based on the types of 9032 // the arguments. 9033 UnresolvedSet<16> Functions; 9034 OverloadedOperatorKind OverOp 9035 = BinaryOperator::getOverloadedOperator(Opc); 9036 if (Sc && OverOp != OO_None) 9037 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 9038 RHS->getType(), Functions); 9039 9040 // Build the (potentially-overloaded, potentially-dependent) 9041 // binary operation. 9042 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 9043 } 9044 9045 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 9046 BinaryOperatorKind Opc, 9047 Expr *LHSExpr, Expr *RHSExpr) { 9048 // We want to end up calling one of checkPseudoObjectAssignment 9049 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 9050 // both expressions are overloadable or either is type-dependent), 9051 // or CreateBuiltinBinOp (in any other case). We also want to get 9052 // any placeholder types out of the way. 9053 9054 // Handle pseudo-objects in the LHS. 9055 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 9056 // Assignments with a pseudo-object l-value need special analysis. 9057 if (pty->getKind() == BuiltinType::PseudoObject && 9058 BinaryOperator::isAssignmentOp(Opc)) 9059 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 9060 9061 // Don't resolve overloads if the other type is overloadable. 9062 if (pty->getKind() == BuiltinType::Overload) { 9063 // We can't actually test that if we still have a placeholder, 9064 // though. Fortunately, none of the exceptions we see in that 9065 // code below are valid when the LHS is an overload set. Note 9066 // that an overload set can be dependently-typed, but it never 9067 // instantiates to having an overloadable type. 9068 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 9069 if (resolvedRHS.isInvalid()) return ExprError(); 9070 RHSExpr = resolvedRHS.take(); 9071 9072 if (RHSExpr->isTypeDependent() || 9073 RHSExpr->getType()->isOverloadableType()) 9074 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9075 } 9076 9077 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 9078 if (LHS.isInvalid()) return ExprError(); 9079 LHSExpr = LHS.take(); 9080 } 9081 9082 // Handle pseudo-objects in the RHS. 9083 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 9084 // An overload in the RHS can potentially be resolved by the type 9085 // being assigned to. 9086 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 9087 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 9088 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9089 9090 if (LHSExpr->getType()->isOverloadableType()) 9091 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9092 9093 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 9094 } 9095 9096 // Don't resolve overloads if the other type is overloadable. 9097 if (pty->getKind() == BuiltinType::Overload && 9098 LHSExpr->getType()->isOverloadableType()) 9099 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9100 9101 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 9102 if (!resolvedRHS.isUsable()) return ExprError(); 9103 RHSExpr = resolvedRHS.take(); 9104 } 9105 9106 if (getLangOpts().CPlusPlus) { 9107 // If either expression is type-dependent, always build an 9108 // overloaded op. 9109 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 9110 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9111 9112 // Otherwise, build an overloaded op if either expression has an 9113 // overloadable type. 9114 if (LHSExpr->getType()->isOverloadableType() || 9115 RHSExpr->getType()->isOverloadableType()) 9116 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9117 } 9118 9119 // Build a built-in binary operation. 9120 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 9121 } 9122 9123 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 9124 UnaryOperatorKind Opc, 9125 Expr *InputExpr) { 9126 ExprResult Input = Owned(InputExpr); 9127 ExprValueKind VK = VK_RValue; 9128 ExprObjectKind OK = OK_Ordinary; 9129 QualType resultType; 9130 switch (Opc) { 9131 case UO_PreInc: 9132 case UO_PreDec: 9133 case UO_PostInc: 9134 case UO_PostDec: 9135 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc, 9136 Opc == UO_PreInc || 9137 Opc == UO_PostInc, 9138 Opc == UO_PreInc || 9139 Opc == UO_PreDec); 9140 break; 9141 case UO_AddrOf: 9142 resultType = CheckAddressOfOperand(*this, Input, OpLoc); 9143 break; 9144 case UO_Deref: { 9145 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 9146 if (Input.isInvalid()) return ExprError(); 9147 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 9148 break; 9149 } 9150 case UO_Plus: 9151 case UO_Minus: 9152 Input = UsualUnaryConversions(Input.take()); 9153 if (Input.isInvalid()) return ExprError(); 9154 resultType = Input.get()->getType(); 9155 if (resultType->isDependentType()) 9156 break; 9157 if (resultType->isArithmeticType() || // C99 6.5.3.3p1 9158 resultType->isVectorType()) 9159 break; 9160 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7 9161 resultType->isEnumeralType()) 9162 break; 9163 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 9164 Opc == UO_Plus && 9165 resultType->isPointerType()) 9166 break; 9167 9168 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9169 << resultType << Input.get()->getSourceRange()); 9170 9171 case UO_Not: // bitwise complement 9172 Input = UsualUnaryConversions(Input.take()); 9173 if (Input.isInvalid()) 9174 return ExprError(); 9175 resultType = Input.get()->getType(); 9176 if (resultType->isDependentType()) 9177 break; 9178 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 9179 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 9180 // C99 does not support '~' for complex conjugation. 9181 Diag(OpLoc, diag::ext_integer_complement_complex) 9182 << resultType << Input.get()->getSourceRange(); 9183 else if (resultType->hasIntegerRepresentation()) 9184 break; 9185 else if (resultType->isExtVectorType()) { 9186 if (Context.getLangOpts().OpenCL) { 9187 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 9188 // on vector float types. 9189 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 9190 if (!T->isIntegerType()) 9191 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9192 << resultType << Input.get()->getSourceRange()); 9193 } 9194 break; 9195 } else { 9196 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9197 << resultType << Input.get()->getSourceRange()); 9198 } 9199 break; 9200 9201 case UO_LNot: // logical negation 9202 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 9203 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 9204 if (Input.isInvalid()) return ExprError(); 9205 resultType = Input.get()->getType(); 9206 9207 // Though we still have to promote half FP to float... 9208 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 9209 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take(); 9210 resultType = Context.FloatTy; 9211 } 9212 9213 if (resultType->isDependentType()) 9214 break; 9215 if (resultType->isScalarType()) { 9216 // C99 6.5.3.3p1: ok, fallthrough; 9217 if (Context.getLangOpts().CPlusPlus) { 9218 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 9219 // operand contextually converted to bool. 9220 Input = ImpCastExprToType(Input.take(), Context.BoolTy, 9221 ScalarTypeToBooleanCastKind(resultType)); 9222 } else if (Context.getLangOpts().OpenCL && 9223 Context.getLangOpts().OpenCLVersion < 120) { 9224 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 9225 // operate on scalar float types. 9226 if (!resultType->isIntegerType()) 9227 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9228 << resultType << Input.get()->getSourceRange()); 9229 } 9230 } else if (resultType->isExtVectorType()) { 9231 if (Context.getLangOpts().OpenCL && 9232 Context.getLangOpts().OpenCLVersion < 120) { 9233 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 9234 // operate on vector float types. 9235 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 9236 if (!T->isIntegerType()) 9237 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9238 << resultType << Input.get()->getSourceRange()); 9239 } 9240 // Vector logical not returns the signed variant of the operand type. 9241 resultType = GetSignedVectorType(resultType); 9242 break; 9243 } else { 9244 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9245 << resultType << Input.get()->getSourceRange()); 9246 } 9247 9248 // LNot always has type int. C99 6.5.3.3p5. 9249 // In C++, it's bool. C++ 5.3.1p8 9250 resultType = Context.getLogicalOperationType(); 9251 break; 9252 case UO_Real: 9253 case UO_Imag: 9254 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 9255 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 9256 // complex l-values to ordinary l-values and all other values to r-values. 9257 if (Input.isInvalid()) return ExprError(); 9258 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 9259 if (Input.get()->getValueKind() != VK_RValue && 9260 Input.get()->getObjectKind() == OK_Ordinary) 9261 VK = Input.get()->getValueKind(); 9262 } else if (!getLangOpts().CPlusPlus) { 9263 // In C, a volatile scalar is read by __imag. In C++, it is not. 9264 Input = DefaultLvalueConversion(Input.take()); 9265 } 9266 break; 9267 case UO_Extension: 9268 resultType = Input.get()->getType(); 9269 VK = Input.get()->getValueKind(); 9270 OK = Input.get()->getObjectKind(); 9271 break; 9272 } 9273 if (resultType.isNull() || Input.isInvalid()) 9274 return ExprError(); 9275 9276 // Check for array bounds violations in the operand of the UnaryOperator, 9277 // except for the '*' and '&' operators that have to be handled specially 9278 // by CheckArrayAccess (as there are special cases like &array[arraysize] 9279 // that are explicitly defined as valid by the standard). 9280 if (Opc != UO_AddrOf && Opc != UO_Deref) 9281 CheckArrayAccess(Input.get()); 9282 9283 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType, 9284 VK, OK, OpLoc)); 9285 } 9286 9287 /// \brief Determine whether the given expression is a qualified member 9288 /// access expression, of a form that could be turned into a pointer to member 9289 /// with the address-of operator. 9290 static bool isQualifiedMemberAccess(Expr *E) { 9291 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9292 if (!DRE->getQualifier()) 9293 return false; 9294 9295 ValueDecl *VD = DRE->getDecl(); 9296 if (!VD->isCXXClassMember()) 9297 return false; 9298 9299 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 9300 return true; 9301 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 9302 return Method->isInstance(); 9303 9304 return false; 9305 } 9306 9307 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 9308 if (!ULE->getQualifier()) 9309 return false; 9310 9311 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(), 9312 DEnd = ULE->decls_end(); 9313 D != DEnd; ++D) { 9314 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) { 9315 if (Method->isInstance()) 9316 return true; 9317 } else { 9318 // Overload set does not contain methods. 9319 break; 9320 } 9321 } 9322 9323 return false; 9324 } 9325 9326 return false; 9327 } 9328 9329 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 9330 UnaryOperatorKind Opc, Expr *Input) { 9331 // First things first: handle placeholders so that the 9332 // overloaded-operator check considers the right type. 9333 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 9334 // Increment and decrement of pseudo-object references. 9335 if (pty->getKind() == BuiltinType::PseudoObject && 9336 UnaryOperator::isIncrementDecrementOp(Opc)) 9337 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 9338 9339 // extension is always a builtin operator. 9340 if (Opc == UO_Extension) 9341 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9342 9343 // & gets special logic for several kinds of placeholder. 9344 // The builtin code knows what to do. 9345 if (Opc == UO_AddrOf && 9346 (pty->getKind() == BuiltinType::Overload || 9347 pty->getKind() == BuiltinType::UnknownAny || 9348 pty->getKind() == BuiltinType::BoundMember)) 9349 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9350 9351 // Anything else needs to be handled now. 9352 ExprResult Result = CheckPlaceholderExpr(Input); 9353 if (Result.isInvalid()) return ExprError(); 9354 Input = Result.take(); 9355 } 9356 9357 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 9358 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 9359 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 9360 // Find all of the overloaded operators visible from this 9361 // point. We perform both an operator-name lookup from the local 9362 // scope and an argument-dependent lookup based on the types of 9363 // the arguments. 9364 UnresolvedSet<16> Functions; 9365 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 9366 if (S && OverOp != OO_None) 9367 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 9368 Functions); 9369 9370 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 9371 } 9372 9373 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9374 } 9375 9376 // Unary Operators. 'Tok' is the token for the operator. 9377 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 9378 tok::TokenKind Op, Expr *Input) { 9379 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 9380 } 9381 9382 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 9383 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 9384 LabelDecl *TheDecl) { 9385 TheDecl->setUsed(); 9386 // Create the AST node. The address of a label always has type 'void*'. 9387 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 9388 Context.getPointerType(Context.VoidTy))); 9389 } 9390 9391 /// Given the last statement in a statement-expression, check whether 9392 /// the result is a producing expression (like a call to an 9393 /// ns_returns_retained function) and, if so, rebuild it to hoist the 9394 /// release out of the full-expression. Otherwise, return null. 9395 /// Cannot fail. 9396 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 9397 // Should always be wrapped with one of these. 9398 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 9399 if (!cleanups) return 0; 9400 9401 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 9402 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 9403 return 0; 9404 9405 // Splice out the cast. This shouldn't modify any interesting 9406 // features of the statement. 9407 Expr *producer = cast->getSubExpr(); 9408 assert(producer->getType() == cast->getType()); 9409 assert(producer->getValueKind() == cast->getValueKind()); 9410 cleanups->setSubExpr(producer); 9411 return cleanups; 9412 } 9413 9414 void Sema::ActOnStartStmtExpr() { 9415 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 9416 } 9417 9418 void Sema::ActOnStmtExprError() { 9419 // Note that function is also called by TreeTransform when leaving a 9420 // StmtExpr scope without rebuilding anything. 9421 9422 DiscardCleanupsInEvaluationContext(); 9423 PopExpressionEvaluationContext(); 9424 } 9425 9426 ExprResult 9427 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 9428 SourceLocation RPLoc) { // "({..})" 9429 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 9430 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 9431 9432 if (hasAnyUnrecoverableErrorsInThisFunction()) 9433 DiscardCleanupsInEvaluationContext(); 9434 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!"); 9435 PopExpressionEvaluationContext(); 9436 9437 bool isFileScope 9438 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0); 9439 if (isFileScope) 9440 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope)); 9441 9442 // FIXME: there are a variety of strange constraints to enforce here, for 9443 // example, it is not possible to goto into a stmt expression apparently. 9444 // More semantic analysis is needed. 9445 9446 // If there are sub stmts in the compound stmt, take the type of the last one 9447 // as the type of the stmtexpr. 9448 QualType Ty = Context.VoidTy; 9449 bool StmtExprMayBindToTemp = false; 9450 if (!Compound->body_empty()) { 9451 Stmt *LastStmt = Compound->body_back(); 9452 LabelStmt *LastLabelStmt = 0; 9453 // If LastStmt is a label, skip down through into the body. 9454 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 9455 LastLabelStmt = Label; 9456 LastStmt = Label->getSubStmt(); 9457 } 9458 9459 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 9460 // Do function/array conversion on the last expression, but not 9461 // lvalue-to-rvalue. However, initialize an unqualified type. 9462 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 9463 if (LastExpr.isInvalid()) 9464 return ExprError(); 9465 Ty = LastExpr.get()->getType().getUnqualifiedType(); 9466 9467 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 9468 // In ARC, if the final expression ends in a consume, splice 9469 // the consume out and bind it later. In the alternate case 9470 // (when dealing with a retainable type), the result 9471 // initialization will create a produce. In both cases the 9472 // result will be +1, and we'll need to balance that out with 9473 // a bind. 9474 if (Expr *rebuiltLastStmt 9475 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 9476 LastExpr = rebuiltLastStmt; 9477 } else { 9478 LastExpr = PerformCopyInitialization( 9479 InitializedEntity::InitializeResult(LPLoc, 9480 Ty, 9481 false), 9482 SourceLocation(), 9483 LastExpr); 9484 } 9485 9486 if (LastExpr.isInvalid()) 9487 return ExprError(); 9488 if (LastExpr.get() != 0) { 9489 if (!LastLabelStmt) 9490 Compound->setLastStmt(LastExpr.take()); 9491 else 9492 LastLabelStmt->setSubStmt(LastExpr.take()); 9493 StmtExprMayBindToTemp = true; 9494 } 9495 } 9496 } 9497 } 9498 9499 // FIXME: Check that expression type is complete/non-abstract; statement 9500 // expressions are not lvalues. 9501 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 9502 if (StmtExprMayBindToTemp) 9503 return MaybeBindToTemporary(ResStmtExpr); 9504 return Owned(ResStmtExpr); 9505 } 9506 9507 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 9508 TypeSourceInfo *TInfo, 9509 OffsetOfComponent *CompPtr, 9510 unsigned NumComponents, 9511 SourceLocation RParenLoc) { 9512 QualType ArgTy = TInfo->getType(); 9513 bool Dependent = ArgTy->isDependentType(); 9514 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 9515 9516 // We must have at least one component that refers to the type, and the first 9517 // one is known to be a field designator. Verify that the ArgTy represents 9518 // a struct/union/class. 9519 if (!Dependent && !ArgTy->isRecordType()) 9520 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 9521 << ArgTy << TypeRange); 9522 9523 // Type must be complete per C99 7.17p3 because a declaring a variable 9524 // with an incomplete type would be ill-formed. 9525 if (!Dependent 9526 && RequireCompleteType(BuiltinLoc, ArgTy, 9527 diag::err_offsetof_incomplete_type, TypeRange)) 9528 return ExprError(); 9529 9530 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 9531 // GCC extension, diagnose them. 9532 // FIXME: This diagnostic isn't actually visible because the location is in 9533 // a system header! 9534 if (NumComponents != 1) 9535 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 9536 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); 9537 9538 bool DidWarnAboutNonPOD = false; 9539 QualType CurrentType = ArgTy; 9540 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; 9541 SmallVector<OffsetOfNode, 4> Comps; 9542 SmallVector<Expr*, 4> Exprs; 9543 for (unsigned i = 0; i != NumComponents; ++i) { 9544 const OffsetOfComponent &OC = CompPtr[i]; 9545 if (OC.isBrackets) { 9546 // Offset of an array sub-field. TODO: Should we allow vector elements? 9547 if (!CurrentType->isDependentType()) { 9548 const ArrayType *AT = Context.getAsArrayType(CurrentType); 9549 if(!AT) 9550 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 9551 << CurrentType); 9552 CurrentType = AT->getElementType(); 9553 } else 9554 CurrentType = Context.DependentTy; 9555 9556 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 9557 if (IdxRval.isInvalid()) 9558 return ExprError(); 9559 Expr *Idx = IdxRval.take(); 9560 9561 // The expression must be an integral expression. 9562 // FIXME: An integral constant expression? 9563 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 9564 !Idx->getType()->isIntegerType()) 9565 return ExprError(Diag(Idx->getLocStart(), 9566 diag::err_typecheck_subscript_not_integer) 9567 << Idx->getSourceRange()); 9568 9569 // Record this array index. 9570 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 9571 Exprs.push_back(Idx); 9572 continue; 9573 } 9574 9575 // Offset of a field. 9576 if (CurrentType->isDependentType()) { 9577 // We have the offset of a field, but we can't look into the dependent 9578 // type. Just record the identifier of the field. 9579 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 9580 CurrentType = Context.DependentTy; 9581 continue; 9582 } 9583 9584 // We need to have a complete type to look into. 9585 if (RequireCompleteType(OC.LocStart, CurrentType, 9586 diag::err_offsetof_incomplete_type)) 9587 return ExprError(); 9588 9589 // Look for the designated field. 9590 const RecordType *RC = CurrentType->getAs<RecordType>(); 9591 if (!RC) 9592 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 9593 << CurrentType); 9594 RecordDecl *RD = RC->getDecl(); 9595 9596 // C++ [lib.support.types]p5: 9597 // The macro offsetof accepts a restricted set of type arguments in this 9598 // International Standard. type shall be a POD structure or a POD union 9599 // (clause 9). 9600 // C++11 [support.types]p4: 9601 // If type is not a standard-layout class (Clause 9), the results are 9602 // undefined. 9603 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 9604 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 9605 unsigned DiagID = 9606 LangOpts.CPlusPlus11? diag::warn_offsetof_non_standardlayout_type 9607 : diag::warn_offsetof_non_pod_type; 9608 9609 if (!IsSafe && !DidWarnAboutNonPOD && 9610 DiagRuntimeBehavior(BuiltinLoc, 0, 9611 PDiag(DiagID) 9612 << SourceRange(CompPtr[0].LocStart, OC.LocEnd) 9613 << CurrentType)) 9614 DidWarnAboutNonPOD = true; 9615 } 9616 9617 // Look for the field. 9618 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 9619 LookupQualifiedName(R, RD); 9620 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 9621 IndirectFieldDecl *IndirectMemberDecl = 0; 9622 if (!MemberDecl) { 9623 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 9624 MemberDecl = IndirectMemberDecl->getAnonField(); 9625 } 9626 9627 if (!MemberDecl) 9628 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 9629 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 9630 OC.LocEnd)); 9631 9632 // C99 7.17p3: 9633 // (If the specified member is a bit-field, the behavior is undefined.) 9634 // 9635 // We diagnose this as an error. 9636 if (MemberDecl->isBitField()) { 9637 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 9638 << MemberDecl->getDeclName() 9639 << SourceRange(BuiltinLoc, RParenLoc); 9640 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 9641 return ExprError(); 9642 } 9643 9644 RecordDecl *Parent = MemberDecl->getParent(); 9645 if (IndirectMemberDecl) 9646 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 9647 9648 // If the member was found in a base class, introduce OffsetOfNodes for 9649 // the base class indirections. 9650 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 9651 /*DetectVirtual=*/false); 9652 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) { 9653 CXXBasePath &Path = Paths.front(); 9654 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end(); 9655 B != BEnd; ++B) 9656 Comps.push_back(OffsetOfNode(B->Base)); 9657 } 9658 9659 if (IndirectMemberDecl) { 9660 for (IndirectFieldDecl::chain_iterator FI = 9661 IndirectMemberDecl->chain_begin(), 9662 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) { 9663 assert(isa<FieldDecl>(*FI)); 9664 Comps.push_back(OffsetOfNode(OC.LocStart, 9665 cast<FieldDecl>(*FI), OC.LocEnd)); 9666 } 9667 } else 9668 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 9669 9670 CurrentType = MemberDecl->getType().getNonReferenceType(); 9671 } 9672 9673 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, 9674 TInfo, Comps, Exprs, RParenLoc)); 9675 } 9676 9677 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 9678 SourceLocation BuiltinLoc, 9679 SourceLocation TypeLoc, 9680 ParsedType ParsedArgTy, 9681 OffsetOfComponent *CompPtr, 9682 unsigned NumComponents, 9683 SourceLocation RParenLoc) { 9684 9685 TypeSourceInfo *ArgTInfo; 9686 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 9687 if (ArgTy.isNull()) 9688 return ExprError(); 9689 9690 if (!ArgTInfo) 9691 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 9692 9693 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents, 9694 RParenLoc); 9695 } 9696 9697 9698 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 9699 Expr *CondExpr, 9700 Expr *LHSExpr, Expr *RHSExpr, 9701 SourceLocation RPLoc) { 9702 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 9703 9704 ExprValueKind VK = VK_RValue; 9705 ExprObjectKind OK = OK_Ordinary; 9706 QualType resType; 9707 bool ValueDependent = false; 9708 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 9709 resType = Context.DependentTy; 9710 ValueDependent = true; 9711 } else { 9712 // The conditional expression is required to be a constant expression. 9713 llvm::APSInt condEval(32); 9714 ExprResult CondICE 9715 = VerifyIntegerConstantExpression(CondExpr, &condEval, 9716 diag::err_typecheck_choose_expr_requires_constant, false); 9717 if (CondICE.isInvalid()) 9718 return ExprError(); 9719 CondExpr = CondICE.take(); 9720 9721 // If the condition is > zero, then the AST type is the same as the LSHExpr. 9722 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr; 9723 9724 resType = ActiveExpr->getType(); 9725 ValueDependent = ActiveExpr->isValueDependent(); 9726 VK = ActiveExpr->getValueKind(); 9727 OK = ActiveExpr->getObjectKind(); 9728 } 9729 9730 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 9731 resType, VK, OK, RPLoc, 9732 resType->isDependentType(), 9733 ValueDependent)); 9734 } 9735 9736 //===----------------------------------------------------------------------===// 9737 // Clang Extensions. 9738 //===----------------------------------------------------------------------===// 9739 9740 /// ActOnBlockStart - This callback is invoked when a block literal is started. 9741 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 9742 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 9743 PushBlockScope(CurScope, Block); 9744 CurContext->addDecl(Block); 9745 if (CurScope) 9746 PushDeclContext(CurScope, Block); 9747 else 9748 CurContext = Block; 9749 9750 getCurBlock()->HasImplicitReturnType = true; 9751 9752 // Enter a new evaluation context to insulate the block from any 9753 // cleanups from the enclosing full-expression. 9754 PushExpressionEvaluationContext(PotentiallyEvaluated); 9755 } 9756 9757 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 9758 Scope *CurScope) { 9759 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!"); 9760 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 9761 BlockScopeInfo *CurBlock = getCurBlock(); 9762 9763 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 9764 QualType T = Sig->getType(); 9765 9766 // FIXME: We should allow unexpanded parameter packs here, but that would, 9767 // in turn, make the block expression contain unexpanded parameter packs. 9768 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 9769 // Drop the parameters. 9770 FunctionProtoType::ExtProtoInfo EPI; 9771 EPI.HasTrailingReturn = false; 9772 EPI.TypeQuals |= DeclSpec::TQ_const; 9773 T = Context.getFunctionType(Context.DependentTy, None, EPI); 9774 Sig = Context.getTrivialTypeSourceInfo(T); 9775 } 9776 9777 // GetTypeForDeclarator always produces a function type for a block 9778 // literal signature. Furthermore, it is always a FunctionProtoType 9779 // unless the function was written with a typedef. 9780 assert(T->isFunctionType() && 9781 "GetTypeForDeclarator made a non-function block signature"); 9782 9783 // Look for an explicit signature in that function type. 9784 FunctionProtoTypeLoc ExplicitSignature; 9785 9786 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 9787 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 9788 9789 // Check whether that explicit signature was synthesized by 9790 // GetTypeForDeclarator. If so, don't save that as part of the 9791 // written signature. 9792 if (ExplicitSignature.getLocalRangeBegin() == 9793 ExplicitSignature.getLocalRangeEnd()) { 9794 // This would be much cheaper if we stored TypeLocs instead of 9795 // TypeSourceInfos. 9796 TypeLoc Result = ExplicitSignature.getResultLoc(); 9797 unsigned Size = Result.getFullDataSize(); 9798 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 9799 Sig->getTypeLoc().initializeFullCopy(Result, Size); 9800 9801 ExplicitSignature = FunctionProtoTypeLoc(); 9802 } 9803 } 9804 9805 CurBlock->TheDecl->setSignatureAsWritten(Sig); 9806 CurBlock->FunctionType = T; 9807 9808 const FunctionType *Fn = T->getAs<FunctionType>(); 9809 QualType RetTy = Fn->getResultType(); 9810 bool isVariadic = 9811 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 9812 9813 CurBlock->TheDecl->setIsVariadic(isVariadic); 9814 9815 // Don't allow returning a objc interface by value. 9816 if (RetTy->isObjCObjectType()) { 9817 Diag(ParamInfo.getLocStart(), 9818 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy; 9819 return; 9820 } 9821 9822 // Context.DependentTy is used as a placeholder for a missing block 9823 // return type. TODO: what should we do with declarators like: 9824 // ^ * { ... } 9825 // If the answer is "apply template argument deduction".... 9826 if (RetTy != Context.DependentTy) { 9827 CurBlock->ReturnType = RetTy; 9828 CurBlock->TheDecl->setBlockMissingReturnType(false); 9829 CurBlock->HasImplicitReturnType = false; 9830 } 9831 9832 // Push block parameters from the declarator if we had them. 9833 SmallVector<ParmVarDecl*, 8> Params; 9834 if (ExplicitSignature) { 9835 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) { 9836 ParmVarDecl *Param = ExplicitSignature.getArg(I); 9837 if (Param->getIdentifier() == 0 && 9838 !Param->isImplicit() && 9839 !Param->isInvalidDecl() && 9840 !getLangOpts().CPlusPlus) 9841 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 9842 Params.push_back(Param); 9843 } 9844 9845 // Fake up parameter variables if we have a typedef, like 9846 // ^ fntype { ... } 9847 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 9848 for (FunctionProtoType::arg_type_iterator 9849 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) { 9850 ParmVarDecl *Param = 9851 BuildParmVarDeclForTypedef(CurBlock->TheDecl, 9852 ParamInfo.getLocStart(), 9853 *I); 9854 Params.push_back(Param); 9855 } 9856 } 9857 9858 // Set the parameters on the block decl. 9859 if (!Params.empty()) { 9860 CurBlock->TheDecl->setParams(Params); 9861 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(), 9862 CurBlock->TheDecl->param_end(), 9863 /*CheckParameterNames=*/false); 9864 } 9865 9866 // Finally we can process decl attributes. 9867 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 9868 9869 // Put the parameter variables in scope. We can bail out immediately 9870 // if we don't have any. 9871 if (Params.empty()) 9872 return; 9873 9874 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(), 9875 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) { 9876 (*AI)->setOwningFunction(CurBlock->TheDecl); 9877 9878 // If this has an identifier, add it to the scope stack. 9879 if ((*AI)->getIdentifier()) { 9880 CheckShadow(CurBlock->TheScope, *AI); 9881 9882 PushOnScopeChains(*AI, CurBlock->TheScope); 9883 } 9884 } 9885 } 9886 9887 /// ActOnBlockError - If there is an error parsing a block, this callback 9888 /// is invoked to pop the information about the block from the action impl. 9889 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 9890 // Leave the expression-evaluation context. 9891 DiscardCleanupsInEvaluationContext(); 9892 PopExpressionEvaluationContext(); 9893 9894 // Pop off CurBlock, handle nested blocks. 9895 PopDeclContext(); 9896 PopFunctionScopeInfo(); 9897 } 9898 9899 /// ActOnBlockStmtExpr - This is called when the body of a block statement 9900 /// literal was successfully completed. ^(int x){...} 9901 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 9902 Stmt *Body, Scope *CurScope) { 9903 // If blocks are disabled, emit an error. 9904 if (!LangOpts.Blocks) 9905 Diag(CaretLoc, diag::err_blocks_disable); 9906 9907 // Leave the expression-evaluation context. 9908 if (hasAnyUnrecoverableErrorsInThisFunction()) 9909 DiscardCleanupsInEvaluationContext(); 9910 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!"); 9911 PopExpressionEvaluationContext(); 9912 9913 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 9914 9915 if (BSI->HasImplicitReturnType) 9916 deduceClosureReturnType(*BSI); 9917 9918 PopDeclContext(); 9919 9920 QualType RetTy = Context.VoidTy; 9921 if (!BSI->ReturnType.isNull()) 9922 RetTy = BSI->ReturnType; 9923 9924 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>(); 9925 QualType BlockTy; 9926 9927 // Set the captured variables on the block. 9928 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 9929 SmallVector<BlockDecl::Capture, 4> Captures; 9930 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) { 9931 CapturingScopeInfo::Capture &Cap = BSI->Captures[i]; 9932 if (Cap.isThisCapture()) 9933 continue; 9934 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 9935 Cap.isNested(), Cap.getCopyExpr()); 9936 Captures.push_back(NewCap); 9937 } 9938 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(), 9939 BSI->CXXThisCaptureIndex != 0); 9940 9941 // If the user wrote a function type in some form, try to use that. 9942 if (!BSI->FunctionType.isNull()) { 9943 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 9944 9945 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 9946 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 9947 9948 // Turn protoless block types into nullary block types. 9949 if (isa<FunctionNoProtoType>(FTy)) { 9950 FunctionProtoType::ExtProtoInfo EPI; 9951 EPI.ExtInfo = Ext; 9952 BlockTy = Context.getFunctionType(RetTy, None, EPI); 9953 9954 // Otherwise, if we don't need to change anything about the function type, 9955 // preserve its sugar structure. 9956 } else if (FTy->getResultType() == RetTy && 9957 (!NoReturn || FTy->getNoReturnAttr())) { 9958 BlockTy = BSI->FunctionType; 9959 9960 // Otherwise, make the minimal modifications to the function type. 9961 } else { 9962 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 9963 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9964 EPI.TypeQuals = 0; // FIXME: silently? 9965 EPI.ExtInfo = Ext; 9966 BlockTy = 9967 Context.getFunctionType(RetTy, 9968 ArrayRef<QualType>(FPT->arg_type_begin(), 9969 FPT->getNumArgs()), 9970 EPI); 9971 } 9972 9973 // If we don't have a function type, just build one from nothing. 9974 } else { 9975 FunctionProtoType::ExtProtoInfo EPI; 9976 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 9977 BlockTy = Context.getFunctionType(RetTy, None, EPI); 9978 } 9979 9980 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(), 9981 BSI->TheDecl->param_end()); 9982 BlockTy = Context.getBlockPointerType(BlockTy); 9983 9984 // If needed, diagnose invalid gotos and switches in the block. 9985 if (getCurFunction()->NeedsScopeChecking() && 9986 !hasAnyUnrecoverableErrorsInThisFunction() && 9987 !PP.isCodeCompletionEnabled()) 9988 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 9989 9990 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 9991 9992 // Try to apply the named return value optimization. We have to check again 9993 // if we can do this, though, because blocks keep return statements around 9994 // to deduce an implicit return type. 9995 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 9996 !BSI->TheDecl->isDependentContext()) 9997 computeNRVO(Body, getCurBlock()); 9998 9999 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 10000 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy(); 10001 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 10002 10003 // If the block isn't obviously global, i.e. it captures anything at 10004 // all, then we need to do a few things in the surrounding context: 10005 if (Result->getBlockDecl()->hasCaptures()) { 10006 // First, this expression has a new cleanup object. 10007 ExprCleanupObjects.push_back(Result->getBlockDecl()); 10008 ExprNeedsCleanups = true; 10009 10010 // It also gets a branch-protected scope if any of the captured 10011 // variables needs destruction. 10012 for (BlockDecl::capture_const_iterator 10013 ci = Result->getBlockDecl()->capture_begin(), 10014 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) { 10015 const VarDecl *var = ci->getVariable(); 10016 if (var->getType().isDestructedType() != QualType::DK_none) { 10017 getCurFunction()->setHasBranchProtectedScope(); 10018 break; 10019 } 10020 } 10021 } 10022 10023 return Owned(Result); 10024 } 10025 10026 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 10027 Expr *E, ParsedType Ty, 10028 SourceLocation RPLoc) { 10029 TypeSourceInfo *TInfo; 10030 GetTypeFromParser(Ty, &TInfo); 10031 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 10032 } 10033 10034 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 10035 Expr *E, TypeSourceInfo *TInfo, 10036 SourceLocation RPLoc) { 10037 Expr *OrigExpr = E; 10038 10039 // Get the va_list type 10040 QualType VaListType = Context.getBuiltinVaListType(); 10041 if (VaListType->isArrayType()) { 10042 // Deal with implicit array decay; for example, on x86-64, 10043 // va_list is an array, but it's supposed to decay to 10044 // a pointer for va_arg. 10045 VaListType = Context.getArrayDecayedType(VaListType); 10046 // Make sure the input expression also decays appropriately. 10047 ExprResult Result = UsualUnaryConversions(E); 10048 if (Result.isInvalid()) 10049 return ExprError(); 10050 E = Result.take(); 10051 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 10052 // If va_list is a record type and we are compiling in C++ mode, 10053 // check the argument using reference binding. 10054 InitializedEntity Entity 10055 = InitializedEntity::InitializeParameter(Context, 10056 Context.getLValueReferenceType(VaListType), false); 10057 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 10058 if (Init.isInvalid()) 10059 return ExprError(); 10060 E = Init.takeAs<Expr>(); 10061 } else { 10062 // Otherwise, the va_list argument must be an l-value because 10063 // it is modified by va_arg. 10064 if (!E->isTypeDependent() && 10065 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 10066 return ExprError(); 10067 } 10068 10069 if (!E->isTypeDependent() && 10070 !Context.hasSameType(VaListType, E->getType())) { 10071 return ExprError(Diag(E->getLocStart(), 10072 diag::err_first_argument_to_va_arg_not_of_type_va_list) 10073 << OrigExpr->getType() << E->getSourceRange()); 10074 } 10075 10076 if (!TInfo->getType()->isDependentType()) { 10077 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 10078 diag::err_second_parameter_to_va_arg_incomplete, 10079 TInfo->getTypeLoc())) 10080 return ExprError(); 10081 10082 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 10083 TInfo->getType(), 10084 diag::err_second_parameter_to_va_arg_abstract, 10085 TInfo->getTypeLoc())) 10086 return ExprError(); 10087 10088 if (!TInfo->getType().isPODType(Context)) { 10089 Diag(TInfo->getTypeLoc().getBeginLoc(), 10090 TInfo->getType()->isObjCLifetimeType() 10091 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 10092 : diag::warn_second_parameter_to_va_arg_not_pod) 10093 << TInfo->getType() 10094 << TInfo->getTypeLoc().getSourceRange(); 10095 } 10096 10097 // Check for va_arg where arguments of the given type will be promoted 10098 // (i.e. this va_arg is guaranteed to have undefined behavior). 10099 QualType PromoteType; 10100 if (TInfo->getType()->isPromotableIntegerType()) { 10101 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 10102 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 10103 PromoteType = QualType(); 10104 } 10105 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 10106 PromoteType = Context.DoubleTy; 10107 if (!PromoteType.isNull()) 10108 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 10109 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 10110 << TInfo->getType() 10111 << PromoteType 10112 << TInfo->getTypeLoc().getSourceRange()); 10113 } 10114 10115 QualType T = TInfo->getType().getNonLValueExprType(Context); 10116 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T)); 10117 } 10118 10119 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 10120 // The type of __null will be int or long, depending on the size of 10121 // pointers on the target. 10122 QualType Ty; 10123 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 10124 if (pw == Context.getTargetInfo().getIntWidth()) 10125 Ty = Context.IntTy; 10126 else if (pw == Context.getTargetInfo().getLongWidth()) 10127 Ty = Context.LongTy; 10128 else if (pw == Context.getTargetInfo().getLongLongWidth()) 10129 Ty = Context.LongLongTy; 10130 else { 10131 llvm_unreachable("I don't know size of pointer!"); 10132 } 10133 10134 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc)); 10135 } 10136 10137 static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType, 10138 Expr *SrcExpr, FixItHint &Hint) { 10139 if (!SemaRef.getLangOpts().ObjC1) 10140 return; 10141 10142 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 10143 if (!PT) 10144 return; 10145 10146 // Check if the destination is of type 'id'. 10147 if (!PT->isObjCIdType()) { 10148 // Check if the destination is the 'NSString' interface. 10149 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 10150 if (!ID || !ID->getIdentifier()->isStr("NSString")) 10151 return; 10152 } 10153 10154 // Ignore any parens, implicit casts (should only be 10155 // array-to-pointer decays), and not-so-opaque values. The last is 10156 // important for making this trigger for property assignments. 10157 SrcExpr = SrcExpr->IgnoreParenImpCasts(); 10158 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 10159 if (OV->getSourceExpr()) 10160 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 10161 10162 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 10163 if (!SL || !SL->isAscii()) 10164 return; 10165 10166 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@"); 10167 } 10168 10169 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 10170 SourceLocation Loc, 10171 QualType DstType, QualType SrcType, 10172 Expr *SrcExpr, AssignmentAction Action, 10173 bool *Complained) { 10174 if (Complained) 10175 *Complained = false; 10176 10177 // Decode the result (notice that AST's are still created for extensions). 10178 bool CheckInferredResultType = false; 10179 bool isInvalid = false; 10180 unsigned DiagKind = 0; 10181 FixItHint Hint; 10182 ConversionFixItGenerator ConvHints; 10183 bool MayHaveConvFixit = false; 10184 bool MayHaveFunctionDiff = false; 10185 10186 switch (ConvTy) { 10187 case Compatible: 10188 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 10189 return false; 10190 10191 case PointerToInt: 10192 DiagKind = diag::ext_typecheck_convert_pointer_int; 10193 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10194 MayHaveConvFixit = true; 10195 break; 10196 case IntToPointer: 10197 DiagKind = diag::ext_typecheck_convert_int_pointer; 10198 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10199 MayHaveConvFixit = true; 10200 break; 10201 case IncompatiblePointer: 10202 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint); 10203 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 10204 CheckInferredResultType = DstType->isObjCObjectPointerType() && 10205 SrcType->isObjCObjectPointerType(); 10206 if (Hint.isNull() && !CheckInferredResultType) { 10207 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10208 } 10209 else if (CheckInferredResultType) { 10210 SrcType = SrcType.getUnqualifiedType(); 10211 DstType = DstType.getUnqualifiedType(); 10212 } 10213 MayHaveConvFixit = true; 10214 break; 10215 case IncompatiblePointerSign: 10216 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 10217 break; 10218 case FunctionVoidPointer: 10219 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 10220 break; 10221 case IncompatiblePointerDiscardsQualifiers: { 10222 // Perform array-to-pointer decay if necessary. 10223 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 10224 10225 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 10226 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 10227 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 10228 DiagKind = diag::err_typecheck_incompatible_address_space; 10229 break; 10230 10231 10232 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 10233 DiagKind = diag::err_typecheck_incompatible_ownership; 10234 break; 10235 } 10236 10237 llvm_unreachable("unknown error case for discarding qualifiers!"); 10238 // fallthrough 10239 } 10240 case CompatiblePointerDiscardsQualifiers: 10241 // If the qualifiers lost were because we were applying the 10242 // (deprecated) C++ conversion from a string literal to a char* 10243 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 10244 // Ideally, this check would be performed in 10245 // checkPointerTypesForAssignment. However, that would require a 10246 // bit of refactoring (so that the second argument is an 10247 // expression, rather than a type), which should be done as part 10248 // of a larger effort to fix checkPointerTypesForAssignment for 10249 // C++ semantics. 10250 if (getLangOpts().CPlusPlus && 10251 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 10252 return false; 10253 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 10254 break; 10255 case IncompatibleNestedPointerQualifiers: 10256 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 10257 break; 10258 case IntToBlockPointer: 10259 DiagKind = diag::err_int_to_block_pointer; 10260 break; 10261 case IncompatibleBlockPointer: 10262 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 10263 break; 10264 case IncompatibleObjCQualifiedId: 10265 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since 10266 // it can give a more specific diagnostic. 10267 DiagKind = diag::warn_incompatible_qualified_id; 10268 break; 10269 case IncompatibleVectors: 10270 DiagKind = diag::warn_incompatible_vectors; 10271 break; 10272 case IncompatibleObjCWeakRef: 10273 DiagKind = diag::err_arc_weak_unavailable_assign; 10274 break; 10275 case Incompatible: 10276 DiagKind = diag::err_typecheck_convert_incompatible; 10277 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10278 MayHaveConvFixit = true; 10279 isInvalid = true; 10280 MayHaveFunctionDiff = true; 10281 break; 10282 } 10283 10284 QualType FirstType, SecondType; 10285 switch (Action) { 10286 case AA_Assigning: 10287 case AA_Initializing: 10288 // The destination type comes first. 10289 FirstType = DstType; 10290 SecondType = SrcType; 10291 break; 10292 10293 case AA_Returning: 10294 case AA_Passing: 10295 case AA_Converting: 10296 case AA_Sending: 10297 case AA_Casting: 10298 // The source type comes first. 10299 FirstType = SrcType; 10300 SecondType = DstType; 10301 break; 10302 } 10303 10304 PartialDiagnostic FDiag = PDiag(DiagKind); 10305 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 10306 10307 // If we can fix the conversion, suggest the FixIts. 10308 assert(ConvHints.isNull() || Hint.isNull()); 10309 if (!ConvHints.isNull()) { 10310 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(), 10311 HE = ConvHints.Hints.end(); HI != HE; ++HI) 10312 FDiag << *HI; 10313 } else { 10314 FDiag << Hint; 10315 } 10316 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 10317 10318 if (MayHaveFunctionDiff) 10319 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 10320 10321 Diag(Loc, FDiag); 10322 10323 if (SecondType == Context.OverloadTy) 10324 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 10325 FirstType); 10326 10327 if (CheckInferredResultType) 10328 EmitRelatedResultTypeNote(SrcExpr); 10329 10330 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 10331 EmitRelatedResultTypeNoteForReturn(DstType); 10332 10333 if (Complained) 10334 *Complained = true; 10335 return isInvalid; 10336 } 10337 10338 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 10339 llvm::APSInt *Result) { 10340 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 10341 public: 10342 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 10343 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 10344 } 10345 } Diagnoser; 10346 10347 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 10348 } 10349 10350 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 10351 llvm::APSInt *Result, 10352 unsigned DiagID, 10353 bool AllowFold) { 10354 class IDDiagnoser : public VerifyICEDiagnoser { 10355 unsigned DiagID; 10356 10357 public: 10358 IDDiagnoser(unsigned DiagID) 10359 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 10360 10361 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 10362 S.Diag(Loc, DiagID) << SR; 10363 } 10364 } Diagnoser(DiagID); 10365 10366 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 10367 } 10368 10369 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 10370 SourceRange SR) { 10371 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 10372 } 10373 10374 ExprResult 10375 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 10376 VerifyICEDiagnoser &Diagnoser, 10377 bool AllowFold) { 10378 SourceLocation DiagLoc = E->getLocStart(); 10379 10380 if (getLangOpts().CPlusPlus11) { 10381 // C++11 [expr.const]p5: 10382 // If an expression of literal class type is used in a context where an 10383 // integral constant expression is required, then that class type shall 10384 // have a single non-explicit conversion function to an integral or 10385 // unscoped enumeration type 10386 ExprResult Converted; 10387 if (!Diagnoser.Suppress) { 10388 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 10389 public: 10390 CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { } 10391 10392 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 10393 QualType T) { 10394 return S.Diag(Loc, diag::err_ice_not_integral) << T; 10395 } 10396 10397 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, 10398 SourceLocation Loc, 10399 QualType T) { 10400 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 10401 } 10402 10403 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, 10404 SourceLocation Loc, 10405 QualType T, 10406 QualType ConvTy) { 10407 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 10408 } 10409 10410 virtual DiagnosticBuilder noteExplicitConv(Sema &S, 10411 CXXConversionDecl *Conv, 10412 QualType ConvTy) { 10413 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 10414 << ConvTy->isEnumeralType() << ConvTy; 10415 } 10416 10417 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 10418 QualType T) { 10419 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 10420 } 10421 10422 virtual DiagnosticBuilder noteAmbiguous(Sema &S, 10423 CXXConversionDecl *Conv, 10424 QualType ConvTy) { 10425 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 10426 << ConvTy->isEnumeralType() << ConvTy; 10427 } 10428 10429 virtual DiagnosticBuilder diagnoseConversion(Sema &S, 10430 SourceLocation Loc, 10431 QualType T, 10432 QualType ConvTy) { 10433 return DiagnosticBuilder::getEmpty(); 10434 } 10435 } ConvertDiagnoser; 10436 10437 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E, 10438 ConvertDiagnoser, 10439 /*AllowScopedEnumerations*/ false); 10440 } else { 10441 // The caller wants to silently enquire whether this is an ICE. Don't 10442 // produce any diagnostics if it isn't. 10443 class SilentICEConvertDiagnoser : public ICEConvertDiagnoser { 10444 public: 10445 SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { } 10446 10447 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 10448 QualType T) { 10449 return DiagnosticBuilder::getEmpty(); 10450 } 10451 10452 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, 10453 SourceLocation Loc, 10454 QualType T) { 10455 return DiagnosticBuilder::getEmpty(); 10456 } 10457 10458 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, 10459 SourceLocation Loc, 10460 QualType T, 10461 QualType ConvTy) { 10462 return DiagnosticBuilder::getEmpty(); 10463 } 10464 10465 virtual DiagnosticBuilder noteExplicitConv(Sema &S, 10466 CXXConversionDecl *Conv, 10467 QualType ConvTy) { 10468 return DiagnosticBuilder::getEmpty(); 10469 } 10470 10471 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 10472 QualType T) { 10473 return DiagnosticBuilder::getEmpty(); 10474 } 10475 10476 virtual DiagnosticBuilder noteAmbiguous(Sema &S, 10477 CXXConversionDecl *Conv, 10478 QualType ConvTy) { 10479 return DiagnosticBuilder::getEmpty(); 10480 } 10481 10482 virtual DiagnosticBuilder diagnoseConversion(Sema &S, 10483 SourceLocation Loc, 10484 QualType T, 10485 QualType ConvTy) { 10486 return DiagnosticBuilder::getEmpty(); 10487 } 10488 } ConvertDiagnoser; 10489 10490 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E, 10491 ConvertDiagnoser, false); 10492 } 10493 if (Converted.isInvalid()) 10494 return Converted; 10495 E = Converted.take(); 10496 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 10497 return ExprError(); 10498 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 10499 // An ICE must be of integral or unscoped enumeration type. 10500 if (!Diagnoser.Suppress) 10501 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 10502 return ExprError(); 10503 } 10504 10505 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 10506 // in the non-ICE case. 10507 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 10508 if (Result) 10509 *Result = E->EvaluateKnownConstInt(Context); 10510 return Owned(E); 10511 } 10512 10513 Expr::EvalResult EvalResult; 10514 SmallVector<PartialDiagnosticAt, 8> Notes; 10515 EvalResult.Diag = &Notes; 10516 10517 // Try to evaluate the expression, and produce diagnostics explaining why it's 10518 // not a constant expression as a side-effect. 10519 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 10520 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 10521 10522 // In C++11, we can rely on diagnostics being produced for any expression 10523 // which is not a constant expression. If no diagnostics were produced, then 10524 // this is a constant expression. 10525 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 10526 if (Result) 10527 *Result = EvalResult.Val.getInt(); 10528 return Owned(E); 10529 } 10530 10531 // If our only note is the usual "invalid subexpression" note, just point 10532 // the caret at its location rather than producing an essentially 10533 // redundant note. 10534 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 10535 diag::note_invalid_subexpr_in_const_expr) { 10536 DiagLoc = Notes[0].first; 10537 Notes.clear(); 10538 } 10539 10540 if (!Folded || !AllowFold) { 10541 if (!Diagnoser.Suppress) { 10542 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 10543 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 10544 Diag(Notes[I].first, Notes[I].second); 10545 } 10546 10547 return ExprError(); 10548 } 10549 10550 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 10551 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 10552 Diag(Notes[I].first, Notes[I].second); 10553 10554 if (Result) 10555 *Result = EvalResult.Val.getInt(); 10556 return Owned(E); 10557 } 10558 10559 namespace { 10560 // Handle the case where we conclude a expression which we speculatively 10561 // considered to be unevaluated is actually evaluated. 10562 class TransformToPE : public TreeTransform<TransformToPE> { 10563 typedef TreeTransform<TransformToPE> BaseTransform; 10564 10565 public: 10566 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 10567 10568 // Make sure we redo semantic analysis 10569 bool AlwaysRebuild() { return true; } 10570 10571 // Make sure we handle LabelStmts correctly. 10572 // FIXME: This does the right thing, but maybe we need a more general 10573 // fix to TreeTransform? 10574 StmtResult TransformLabelStmt(LabelStmt *S) { 10575 S->getDecl()->setStmt(0); 10576 return BaseTransform::TransformLabelStmt(S); 10577 } 10578 10579 // We need to special-case DeclRefExprs referring to FieldDecls which 10580 // are not part of a member pointer formation; normal TreeTransforming 10581 // doesn't catch this case because of the way we represent them in the AST. 10582 // FIXME: This is a bit ugly; is it really the best way to handle this 10583 // case? 10584 // 10585 // Error on DeclRefExprs referring to FieldDecls. 10586 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 10587 if (isa<FieldDecl>(E->getDecl()) && 10588 !SemaRef.isUnevaluatedContext()) 10589 return SemaRef.Diag(E->getLocation(), 10590 diag::err_invalid_non_static_member_use) 10591 << E->getDecl() << E->getSourceRange(); 10592 10593 return BaseTransform::TransformDeclRefExpr(E); 10594 } 10595 10596 // Exception: filter out member pointer formation 10597 ExprResult TransformUnaryOperator(UnaryOperator *E) { 10598 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 10599 return E; 10600 10601 return BaseTransform::TransformUnaryOperator(E); 10602 } 10603 10604 ExprResult TransformLambdaExpr(LambdaExpr *E) { 10605 // Lambdas never need to be transformed. 10606 return E; 10607 } 10608 }; 10609 } 10610 10611 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 10612 assert(isUnevaluatedContext() && 10613 "Should only transform unevaluated expressions"); 10614 ExprEvalContexts.back().Context = 10615 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 10616 if (isUnevaluatedContext()) 10617 return E; 10618 return TransformToPE(*this).TransformExpr(E); 10619 } 10620 10621 void 10622 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 10623 Decl *LambdaContextDecl, 10624 bool IsDecltype) { 10625 ExprEvalContexts.push_back( 10626 ExpressionEvaluationContextRecord(NewContext, 10627 ExprCleanupObjects.size(), 10628 ExprNeedsCleanups, 10629 LambdaContextDecl, 10630 IsDecltype)); 10631 ExprNeedsCleanups = false; 10632 if (!MaybeODRUseExprs.empty()) 10633 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 10634 } 10635 10636 void 10637 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 10638 ReuseLambdaContextDecl_t, 10639 bool IsDecltype) { 10640 Decl *LambdaContextDecl = ExprEvalContexts.back().LambdaContextDecl; 10641 PushExpressionEvaluationContext(NewContext, LambdaContextDecl, IsDecltype); 10642 } 10643 10644 void Sema::PopExpressionEvaluationContext() { 10645 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 10646 10647 if (!Rec.Lambdas.empty()) { 10648 if (Rec.isUnevaluated()) { 10649 // C++11 [expr.prim.lambda]p2: 10650 // A lambda-expression shall not appear in an unevaluated operand 10651 // (Clause 5). 10652 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) 10653 Diag(Rec.Lambdas[I]->getLocStart(), 10654 diag::err_lambda_unevaluated_operand); 10655 } else { 10656 // Mark the capture expressions odr-used. This was deferred 10657 // during lambda expression creation. 10658 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) { 10659 LambdaExpr *Lambda = Rec.Lambdas[I]; 10660 for (LambdaExpr::capture_init_iterator 10661 C = Lambda->capture_init_begin(), 10662 CEnd = Lambda->capture_init_end(); 10663 C != CEnd; ++C) { 10664 MarkDeclarationsReferencedInExpr(*C); 10665 } 10666 } 10667 } 10668 } 10669 10670 // When are coming out of an unevaluated context, clear out any 10671 // temporaries that we may have created as part of the evaluation of 10672 // the expression in that context: they aren't relevant because they 10673 // will never be constructed. 10674 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 10675 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 10676 ExprCleanupObjects.end()); 10677 ExprNeedsCleanups = Rec.ParentNeedsCleanups; 10678 CleanupVarDeclMarking(); 10679 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 10680 // Otherwise, merge the contexts together. 10681 } else { 10682 ExprNeedsCleanups |= Rec.ParentNeedsCleanups; 10683 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 10684 Rec.SavedMaybeODRUseExprs.end()); 10685 } 10686 10687 // Pop the current expression evaluation context off the stack. 10688 ExprEvalContexts.pop_back(); 10689 } 10690 10691 void Sema::DiscardCleanupsInEvaluationContext() { 10692 ExprCleanupObjects.erase( 10693 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 10694 ExprCleanupObjects.end()); 10695 ExprNeedsCleanups = false; 10696 MaybeODRUseExprs.clear(); 10697 } 10698 10699 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 10700 if (!E->getType()->isVariablyModifiedType()) 10701 return E; 10702 return TransformToPotentiallyEvaluated(E); 10703 } 10704 10705 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 10706 // Do not mark anything as "used" within a dependent context; wait for 10707 // an instantiation. 10708 if (SemaRef.CurContext->isDependentContext()) 10709 return false; 10710 10711 switch (SemaRef.ExprEvalContexts.back().Context) { 10712 case Sema::Unevaluated: 10713 case Sema::UnevaluatedAbstract: 10714 // We are in an expression that is not potentially evaluated; do nothing. 10715 // (Depending on how you read the standard, we actually do need to do 10716 // something here for null pointer constants, but the standard's 10717 // definition of a null pointer constant is completely crazy.) 10718 return false; 10719 10720 case Sema::ConstantEvaluated: 10721 case Sema::PotentiallyEvaluated: 10722 // We are in a potentially evaluated expression (or a constant-expression 10723 // in C++03); we need to do implicit template instantiation, implicitly 10724 // define class members, and mark most declarations as used. 10725 return true; 10726 10727 case Sema::PotentiallyEvaluatedIfUsed: 10728 // Referenced declarations will only be used if the construct in the 10729 // containing expression is used. 10730 return false; 10731 } 10732 llvm_unreachable("Invalid context"); 10733 } 10734 10735 /// \brief Mark a function referenced, and check whether it is odr-used 10736 /// (C++ [basic.def.odr]p2, C99 6.9p3) 10737 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) { 10738 assert(Func && "No function?"); 10739 10740 Func->setReferenced(); 10741 10742 // C++11 [basic.def.odr]p3: 10743 // A function whose name appears as a potentially-evaluated expression is 10744 // odr-used if it is the unique lookup result or the selected member of a 10745 // set of overloaded functions [...]. 10746 // 10747 // We (incorrectly) mark overload resolution as an unevaluated context, so we 10748 // can just check that here. Skip the rest of this function if we've already 10749 // marked the function as used. 10750 if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) { 10751 // C++11 [temp.inst]p3: 10752 // Unless a function template specialization has been explicitly 10753 // instantiated or explicitly specialized, the function template 10754 // specialization is implicitly instantiated when the specialization is 10755 // referenced in a context that requires a function definition to exist. 10756 // 10757 // We consider constexpr function templates to be referenced in a context 10758 // that requires a definition to exist whenever they are referenced. 10759 // 10760 // FIXME: This instantiates constexpr functions too frequently. If this is 10761 // really an unevaluated context (and we're not just in the definition of a 10762 // function template or overload resolution or other cases which we 10763 // incorrectly consider to be unevaluated contexts), and we're not in a 10764 // subexpression which we actually need to evaluate (for instance, a 10765 // template argument, array bound or an expression in a braced-init-list), 10766 // we are not permitted to instantiate this constexpr function definition. 10767 // 10768 // FIXME: This also implicitly defines special members too frequently. They 10769 // are only supposed to be implicitly defined if they are odr-used, but they 10770 // are not odr-used from constant expressions in unevaluated contexts. 10771 // However, they cannot be referenced if they are deleted, and they are 10772 // deleted whenever the implicit definition of the special member would 10773 // fail. 10774 if (!Func->isConstexpr() || Func->getBody()) 10775 return; 10776 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 10777 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided())) 10778 return; 10779 } 10780 10781 // Note that this declaration has been used. 10782 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 10783 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 10784 if (Constructor->isDefaultConstructor()) { 10785 if (Constructor->isTrivial()) 10786 return; 10787 if (!Constructor->isUsed(false)) 10788 DefineImplicitDefaultConstructor(Loc, Constructor); 10789 } else if (Constructor->isCopyConstructor()) { 10790 if (!Constructor->isUsed(false)) 10791 DefineImplicitCopyConstructor(Loc, Constructor); 10792 } else if (Constructor->isMoveConstructor()) { 10793 if (!Constructor->isUsed(false)) 10794 DefineImplicitMoveConstructor(Loc, Constructor); 10795 } 10796 } else if (Constructor->getInheritedConstructor()) { 10797 if (!Constructor->isUsed(false)) 10798 DefineInheritingConstructor(Loc, Constructor); 10799 } 10800 10801 MarkVTableUsed(Loc, Constructor->getParent()); 10802 } else if (CXXDestructorDecl *Destructor = 10803 dyn_cast<CXXDestructorDecl>(Func)) { 10804 if (Destructor->isDefaulted() && !Destructor->isDeleted() && 10805 !Destructor->isUsed(false)) 10806 DefineImplicitDestructor(Loc, Destructor); 10807 if (Destructor->isVirtual()) 10808 MarkVTableUsed(Loc, Destructor->getParent()); 10809 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 10810 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() && 10811 MethodDecl->isOverloadedOperator() && 10812 MethodDecl->getOverloadedOperator() == OO_Equal) { 10813 if (!MethodDecl->isUsed(false)) { 10814 if (MethodDecl->isCopyAssignmentOperator()) 10815 DefineImplicitCopyAssignment(Loc, MethodDecl); 10816 else 10817 DefineImplicitMoveAssignment(Loc, MethodDecl); 10818 } 10819 } else if (isa<CXXConversionDecl>(MethodDecl) && 10820 MethodDecl->getParent()->isLambda()) { 10821 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl); 10822 if (Conversion->isLambdaToBlockPointerConversion()) 10823 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 10824 else 10825 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 10826 } else if (MethodDecl->isVirtual()) 10827 MarkVTableUsed(Loc, MethodDecl->getParent()); 10828 } 10829 10830 // Recursive functions should be marked when used from another function. 10831 // FIXME: Is this really right? 10832 if (CurContext == Func) return; 10833 10834 // Resolve the exception specification for any function which is 10835 // used: CodeGen will need it. 10836 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 10837 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 10838 ResolveExceptionSpec(Loc, FPT); 10839 10840 // Implicit instantiation of function templates and member functions of 10841 // class templates. 10842 if (Func->isImplicitlyInstantiable()) { 10843 bool AlreadyInstantiated = false; 10844 SourceLocation PointOfInstantiation = Loc; 10845 if (FunctionTemplateSpecializationInfo *SpecInfo 10846 = Func->getTemplateSpecializationInfo()) { 10847 if (SpecInfo->getPointOfInstantiation().isInvalid()) 10848 SpecInfo->setPointOfInstantiation(Loc); 10849 else if (SpecInfo->getTemplateSpecializationKind() 10850 == TSK_ImplicitInstantiation) { 10851 AlreadyInstantiated = true; 10852 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 10853 } 10854 } else if (MemberSpecializationInfo *MSInfo 10855 = Func->getMemberSpecializationInfo()) { 10856 if (MSInfo->getPointOfInstantiation().isInvalid()) 10857 MSInfo->setPointOfInstantiation(Loc); 10858 else if (MSInfo->getTemplateSpecializationKind() 10859 == TSK_ImplicitInstantiation) { 10860 AlreadyInstantiated = true; 10861 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 10862 } 10863 } 10864 10865 if (!AlreadyInstantiated || Func->isConstexpr()) { 10866 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 10867 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass()) 10868 PendingLocalImplicitInstantiations.push_back( 10869 std::make_pair(Func, PointOfInstantiation)); 10870 else if (Func->isConstexpr()) 10871 // Do not defer instantiations of constexpr functions, to avoid the 10872 // expression evaluator needing to call back into Sema if it sees a 10873 // call to such a function. 10874 InstantiateFunctionDefinition(PointOfInstantiation, Func); 10875 else { 10876 PendingInstantiations.push_back(std::make_pair(Func, 10877 PointOfInstantiation)); 10878 // Notify the consumer that a function was implicitly instantiated. 10879 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 10880 } 10881 } 10882 } else { 10883 // Walk redefinitions, as some of them may be instantiable. 10884 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()), 10885 e(Func->redecls_end()); i != e; ++i) { 10886 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 10887 MarkFunctionReferenced(Loc, *i); 10888 } 10889 } 10890 10891 // Keep track of used but undefined functions. 10892 if (!Func->isDefined()) { 10893 if (mightHaveNonExternalLinkage(Func)) 10894 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 10895 else if (Func->getMostRecentDecl()->isInlined() && 10896 (LangOpts.CPlusPlus || !LangOpts.GNUInline) && 10897 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 10898 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 10899 } 10900 10901 // Normally the must current decl is marked used while processing the use and 10902 // any subsequent decls are marked used by decl merging. This fails with 10903 // template instantiation since marking can happen at the end of the file 10904 // and, because of the two phase lookup, this function is called with at 10905 // decl in the middle of a decl chain. We loop to maintain the invariant 10906 // that once a decl is used, all decls after it are also used. 10907 for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) { 10908 F->setUsed(true); 10909 if (F == Func) 10910 break; 10911 } 10912 } 10913 10914 static void 10915 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 10916 VarDecl *var, DeclContext *DC) { 10917 DeclContext *VarDC = var->getDeclContext(); 10918 10919 // If the parameter still belongs to the translation unit, then 10920 // we're actually just using one parameter in the declaration of 10921 // the next. 10922 if (isa<ParmVarDecl>(var) && 10923 isa<TranslationUnitDecl>(VarDC)) 10924 return; 10925 10926 // For C code, don't diagnose about capture if we're not actually in code 10927 // right now; it's impossible to write a non-constant expression outside of 10928 // function context, so we'll get other (more useful) diagnostics later. 10929 // 10930 // For C++, things get a bit more nasty... it would be nice to suppress this 10931 // diagnostic for certain cases like using a local variable in an array bound 10932 // for a member of a local class, but the correct predicate is not obvious. 10933 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 10934 return; 10935 10936 if (isa<CXXMethodDecl>(VarDC) && 10937 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 10938 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda) 10939 << var->getIdentifier(); 10940 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) { 10941 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 10942 << var->getIdentifier() << fn->getDeclName(); 10943 } else if (isa<BlockDecl>(VarDC)) { 10944 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block) 10945 << var->getIdentifier(); 10946 } else { 10947 // FIXME: Is there any other context where a local variable can be 10948 // declared? 10949 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context) 10950 << var->getIdentifier(); 10951 } 10952 10953 S.Diag(var->getLocation(), diag::note_local_variable_declared_here) 10954 << var->getIdentifier(); 10955 10956 // FIXME: Add additional diagnostic info about class etc. which prevents 10957 // capture. 10958 } 10959 10960 /// \brief Capture the given variable in the captured region. 10961 static ExprResult captureInCapturedRegion(Sema &S, CapturedRegionScopeInfo *RSI, 10962 VarDecl *Var, QualType FieldType, 10963 QualType DeclRefType, 10964 SourceLocation Loc, 10965 bool RefersToEnclosingLocal) { 10966 // The current implemention assumes that all variables are captured 10967 // by references. Since there is no capture by copy, no expression evaluation 10968 // will be needed. 10969 // 10970 RecordDecl *RD = RSI->TheRecordDecl; 10971 10972 FieldDecl *Field 10973 = FieldDecl::Create(S.Context, RD, Loc, Loc, 0, FieldType, 10974 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 10975 0, false, ICIS_NoInit); 10976 Field->setImplicit(true); 10977 Field->setAccess(AS_private); 10978 RD->addDecl(Field); 10979 10980 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 10981 DeclRefType, VK_LValue, Loc); 10982 Var->setReferenced(true); 10983 Var->setUsed(true); 10984 10985 return Ref; 10986 } 10987 10988 /// \brief Capture the given variable in the given lambda expression. 10989 static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI, 10990 VarDecl *Var, QualType FieldType, 10991 QualType DeclRefType, 10992 SourceLocation Loc, 10993 bool RefersToEnclosingLocal) { 10994 CXXRecordDecl *Lambda = LSI->Lambda; 10995 10996 // Build the non-static data member. 10997 FieldDecl *Field 10998 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType, 10999 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 11000 0, false, ICIS_NoInit); 11001 Field->setImplicit(true); 11002 Field->setAccess(AS_private); 11003 Lambda->addDecl(Field); 11004 11005 // C++11 [expr.prim.lambda]p21: 11006 // When the lambda-expression is evaluated, the entities that 11007 // are captured by copy are used to direct-initialize each 11008 // corresponding non-static data member of the resulting closure 11009 // object. (For array members, the array elements are 11010 // direct-initialized in increasing subscript order.) These 11011 // initializations are performed in the (unspecified) order in 11012 // which the non-static data members are declared. 11013 11014 // Introduce a new evaluation context for the initialization, so 11015 // that temporaries introduced as part of the capture are retained 11016 // to be re-"exported" from the lambda expression itself. 11017 EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated); 11018 11019 // C++ [expr.prim.labda]p12: 11020 // An entity captured by a lambda-expression is odr-used (3.2) in 11021 // the scope containing the lambda-expression. 11022 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 11023 DeclRefType, VK_LValue, Loc); 11024 Var->setReferenced(true); 11025 Var->setUsed(true); 11026 11027 // When the field has array type, create index variables for each 11028 // dimension of the array. We use these index variables to subscript 11029 // the source array, and other clients (e.g., CodeGen) will perform 11030 // the necessary iteration with these index variables. 11031 SmallVector<VarDecl *, 4> IndexVariables; 11032 QualType BaseType = FieldType; 11033 QualType SizeType = S.Context.getSizeType(); 11034 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size()); 11035 while (const ConstantArrayType *Array 11036 = S.Context.getAsConstantArrayType(BaseType)) { 11037 // Create the iteration variable for this array index. 11038 IdentifierInfo *IterationVarName = 0; 11039 { 11040 SmallString<8> Str; 11041 llvm::raw_svector_ostream OS(Str); 11042 OS << "__i" << IndexVariables.size(); 11043 IterationVarName = &S.Context.Idents.get(OS.str()); 11044 } 11045 VarDecl *IterationVar 11046 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 11047 IterationVarName, SizeType, 11048 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 11049 SC_None); 11050 IndexVariables.push_back(IterationVar); 11051 LSI->ArrayIndexVars.push_back(IterationVar); 11052 11053 // Create a reference to the iteration variable. 11054 ExprResult IterationVarRef 11055 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 11056 assert(!IterationVarRef.isInvalid() && 11057 "Reference to invented variable cannot fail!"); 11058 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take()); 11059 assert(!IterationVarRef.isInvalid() && 11060 "Conversion of invented variable cannot fail!"); 11061 11062 // Subscript the array with this iteration variable. 11063 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr( 11064 Ref, Loc, IterationVarRef.take(), Loc); 11065 if (Subscript.isInvalid()) { 11066 S.CleanupVarDeclMarking(); 11067 S.DiscardCleanupsInEvaluationContext(); 11068 return ExprError(); 11069 } 11070 11071 Ref = Subscript.take(); 11072 BaseType = Array->getElementType(); 11073 } 11074 11075 // Construct the entity that we will be initializing. For an array, this 11076 // will be first element in the array, which may require several levels 11077 // of array-subscript entities. 11078 SmallVector<InitializedEntity, 4> Entities; 11079 Entities.reserve(1 + IndexVariables.size()); 11080 Entities.push_back( 11081 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc)); 11082 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 11083 Entities.push_back(InitializedEntity::InitializeElement(S.Context, 11084 0, 11085 Entities.back())); 11086 11087 InitializationKind InitKind 11088 = InitializationKind::CreateDirect(Loc, Loc, Loc); 11089 InitializationSequence Init(S, Entities.back(), InitKind, Ref); 11090 ExprResult Result(true); 11091 if (!Init.Diagnose(S, Entities.back(), InitKind, Ref)) 11092 Result = Init.Perform(S, Entities.back(), InitKind, Ref); 11093 11094 // If this initialization requires any cleanups (e.g., due to a 11095 // default argument to a copy constructor), note that for the 11096 // lambda. 11097 if (S.ExprNeedsCleanups) 11098 LSI->ExprNeedsCleanups = true; 11099 11100 // Exit the expression evaluation context used for the capture. 11101 S.CleanupVarDeclMarking(); 11102 S.DiscardCleanupsInEvaluationContext(); 11103 return Result; 11104 } 11105 11106 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 11107 TryCaptureKind Kind, SourceLocation EllipsisLoc, 11108 bool BuildAndDiagnose, 11109 QualType &CaptureType, 11110 QualType &DeclRefType) { 11111 bool Nested = false; 11112 11113 DeclContext *DC = CurContext; 11114 if (Var->getDeclContext() == DC) return true; 11115 if (!Var->hasLocalStorage()) return true; 11116 11117 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 11118 11119 // Walk up the stack to determine whether we can capture the variable, 11120 // performing the "simple" checks that don't depend on type. We stop when 11121 // we've either hit the declared scope of the variable or find an existing 11122 // capture of that variable. 11123 CaptureType = Var->getType(); 11124 DeclRefType = CaptureType.getNonReferenceType(); 11125 bool Explicit = (Kind != TryCapture_Implicit); 11126 unsigned FunctionScopesIndex = FunctionScopes.size() - 1; 11127 do { 11128 // Only block literals, captured statements, and lambda expressions can 11129 // capture; other scopes don't work. 11130 DeclContext *ParentDC; 11131 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) 11132 ParentDC = DC->getParent(); 11133 else if (isa<CXXMethodDecl>(DC) && 11134 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call && 11135 cast<CXXRecordDecl>(DC->getParent())->isLambda()) 11136 ParentDC = DC->getParent()->getParent(); 11137 else { 11138 if (BuildAndDiagnose) 11139 diagnoseUncapturableValueReference(*this, Loc, Var, DC); 11140 return true; 11141 } 11142 11143 CapturingScopeInfo *CSI = 11144 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]); 11145 11146 // Check whether we've already captured it. 11147 if (CSI->CaptureMap.count(Var)) { 11148 // If we found a capture, any subcaptures are nested. 11149 Nested = true; 11150 11151 // Retrieve the capture type for this variable. 11152 CaptureType = CSI->getCapture(Var).getCaptureType(); 11153 11154 // Compute the type of an expression that refers to this variable. 11155 DeclRefType = CaptureType.getNonReferenceType(); 11156 11157 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 11158 if (Cap.isCopyCapture() && 11159 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable)) 11160 DeclRefType.addConst(); 11161 break; 11162 } 11163 11164 bool IsBlock = isa<BlockScopeInfo>(CSI); 11165 bool IsLambda = isa<LambdaScopeInfo>(CSI); 11166 11167 // Lambdas are not allowed to capture unnamed variables 11168 // (e.g. anonymous unions). 11169 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 11170 // assuming that's the intent. 11171 if (IsLambda && !Var->getDeclName()) { 11172 if (BuildAndDiagnose) { 11173 Diag(Loc, diag::err_lambda_capture_anonymous_var); 11174 Diag(Var->getLocation(), diag::note_declared_at); 11175 } 11176 return true; 11177 } 11178 11179 // Prohibit variably-modified types; they're difficult to deal with. 11180 if (Var->getType()->isVariablyModifiedType()) { 11181 if (BuildAndDiagnose) { 11182 if (IsBlock) 11183 Diag(Loc, diag::err_ref_vm_type); 11184 else 11185 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName(); 11186 Diag(Var->getLocation(), diag::note_previous_decl) 11187 << Var->getDeclName(); 11188 } 11189 return true; 11190 } 11191 // Prohibit structs with flexible array members too. 11192 // We cannot capture what is in the tail end of the struct. 11193 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 11194 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 11195 if (BuildAndDiagnose) { 11196 if (IsBlock) 11197 Diag(Loc, diag::err_ref_flexarray_type); 11198 else 11199 Diag(Loc, diag::err_lambda_capture_flexarray_type) 11200 << Var->getDeclName(); 11201 Diag(Var->getLocation(), diag::note_previous_decl) 11202 << Var->getDeclName(); 11203 } 11204 return true; 11205 } 11206 } 11207 // Lambdas and captured statements are not allowed to capture __block 11208 // variables; they don't support the expected semantics. 11209 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 11210 if (BuildAndDiagnose) { 11211 Diag(Loc, diag::err_capture_block_variable) 11212 << Var->getDeclName() << !IsLambda; 11213 Diag(Var->getLocation(), diag::note_previous_decl) 11214 << Var->getDeclName(); 11215 } 11216 return true; 11217 } 11218 11219 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 11220 // No capture-default 11221 if (BuildAndDiagnose) { 11222 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName(); 11223 Diag(Var->getLocation(), diag::note_previous_decl) 11224 << Var->getDeclName(); 11225 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 11226 diag::note_lambda_decl); 11227 } 11228 return true; 11229 } 11230 11231 FunctionScopesIndex--; 11232 DC = ParentDC; 11233 Explicit = false; 11234 } while (!Var->getDeclContext()->Equals(DC)); 11235 11236 // Walk back down the scope stack, computing the type of the capture at 11237 // each step, checking type-specific requirements, and adding captures if 11238 // requested. 11239 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N; 11240 ++I) { 11241 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 11242 11243 // Compute the type of the capture and of a reference to the capture within 11244 // this scope. 11245 if (isa<BlockScopeInfo>(CSI)) { 11246 Expr *CopyExpr = 0; 11247 bool ByRef = false; 11248 11249 // Blocks are not allowed to capture arrays. 11250 if (CaptureType->isArrayType()) { 11251 if (BuildAndDiagnose) { 11252 Diag(Loc, diag::err_ref_array_type); 11253 Diag(Var->getLocation(), diag::note_previous_decl) 11254 << Var->getDeclName(); 11255 } 11256 return true; 11257 } 11258 11259 // Forbid the block-capture of autoreleasing variables. 11260 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 11261 if (BuildAndDiagnose) { 11262 Diag(Loc, diag::err_arc_autoreleasing_capture) 11263 << /*block*/ 0; 11264 Diag(Var->getLocation(), diag::note_previous_decl) 11265 << Var->getDeclName(); 11266 } 11267 return true; 11268 } 11269 11270 if (HasBlocksAttr || CaptureType->isReferenceType()) { 11271 // Block capture by reference does not change the capture or 11272 // declaration reference types. 11273 ByRef = true; 11274 } else { 11275 // Block capture by copy introduces 'const'. 11276 CaptureType = CaptureType.getNonReferenceType().withConst(); 11277 DeclRefType = CaptureType; 11278 11279 if (getLangOpts().CPlusPlus && BuildAndDiagnose) { 11280 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 11281 // The capture logic needs the destructor, so make sure we mark it. 11282 // Usually this is unnecessary because most local variables have 11283 // their destructors marked at declaration time, but parameters are 11284 // an exception because it's technically only the call site that 11285 // actually requires the destructor. 11286 if (isa<ParmVarDecl>(Var)) 11287 FinalizeVarWithDestructor(Var, Record); 11288 11289 // Enter a new evaluation context to insulate the copy 11290 // full-expression. 11291 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 11292 11293 // According to the blocks spec, the capture of a variable from 11294 // the stack requires a const copy constructor. This is not true 11295 // of the copy/move done to move a __block variable to the heap. 11296 Expr *DeclRef = new (Context) DeclRefExpr(Var, Nested, 11297 DeclRefType.withConst(), 11298 VK_LValue, Loc); 11299 11300 ExprResult Result 11301 = PerformCopyInitialization( 11302 InitializedEntity::InitializeBlock(Var->getLocation(), 11303 CaptureType, false), 11304 Loc, Owned(DeclRef)); 11305 11306 // Build a full-expression copy expression if initialization 11307 // succeeded and used a non-trivial constructor. Recover from 11308 // errors by pretending that the copy isn't necessary. 11309 if (!Result.isInvalid() && 11310 !cast<CXXConstructExpr>(Result.get())->getConstructor() 11311 ->isTrivial()) { 11312 Result = MaybeCreateExprWithCleanups(Result); 11313 CopyExpr = Result.take(); 11314 } 11315 } 11316 } 11317 } 11318 11319 // Actually capture the variable. 11320 if (BuildAndDiagnose) 11321 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 11322 SourceLocation(), CaptureType, CopyExpr); 11323 Nested = true; 11324 continue; 11325 } 11326 11327 if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 11328 // By default, capture variables by reference. 11329 bool ByRef = true; 11330 // Using an LValue reference type is consistent with Lambdas (see below). 11331 CaptureType = Context.getLValueReferenceType(DeclRefType); 11332 11333 Expr *CopyExpr = 0; 11334 if (BuildAndDiagnose) { 11335 ExprResult Result = captureInCapturedRegion(*this, RSI, Var, 11336 CaptureType, DeclRefType, 11337 Loc, Nested); 11338 if (!Result.isInvalid()) 11339 CopyExpr = Result.take(); 11340 } 11341 11342 // Actually capture the variable. 11343 if (BuildAndDiagnose) 11344 CSI->addCapture(Var, /*isBlock*/false, ByRef, Nested, Loc, 11345 SourceLocation(), CaptureType, CopyExpr); 11346 Nested = true; 11347 continue; 11348 } 11349 11350 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 11351 11352 // Determine whether we are capturing by reference or by value. 11353 bool ByRef = false; 11354 if (I == N - 1 && Kind != TryCapture_Implicit) { 11355 ByRef = (Kind == TryCapture_ExplicitByRef); 11356 } else { 11357 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 11358 } 11359 11360 // Compute the type of the field that will capture this variable. 11361 if (ByRef) { 11362 // C++11 [expr.prim.lambda]p15: 11363 // An entity is captured by reference if it is implicitly or 11364 // explicitly captured but not captured by copy. It is 11365 // unspecified whether additional unnamed non-static data 11366 // members are declared in the closure type for entities 11367 // captured by reference. 11368 // 11369 // FIXME: It is not clear whether we want to build an lvalue reference 11370 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 11371 // to do the former, while EDG does the latter. Core issue 1249 will 11372 // clarify, but for now we follow GCC because it's a more permissive and 11373 // easily defensible position. 11374 CaptureType = Context.getLValueReferenceType(DeclRefType); 11375 } else { 11376 // C++11 [expr.prim.lambda]p14: 11377 // For each entity captured by copy, an unnamed non-static 11378 // data member is declared in the closure type. The 11379 // declaration order of these members is unspecified. The type 11380 // of such a data member is the type of the corresponding 11381 // captured entity if the entity is not a reference to an 11382 // object, or the referenced type otherwise. [Note: If the 11383 // captured entity is a reference to a function, the 11384 // corresponding data member is also a reference to a 11385 // function. - end note ] 11386 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 11387 if (!RefType->getPointeeType()->isFunctionType()) 11388 CaptureType = RefType->getPointeeType(); 11389 } 11390 11391 // Forbid the lambda copy-capture of autoreleasing variables. 11392 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 11393 if (BuildAndDiagnose) { 11394 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 11395 Diag(Var->getLocation(), diag::note_previous_decl) 11396 << Var->getDeclName(); 11397 } 11398 return true; 11399 } 11400 } 11401 11402 // Capture this variable in the lambda. 11403 Expr *CopyExpr = 0; 11404 if (BuildAndDiagnose) { 11405 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType, 11406 DeclRefType, Loc, 11407 Nested); 11408 if (!Result.isInvalid()) 11409 CopyExpr = Result.take(); 11410 } 11411 11412 // Compute the type of a reference to this captured variable. 11413 if (ByRef) 11414 DeclRefType = CaptureType.getNonReferenceType(); 11415 else { 11416 // C++ [expr.prim.lambda]p5: 11417 // The closure type for a lambda-expression has a public inline 11418 // function call operator [...]. This function call operator is 11419 // declared const (9.3.1) if and only if the lambda-expression’s 11420 // parameter-declaration-clause is not followed by mutable. 11421 DeclRefType = CaptureType.getNonReferenceType(); 11422 if (!LSI->Mutable && !CaptureType->isReferenceType()) 11423 DeclRefType.addConst(); 11424 } 11425 11426 // Add the capture. 11427 if (BuildAndDiagnose) 11428 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc, 11429 EllipsisLoc, CaptureType, CopyExpr); 11430 Nested = true; 11431 } 11432 11433 return false; 11434 } 11435 11436 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 11437 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 11438 QualType CaptureType; 11439 QualType DeclRefType; 11440 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 11441 /*BuildAndDiagnose=*/true, CaptureType, 11442 DeclRefType); 11443 } 11444 11445 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 11446 QualType CaptureType; 11447 QualType DeclRefType; 11448 11449 // Determine whether we can capture this variable. 11450 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 11451 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType)) 11452 return QualType(); 11453 11454 return DeclRefType; 11455 } 11456 11457 static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var, 11458 SourceLocation Loc) { 11459 // Keep track of used but undefined variables. 11460 // FIXME: We shouldn't suppress this warning for static data members. 11461 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 11462 Var->getLinkage() != ExternalLinkage && 11463 !(Var->isStaticDataMember() && Var->hasInit())) { 11464 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 11465 if (old.isInvalid()) old = Loc; 11466 } 11467 11468 SemaRef.tryCaptureVariable(Var, Loc); 11469 11470 Var->setUsed(true); 11471 } 11472 11473 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 11474 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 11475 // an object that satisfies the requirements for appearing in a 11476 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 11477 // is immediately applied." This function handles the lvalue-to-rvalue 11478 // conversion part. 11479 MaybeODRUseExprs.erase(E->IgnoreParens()); 11480 } 11481 11482 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 11483 if (!Res.isUsable()) 11484 return Res; 11485 11486 // If a constant-expression is a reference to a variable where we delay 11487 // deciding whether it is an odr-use, just assume we will apply the 11488 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 11489 // (a non-type template argument), we have special handling anyway. 11490 UpdateMarkingForLValueToRValue(Res.get()); 11491 return Res; 11492 } 11493 11494 void Sema::CleanupVarDeclMarking() { 11495 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(), 11496 e = MaybeODRUseExprs.end(); 11497 i != e; ++i) { 11498 VarDecl *Var; 11499 SourceLocation Loc; 11500 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) { 11501 Var = cast<VarDecl>(DRE->getDecl()); 11502 Loc = DRE->getLocation(); 11503 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) { 11504 Var = cast<VarDecl>(ME->getMemberDecl()); 11505 Loc = ME->getMemberLoc(); 11506 } else { 11507 llvm_unreachable("Unexpcted expression"); 11508 } 11509 11510 MarkVarDeclODRUsed(*this, Var, Loc); 11511 } 11512 11513 MaybeODRUseExprs.clear(); 11514 } 11515 11516 // Mark a VarDecl referenced, and perform the necessary handling to compute 11517 // odr-uses. 11518 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 11519 VarDecl *Var, Expr *E) { 11520 Var->setReferenced(); 11521 11522 if (!IsPotentiallyEvaluatedContext(SemaRef)) 11523 return; 11524 11525 // Implicit instantiation of static data members of class templates. 11526 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) { 11527 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo(); 11528 assert(MSInfo && "Missing member specialization information?"); 11529 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid(); 11530 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation && 11531 (!AlreadyInstantiated || 11532 Var->isUsableInConstantExpressions(SemaRef.Context))) { 11533 if (!AlreadyInstantiated) { 11534 // This is a modification of an existing AST node. Notify listeners. 11535 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 11536 L->StaticDataMemberInstantiated(Var); 11537 MSInfo->setPointOfInstantiation(Loc); 11538 } 11539 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation(); 11540 if (Var->isUsableInConstantExpressions(SemaRef.Context)) 11541 // Do not defer instantiations of variables which could be used in a 11542 // constant expression. 11543 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var); 11544 else 11545 SemaRef.PendingInstantiations.push_back( 11546 std::make_pair(Var, PointOfInstantiation)); 11547 } 11548 } 11549 11550 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 11551 // the requirements for appearing in a constant expression (5.19) and, if 11552 // it is an object, the lvalue-to-rvalue conversion (4.1) 11553 // is immediately applied." We check the first part here, and 11554 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 11555 // Note that we use the C++11 definition everywhere because nothing in 11556 // C++03 depends on whether we get the C++03 version correct. The second 11557 // part does not apply to references, since they are not objects. 11558 const VarDecl *DefVD; 11559 if (E && !isa<ParmVarDecl>(Var) && 11560 Var->isUsableInConstantExpressions(SemaRef.Context) && 11561 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE()) { 11562 if (!Var->getType()->isReferenceType()) 11563 SemaRef.MaybeODRUseExprs.insert(E); 11564 } else 11565 MarkVarDeclODRUsed(SemaRef, Var, Loc); 11566 } 11567 11568 /// \brief Mark a variable referenced, and check whether it is odr-used 11569 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 11570 /// used directly for normal expressions referring to VarDecl. 11571 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 11572 DoMarkVarDeclReferenced(*this, Loc, Var, 0); 11573 } 11574 11575 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 11576 Decl *D, Expr *E, bool OdrUse) { 11577 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 11578 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 11579 return; 11580 } 11581 11582 SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse); 11583 11584 // If this is a call to a method via a cast, also mark the method in the 11585 // derived class used in case codegen can devirtualize the call. 11586 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 11587 if (!ME) 11588 return; 11589 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 11590 if (!MD) 11591 return; 11592 const Expr *Base = ME->getBase(); 11593 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 11594 if (!MostDerivedClassDecl) 11595 return; 11596 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 11597 if (!DM || DM->isPure()) 11598 return; 11599 SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse); 11600 } 11601 11602 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 11603 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 11604 // TODO: update this with DR# once a defect report is filed. 11605 // C++11 defect. The address of a pure member should not be an ODR use, even 11606 // if it's a qualified reference. 11607 bool OdrUse = true; 11608 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 11609 if (Method->isVirtual()) 11610 OdrUse = false; 11611 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 11612 } 11613 11614 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 11615 void Sema::MarkMemberReferenced(MemberExpr *E) { 11616 // C++11 [basic.def.odr]p2: 11617 // A non-overloaded function whose name appears as a potentially-evaluated 11618 // expression or a member of a set of candidate functions, if selected by 11619 // overload resolution when referred to from a potentially-evaluated 11620 // expression, is odr-used, unless it is a pure virtual function and its 11621 // name is not explicitly qualified. 11622 bool OdrUse = true; 11623 if (!E->hasQualifier()) { 11624 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 11625 if (Method->isPure()) 11626 OdrUse = false; 11627 } 11628 SourceLocation Loc = E->getMemberLoc().isValid() ? 11629 E->getMemberLoc() : E->getLocStart(); 11630 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse); 11631 } 11632 11633 /// \brief Perform marking for a reference to an arbitrary declaration. It 11634 /// marks the declaration referenced, and performs odr-use checking for functions 11635 /// and variables. This method should not be used when building an normal 11636 /// expression which refers to a variable. 11637 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) { 11638 if (OdrUse) { 11639 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 11640 MarkVariableReferenced(Loc, VD); 11641 return; 11642 } 11643 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 11644 MarkFunctionReferenced(Loc, FD); 11645 return; 11646 } 11647 } 11648 D->setReferenced(); 11649 } 11650 11651 namespace { 11652 // Mark all of the declarations referenced 11653 // FIXME: Not fully implemented yet! We need to have a better understanding 11654 // of when we're entering 11655 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 11656 Sema &S; 11657 SourceLocation Loc; 11658 11659 public: 11660 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 11661 11662 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 11663 11664 bool TraverseTemplateArgument(const TemplateArgument &Arg); 11665 bool TraverseRecordType(RecordType *T); 11666 }; 11667 } 11668 11669 bool MarkReferencedDecls::TraverseTemplateArgument( 11670 const TemplateArgument &Arg) { 11671 if (Arg.getKind() == TemplateArgument::Declaration) { 11672 if (Decl *D = Arg.getAsDecl()) 11673 S.MarkAnyDeclReferenced(Loc, D, true); 11674 } 11675 11676 return Inherited::TraverseTemplateArgument(Arg); 11677 } 11678 11679 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 11680 if (ClassTemplateSpecializationDecl *Spec 11681 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 11682 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 11683 return TraverseTemplateArguments(Args.data(), Args.size()); 11684 } 11685 11686 return true; 11687 } 11688 11689 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 11690 MarkReferencedDecls Marker(*this, Loc); 11691 Marker.TraverseType(Context.getCanonicalType(T)); 11692 } 11693 11694 namespace { 11695 /// \brief Helper class that marks all of the declarations referenced by 11696 /// potentially-evaluated subexpressions as "referenced". 11697 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 11698 Sema &S; 11699 bool SkipLocalVariables; 11700 11701 public: 11702 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 11703 11704 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 11705 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 11706 11707 void VisitDeclRefExpr(DeclRefExpr *E) { 11708 // If we were asked not to visit local variables, don't. 11709 if (SkipLocalVariables) { 11710 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 11711 if (VD->hasLocalStorage()) 11712 return; 11713 } 11714 11715 S.MarkDeclRefReferenced(E); 11716 } 11717 11718 void VisitMemberExpr(MemberExpr *E) { 11719 S.MarkMemberReferenced(E); 11720 Inherited::VisitMemberExpr(E); 11721 } 11722 11723 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 11724 S.MarkFunctionReferenced(E->getLocStart(), 11725 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 11726 Visit(E->getSubExpr()); 11727 } 11728 11729 void VisitCXXNewExpr(CXXNewExpr *E) { 11730 if (E->getOperatorNew()) 11731 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 11732 if (E->getOperatorDelete()) 11733 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 11734 Inherited::VisitCXXNewExpr(E); 11735 } 11736 11737 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 11738 if (E->getOperatorDelete()) 11739 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 11740 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 11741 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 11742 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 11743 S.MarkFunctionReferenced(E->getLocStart(), 11744 S.LookupDestructor(Record)); 11745 } 11746 11747 Inherited::VisitCXXDeleteExpr(E); 11748 } 11749 11750 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11751 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 11752 Inherited::VisitCXXConstructExpr(E); 11753 } 11754 11755 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 11756 Visit(E->getExpr()); 11757 } 11758 11759 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11760 Inherited::VisitImplicitCastExpr(E); 11761 11762 if (E->getCastKind() == CK_LValueToRValue) 11763 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 11764 } 11765 }; 11766 } 11767 11768 /// \brief Mark any declarations that appear within this expression or any 11769 /// potentially-evaluated subexpressions as "referenced". 11770 /// 11771 /// \param SkipLocalVariables If true, don't mark local variables as 11772 /// 'referenced'. 11773 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 11774 bool SkipLocalVariables) { 11775 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 11776 } 11777 11778 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 11779 /// of the program being compiled. 11780 /// 11781 /// This routine emits the given diagnostic when the code currently being 11782 /// type-checked is "potentially evaluated", meaning that there is a 11783 /// possibility that the code will actually be executable. Code in sizeof() 11784 /// expressions, code used only during overload resolution, etc., are not 11785 /// potentially evaluated. This routine will suppress such diagnostics or, 11786 /// in the absolutely nutty case of potentially potentially evaluated 11787 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 11788 /// later. 11789 /// 11790 /// This routine should be used for all diagnostics that describe the run-time 11791 /// behavior of a program, such as passing a non-POD value through an ellipsis. 11792 /// Failure to do so will likely result in spurious diagnostics or failures 11793 /// during overload resolution or within sizeof/alignof/typeof/typeid. 11794 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 11795 const PartialDiagnostic &PD) { 11796 switch (ExprEvalContexts.back().Context) { 11797 case Unevaluated: 11798 case UnevaluatedAbstract: 11799 // The argument will never be evaluated, so don't complain. 11800 break; 11801 11802 case ConstantEvaluated: 11803 // Relevant diagnostics should be produced by constant evaluation. 11804 break; 11805 11806 case PotentiallyEvaluated: 11807 case PotentiallyEvaluatedIfUsed: 11808 if (Statement && getCurFunctionOrMethodDecl()) { 11809 FunctionScopes.back()->PossiblyUnreachableDiags. 11810 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 11811 } 11812 else 11813 Diag(Loc, PD); 11814 11815 return true; 11816 } 11817 11818 return false; 11819 } 11820 11821 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 11822 CallExpr *CE, FunctionDecl *FD) { 11823 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 11824 return false; 11825 11826 // If we're inside a decltype's expression, don't check for a valid return 11827 // type or construct temporaries until we know whether this is the last call. 11828 if (ExprEvalContexts.back().IsDecltype) { 11829 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 11830 return false; 11831 } 11832 11833 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 11834 FunctionDecl *FD; 11835 CallExpr *CE; 11836 11837 public: 11838 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 11839 : FD(FD), CE(CE) { } 11840 11841 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 11842 if (!FD) { 11843 S.Diag(Loc, diag::err_call_incomplete_return) 11844 << T << CE->getSourceRange(); 11845 return; 11846 } 11847 11848 S.Diag(Loc, diag::err_call_function_incomplete_return) 11849 << CE->getSourceRange() << FD->getDeclName() << T; 11850 S.Diag(FD->getLocation(), 11851 diag::note_function_with_incomplete_return_type_declared_here) 11852 << FD->getDeclName(); 11853 } 11854 } Diagnoser(FD, CE); 11855 11856 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 11857 return true; 11858 11859 return false; 11860 } 11861 11862 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 11863 // will prevent this condition from triggering, which is what we want. 11864 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 11865 SourceLocation Loc; 11866 11867 unsigned diagnostic = diag::warn_condition_is_assignment; 11868 bool IsOrAssign = false; 11869 11870 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 11871 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 11872 return; 11873 11874 IsOrAssign = Op->getOpcode() == BO_OrAssign; 11875 11876 // Greylist some idioms by putting them into a warning subcategory. 11877 if (ObjCMessageExpr *ME 11878 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 11879 Selector Sel = ME->getSelector(); 11880 11881 // self = [<foo> init...] 11882 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init")) 11883 diagnostic = diag::warn_condition_is_idiomatic_assignment; 11884 11885 // <foo> = [<bar> nextObject] 11886 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 11887 diagnostic = diag::warn_condition_is_idiomatic_assignment; 11888 } 11889 11890 Loc = Op->getOperatorLoc(); 11891 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 11892 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 11893 return; 11894 11895 IsOrAssign = Op->getOperator() == OO_PipeEqual; 11896 Loc = Op->getOperatorLoc(); 11897 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 11898 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 11899 else { 11900 // Not an assignment. 11901 return; 11902 } 11903 11904 Diag(Loc, diagnostic) << E->getSourceRange(); 11905 11906 SourceLocation Open = E->getLocStart(); 11907 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd()); 11908 Diag(Loc, diag::note_condition_assign_silence) 11909 << FixItHint::CreateInsertion(Open, "(") 11910 << FixItHint::CreateInsertion(Close, ")"); 11911 11912 if (IsOrAssign) 11913 Diag(Loc, diag::note_condition_or_assign_to_comparison) 11914 << FixItHint::CreateReplacement(Loc, "!="); 11915 else 11916 Diag(Loc, diag::note_condition_assign_to_comparison) 11917 << FixItHint::CreateReplacement(Loc, "=="); 11918 } 11919 11920 /// \brief Redundant parentheses over an equality comparison can indicate 11921 /// that the user intended an assignment used as condition. 11922 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 11923 // Don't warn if the parens came from a macro. 11924 SourceLocation parenLoc = ParenE->getLocStart(); 11925 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 11926 return; 11927 // Don't warn for dependent expressions. 11928 if (ParenE->isTypeDependent()) 11929 return; 11930 11931 Expr *E = ParenE->IgnoreParens(); 11932 11933 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 11934 if (opE->getOpcode() == BO_EQ && 11935 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 11936 == Expr::MLV_Valid) { 11937 SourceLocation Loc = opE->getOperatorLoc(); 11938 11939 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 11940 SourceRange ParenERange = ParenE->getSourceRange(); 11941 Diag(Loc, diag::note_equality_comparison_silence) 11942 << FixItHint::CreateRemoval(ParenERange.getBegin()) 11943 << FixItHint::CreateRemoval(ParenERange.getEnd()); 11944 Diag(Loc, diag::note_equality_comparison_to_assign) 11945 << FixItHint::CreateReplacement(Loc, "="); 11946 } 11947 } 11948 11949 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) { 11950 DiagnoseAssignmentAsCondition(E); 11951 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 11952 DiagnoseEqualityWithExtraParens(parenE); 11953 11954 ExprResult result = CheckPlaceholderExpr(E); 11955 if (result.isInvalid()) return ExprError(); 11956 E = result.take(); 11957 11958 if (!E->isTypeDependent()) { 11959 if (getLangOpts().CPlusPlus) 11960 return CheckCXXBooleanCondition(E); // C++ 6.4p4 11961 11962 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 11963 if (ERes.isInvalid()) 11964 return ExprError(); 11965 E = ERes.take(); 11966 11967 QualType T = E->getType(); 11968 if (!T->isScalarType()) { // C99 6.8.4.1p1 11969 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 11970 << T << E->getSourceRange(); 11971 return ExprError(); 11972 } 11973 } 11974 11975 return Owned(E); 11976 } 11977 11978 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc, 11979 Expr *SubExpr) { 11980 if (!SubExpr) 11981 return ExprError(); 11982 11983 return CheckBooleanCondition(SubExpr, Loc); 11984 } 11985 11986 namespace { 11987 /// A visitor for rebuilding a call to an __unknown_any expression 11988 /// to have an appropriate type. 11989 struct RebuildUnknownAnyFunction 11990 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 11991 11992 Sema &S; 11993 11994 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 11995 11996 ExprResult VisitStmt(Stmt *S) { 11997 llvm_unreachable("unexpected statement!"); 11998 } 11999 12000 ExprResult VisitExpr(Expr *E) { 12001 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 12002 << E->getSourceRange(); 12003 return ExprError(); 12004 } 12005 12006 /// Rebuild an expression which simply semantically wraps another 12007 /// expression which it shares the type and value kind of. 12008 template <class T> ExprResult rebuildSugarExpr(T *E) { 12009 ExprResult SubResult = Visit(E->getSubExpr()); 12010 if (SubResult.isInvalid()) return ExprError(); 12011 12012 Expr *SubExpr = SubResult.take(); 12013 E->setSubExpr(SubExpr); 12014 E->setType(SubExpr->getType()); 12015 E->setValueKind(SubExpr->getValueKind()); 12016 assert(E->getObjectKind() == OK_Ordinary); 12017 return E; 12018 } 12019 12020 ExprResult VisitParenExpr(ParenExpr *E) { 12021 return rebuildSugarExpr(E); 12022 } 12023 12024 ExprResult VisitUnaryExtension(UnaryOperator *E) { 12025 return rebuildSugarExpr(E); 12026 } 12027 12028 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 12029 ExprResult SubResult = Visit(E->getSubExpr()); 12030 if (SubResult.isInvalid()) return ExprError(); 12031 12032 Expr *SubExpr = SubResult.take(); 12033 E->setSubExpr(SubExpr); 12034 E->setType(S.Context.getPointerType(SubExpr->getType())); 12035 assert(E->getValueKind() == VK_RValue); 12036 assert(E->getObjectKind() == OK_Ordinary); 12037 return E; 12038 } 12039 12040 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 12041 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 12042 12043 E->setType(VD->getType()); 12044 12045 assert(E->getValueKind() == VK_RValue); 12046 if (S.getLangOpts().CPlusPlus && 12047 !(isa<CXXMethodDecl>(VD) && 12048 cast<CXXMethodDecl>(VD)->isInstance())) 12049 E->setValueKind(VK_LValue); 12050 12051 return E; 12052 } 12053 12054 ExprResult VisitMemberExpr(MemberExpr *E) { 12055 return resolveDecl(E, E->getMemberDecl()); 12056 } 12057 12058 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 12059 return resolveDecl(E, E->getDecl()); 12060 } 12061 }; 12062 } 12063 12064 /// Given a function expression of unknown-any type, try to rebuild it 12065 /// to have a function type. 12066 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 12067 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 12068 if (Result.isInvalid()) return ExprError(); 12069 return S.DefaultFunctionArrayConversion(Result.take()); 12070 } 12071 12072 namespace { 12073 /// A visitor for rebuilding an expression of type __unknown_anytype 12074 /// into one which resolves the type directly on the referring 12075 /// expression. Strict preservation of the original source 12076 /// structure is not a goal. 12077 struct RebuildUnknownAnyExpr 12078 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 12079 12080 Sema &S; 12081 12082 /// The current destination type. 12083 QualType DestType; 12084 12085 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 12086 : S(S), DestType(CastType) {} 12087 12088 ExprResult VisitStmt(Stmt *S) { 12089 llvm_unreachable("unexpected statement!"); 12090 } 12091 12092 ExprResult VisitExpr(Expr *E) { 12093 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 12094 << E->getSourceRange(); 12095 return ExprError(); 12096 } 12097 12098 ExprResult VisitCallExpr(CallExpr *E); 12099 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 12100 12101 /// Rebuild an expression which simply semantically wraps another 12102 /// expression which it shares the type and value kind of. 12103 template <class T> ExprResult rebuildSugarExpr(T *E) { 12104 ExprResult SubResult = Visit(E->getSubExpr()); 12105 if (SubResult.isInvalid()) return ExprError(); 12106 Expr *SubExpr = SubResult.take(); 12107 E->setSubExpr(SubExpr); 12108 E->setType(SubExpr->getType()); 12109 E->setValueKind(SubExpr->getValueKind()); 12110 assert(E->getObjectKind() == OK_Ordinary); 12111 return E; 12112 } 12113 12114 ExprResult VisitParenExpr(ParenExpr *E) { 12115 return rebuildSugarExpr(E); 12116 } 12117 12118 ExprResult VisitUnaryExtension(UnaryOperator *E) { 12119 return rebuildSugarExpr(E); 12120 } 12121 12122 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 12123 const PointerType *Ptr = DestType->getAs<PointerType>(); 12124 if (!Ptr) { 12125 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 12126 << E->getSourceRange(); 12127 return ExprError(); 12128 } 12129 assert(E->getValueKind() == VK_RValue); 12130 assert(E->getObjectKind() == OK_Ordinary); 12131 E->setType(DestType); 12132 12133 // Build the sub-expression as if it were an object of the pointee type. 12134 DestType = Ptr->getPointeeType(); 12135 ExprResult SubResult = Visit(E->getSubExpr()); 12136 if (SubResult.isInvalid()) return ExprError(); 12137 E->setSubExpr(SubResult.take()); 12138 return E; 12139 } 12140 12141 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 12142 12143 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 12144 12145 ExprResult VisitMemberExpr(MemberExpr *E) { 12146 return resolveDecl(E, E->getMemberDecl()); 12147 } 12148 12149 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 12150 return resolveDecl(E, E->getDecl()); 12151 } 12152 }; 12153 } 12154 12155 /// Rebuilds a call expression which yielded __unknown_anytype. 12156 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 12157 Expr *CalleeExpr = E->getCallee(); 12158 12159 enum FnKind { 12160 FK_MemberFunction, 12161 FK_FunctionPointer, 12162 FK_BlockPointer 12163 }; 12164 12165 FnKind Kind; 12166 QualType CalleeType = CalleeExpr->getType(); 12167 if (CalleeType == S.Context.BoundMemberTy) { 12168 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 12169 Kind = FK_MemberFunction; 12170 CalleeType = Expr::findBoundMemberType(CalleeExpr); 12171 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 12172 CalleeType = Ptr->getPointeeType(); 12173 Kind = FK_FunctionPointer; 12174 } else { 12175 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 12176 Kind = FK_BlockPointer; 12177 } 12178 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 12179 12180 // Verify that this is a legal result type of a function. 12181 if (DestType->isArrayType() || DestType->isFunctionType()) { 12182 unsigned diagID = diag::err_func_returning_array_function; 12183 if (Kind == FK_BlockPointer) 12184 diagID = diag::err_block_returning_array_function; 12185 12186 S.Diag(E->getExprLoc(), diagID) 12187 << DestType->isFunctionType() << DestType; 12188 return ExprError(); 12189 } 12190 12191 // Otherwise, go ahead and set DestType as the call's result. 12192 E->setType(DestType.getNonLValueExprType(S.Context)); 12193 E->setValueKind(Expr::getValueKindForType(DestType)); 12194 assert(E->getObjectKind() == OK_Ordinary); 12195 12196 // Rebuild the function type, replacing the result type with DestType. 12197 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType)) 12198 DestType = 12199 S.Context.getFunctionType(DestType, 12200 ArrayRef<QualType>(Proto->arg_type_begin(), 12201 Proto->getNumArgs()), 12202 Proto->getExtProtoInfo()); 12203 else 12204 DestType = S.Context.getFunctionNoProtoType(DestType, 12205 FnType->getExtInfo()); 12206 12207 // Rebuild the appropriate pointer-to-function type. 12208 switch (Kind) { 12209 case FK_MemberFunction: 12210 // Nothing to do. 12211 break; 12212 12213 case FK_FunctionPointer: 12214 DestType = S.Context.getPointerType(DestType); 12215 break; 12216 12217 case FK_BlockPointer: 12218 DestType = S.Context.getBlockPointerType(DestType); 12219 break; 12220 } 12221 12222 // Finally, we can recurse. 12223 ExprResult CalleeResult = Visit(CalleeExpr); 12224 if (!CalleeResult.isUsable()) return ExprError(); 12225 E->setCallee(CalleeResult.take()); 12226 12227 // Bind a temporary if necessary. 12228 return S.MaybeBindToTemporary(E); 12229 } 12230 12231 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 12232 // Verify that this is a legal result type of a call. 12233 if (DestType->isArrayType() || DestType->isFunctionType()) { 12234 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 12235 << DestType->isFunctionType() << DestType; 12236 return ExprError(); 12237 } 12238 12239 // Rewrite the method result type if available. 12240 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 12241 assert(Method->getResultType() == S.Context.UnknownAnyTy); 12242 Method->setResultType(DestType); 12243 } 12244 12245 // Change the type of the message. 12246 E->setType(DestType.getNonReferenceType()); 12247 E->setValueKind(Expr::getValueKindForType(DestType)); 12248 12249 return S.MaybeBindToTemporary(E); 12250 } 12251 12252 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 12253 // The only case we should ever see here is a function-to-pointer decay. 12254 if (E->getCastKind() == CK_FunctionToPointerDecay) { 12255 assert(E->getValueKind() == VK_RValue); 12256 assert(E->getObjectKind() == OK_Ordinary); 12257 12258 E->setType(DestType); 12259 12260 // Rebuild the sub-expression as the pointee (function) type. 12261 DestType = DestType->castAs<PointerType>()->getPointeeType(); 12262 12263 ExprResult Result = Visit(E->getSubExpr()); 12264 if (!Result.isUsable()) return ExprError(); 12265 12266 E->setSubExpr(Result.take()); 12267 return S.Owned(E); 12268 } else if (E->getCastKind() == CK_LValueToRValue) { 12269 assert(E->getValueKind() == VK_RValue); 12270 assert(E->getObjectKind() == OK_Ordinary); 12271 12272 assert(isa<BlockPointerType>(E->getType())); 12273 12274 E->setType(DestType); 12275 12276 // The sub-expression has to be a lvalue reference, so rebuild it as such. 12277 DestType = S.Context.getLValueReferenceType(DestType); 12278 12279 ExprResult Result = Visit(E->getSubExpr()); 12280 if (!Result.isUsable()) return ExprError(); 12281 12282 E->setSubExpr(Result.take()); 12283 return S.Owned(E); 12284 } else { 12285 llvm_unreachable("Unhandled cast type!"); 12286 } 12287 } 12288 12289 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 12290 ExprValueKind ValueKind = VK_LValue; 12291 QualType Type = DestType; 12292 12293 // We know how to make this work for certain kinds of decls: 12294 12295 // - functions 12296 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 12297 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 12298 DestType = Ptr->getPointeeType(); 12299 ExprResult Result = resolveDecl(E, VD); 12300 if (Result.isInvalid()) return ExprError(); 12301 return S.ImpCastExprToType(Result.take(), Type, 12302 CK_FunctionToPointerDecay, VK_RValue); 12303 } 12304 12305 if (!Type->isFunctionType()) { 12306 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 12307 << VD << E->getSourceRange(); 12308 return ExprError(); 12309 } 12310 12311 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 12312 if (MD->isInstance()) { 12313 ValueKind = VK_RValue; 12314 Type = S.Context.BoundMemberTy; 12315 } 12316 12317 // Function references aren't l-values in C. 12318 if (!S.getLangOpts().CPlusPlus) 12319 ValueKind = VK_RValue; 12320 12321 // - variables 12322 } else if (isa<VarDecl>(VD)) { 12323 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 12324 Type = RefTy->getPointeeType(); 12325 } else if (Type->isFunctionType()) { 12326 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 12327 << VD << E->getSourceRange(); 12328 return ExprError(); 12329 } 12330 12331 // - nothing else 12332 } else { 12333 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 12334 << VD << E->getSourceRange(); 12335 return ExprError(); 12336 } 12337 12338 VD->setType(DestType); 12339 E->setType(Type); 12340 E->setValueKind(ValueKind); 12341 return S.Owned(E); 12342 } 12343 12344 /// Check a cast of an unknown-any type. We intentionally only 12345 /// trigger this for C-style casts. 12346 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 12347 Expr *CastExpr, CastKind &CastKind, 12348 ExprValueKind &VK, CXXCastPath &Path) { 12349 // Rewrite the casted expression from scratch. 12350 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 12351 if (!result.isUsable()) return ExprError(); 12352 12353 CastExpr = result.take(); 12354 VK = CastExpr->getValueKind(); 12355 CastKind = CK_NoOp; 12356 12357 return CastExpr; 12358 } 12359 12360 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 12361 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 12362 } 12363 12364 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 12365 Expr *arg, QualType ¶mType) { 12366 // If the syntactic form of the argument is not an explicit cast of 12367 // any sort, just do default argument promotion. 12368 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 12369 if (!castArg) { 12370 ExprResult result = DefaultArgumentPromotion(arg); 12371 if (result.isInvalid()) return ExprError(); 12372 paramType = result.get()->getType(); 12373 return result; 12374 } 12375 12376 // Otherwise, use the type that was written in the explicit cast. 12377 assert(!arg->hasPlaceholderType()); 12378 paramType = castArg->getTypeAsWritten(); 12379 12380 // Copy-initialize a parameter of that type. 12381 InitializedEntity entity = 12382 InitializedEntity::InitializeParameter(Context, paramType, 12383 /*consumed*/ false); 12384 return PerformCopyInitialization(entity, callLoc, Owned(arg)); 12385 } 12386 12387 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 12388 Expr *orig = E; 12389 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 12390 while (true) { 12391 E = E->IgnoreParenImpCasts(); 12392 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 12393 E = call->getCallee(); 12394 diagID = diag::err_uncasted_call_of_unknown_any; 12395 } else { 12396 break; 12397 } 12398 } 12399 12400 SourceLocation loc; 12401 NamedDecl *d; 12402 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 12403 loc = ref->getLocation(); 12404 d = ref->getDecl(); 12405 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 12406 loc = mem->getMemberLoc(); 12407 d = mem->getMemberDecl(); 12408 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 12409 diagID = diag::err_uncasted_call_of_unknown_any; 12410 loc = msg->getSelectorStartLoc(); 12411 d = msg->getMethodDecl(); 12412 if (!d) { 12413 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 12414 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 12415 << orig->getSourceRange(); 12416 return ExprError(); 12417 } 12418 } else { 12419 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 12420 << E->getSourceRange(); 12421 return ExprError(); 12422 } 12423 12424 S.Diag(loc, diagID) << d << orig->getSourceRange(); 12425 12426 // Never recoverable. 12427 return ExprError(); 12428 } 12429 12430 /// Check for operands with placeholder types and complain if found. 12431 /// Returns true if there was an error and no recovery was possible. 12432 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 12433 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 12434 if (!placeholderType) return Owned(E); 12435 12436 switch (placeholderType->getKind()) { 12437 12438 // Overloaded expressions. 12439 case BuiltinType::Overload: { 12440 // Try to resolve a single function template specialization. 12441 // This is obligatory. 12442 ExprResult result = Owned(E); 12443 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) { 12444 return result; 12445 12446 // If that failed, try to recover with a call. 12447 } else { 12448 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable), 12449 /*complain*/ true); 12450 return result; 12451 } 12452 } 12453 12454 // Bound member functions. 12455 case BuiltinType::BoundMember: { 12456 ExprResult result = Owned(E); 12457 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function), 12458 /*complain*/ true); 12459 return result; 12460 } 12461 12462 // ARC unbridged casts. 12463 case BuiltinType::ARCUnbridgedCast: { 12464 Expr *realCast = stripARCUnbridgedCast(E); 12465 diagnoseARCUnbridgedCast(realCast); 12466 return Owned(realCast); 12467 } 12468 12469 // Expressions of unknown type. 12470 case BuiltinType::UnknownAny: 12471 return diagnoseUnknownAnyExpr(*this, E); 12472 12473 // Pseudo-objects. 12474 case BuiltinType::PseudoObject: 12475 return checkPseudoObjectRValue(E); 12476 12477 case BuiltinType::BuiltinFn: 12478 Diag(E->getLocStart(), diag::err_builtin_fn_use); 12479 return ExprError(); 12480 12481 // Everything else should be impossible. 12482 #define BUILTIN_TYPE(Id, SingletonId) \ 12483 case BuiltinType::Id: 12484 #define PLACEHOLDER_TYPE(Id, SingletonId) 12485 #include "clang/AST/BuiltinTypes.def" 12486 break; 12487 } 12488 12489 llvm_unreachable("invalid placeholder type!"); 12490 } 12491 12492 bool Sema::CheckCaseExpression(Expr *E) { 12493 if (E->isTypeDependent()) 12494 return true; 12495 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 12496 return E->getType()->isIntegralOrEnumerationType(); 12497 return false; 12498 } 12499 12500 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 12501 ExprResult 12502 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 12503 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 12504 "Unknown Objective-C Boolean value!"); 12505 QualType BoolT = Context.ObjCBuiltinBoolTy; 12506 if (!Context.getBOOLDecl()) { 12507 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 12508 Sema::LookupOrdinaryName); 12509 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 12510 NamedDecl *ND = Result.getFoundDecl(); 12511 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 12512 Context.setBOOLDecl(TD); 12513 } 12514 } 12515 if (Context.getBOOLDecl()) 12516 BoolT = Context.getBOOLType(); 12517 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, 12518 BoolT, OpLoc)); 12519 } 12520